preprocessor directives
TRANSCRIPT
Function
Introduction� A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself.
� This is called structured programming.
� These parts are made into functions in C.� These parts are made into functions in C.� main() then uses these functions to solve the original problem.
2 Dept. of CSE&IT, DBCET, Guwahati
Definition� A function is a named, independent section of C code that performs a specific task and optionally returns a value to the calling program or/and receives values(s) from the calling program.
3 Dept. of CSE&IT, DBCET, Guwahati
Categories of Function� Basically there are two categories of function:
1. Predefined functions: available in C / C++ standard library such as stdio.h, math.h, string.h etc.
2. User-defined functions: functions that programmers create for specialized tasks such as graphic and multimedia for specialized tasks such as graphic and multimedia libraries, implementation extensions or dependent etc.
4 Dept. of CSE&IT, DBCET, Guwahati
Function Characteristics� Basically a function has the following characteristics:
1. Named with unique name .
2. Performs a specific task -Task is a discrete job that the program must perform as part of its overall operation, such as sending a line of text to the printer, sorting an array into numerical order, or calculating a cube root, etc.calculating a cube root, etc.
3. Independent -A function can perform its task without interference from or interfering with other parts of the program.
4. May receive values from the calling program (caller) -Calling program can pass values to function for processing whether directly or indirectly (by reference).
5. May return a value to the calling program – the called function may pass something back to the calling program.
5 Dept. of CSE&IT, DBCET, Guwahati
Advantages of Function
� Functions separates the concept (what is done) from the implementation (how it is done).
� Functions make programs easier to understand.
� Functions can be called several times in the same � Functions can be called several times in the same program, allowing the code to be reused.
6 Dept. of CSE&IT, DBCET, Guwahati
Function Prototype� Function prototype consists of
� Function name
� Parameters – what the function takes in
� Return type – data type function returns (default int)
� Used to validate functions� Used to validate functions
� The function with the prototypeint maximum( int, int, int );
� Takes in 3 ints
� Returns an int
7 Dept. of CSE&IT, DBCET, Guwahati
Function Definition� Function definition format
return-value-type function-name( parameter-list ){
declarations and statements}
� Function-name: any valid identifier� Function-name: any valid identifier
� Return-value-type: data type of the result (default int)� void – indicates that the function returns nothing
� Parameter-list: comma separated list, declares parameters� A type must be listed explicitly for each parameter unless, the parameter is of type int
8 Dept. of CSE&IT, DBCET, Guwahati
Function Definition [contd..]�Declarations and statements: function body (block)
� Variables can be declared inside blocks (can be nested)
� Functions can not be defined inside other functions
�Returning control� If nothing returned � If nothing returned
� return;
� or, until reaches right brace
� If something returned
� return expression;
9 Dept. of CSE&IT, DBCET, Guwahati
Function Call� Invoking functions
� Provide function name and arguments (data)� Function performs operations or manipulations� Function returns results
� Format for calling functions� FunctionName( argument );
� If multiple arguments, use comma-separated list
� printf( "%.2f", sqrt( 900.0 ) );
� Calls function sqrt, which returns the square root of its argument
� All math functions return data type double
� Arguments may be constants, variables, or expressions
10 Dept. of CSE&IT, DBCET, Guwahati
Example#include <stdio.h>int absolute(int); // function prototype for absolute()int main(){
int num, answer; printf("Enter an integer: “); scaf(“%d”,&num);answer = absolute(num); //function callprintf("The absolute value of is %d“, answer);
return 0; } // Define a function to take absolute value of an integer int absolute(int x) // function definition{
if (x >= 0)return x;
elsereturn -x;
}
11 Dept. of CSE&IT, DBCET, Guwahati
Purpose of return statementThe return statement serves two purposes:
� On executing the return statement it immediately transfers the control back to the calling program.
� It returns the value present in the parentheses after return, to the calling program. the calling program.
12 Dept. of CSE&IT, DBCET, Guwahati
Function without arguments
and without return value
#include<stdio.h>void addnumbers(void);void main(){
printf(“ Program for adding two numbers using functions \n”);addnumbers();printf(“\n we are back in main function”);printf(“\n we are back in main function”);
}void addnumbers(){
int a,b,sum;printf(“enter the values of two numbers:”);scanf(“%d%d”,&a,&b);sum=a + b;printf(“The sum of %d and %d is = %d”,a,b,sum);
}
13 Dept. of CSE&IT, DBCET, Guwahati
� One function can also calls another function i.e., function
calls can be nested.
� A function can also calls itself. These types of functions
are called recursion.
void main(){ int fact(int a){
calculate();}void calculate(){
add();mul();
}void add(){}void mul(){}
int fact(int a)
{
f=a*fact(a-1);
}
14 Dept. of CSE&IT, DBCET, Guwahati
Library functions
� Each standard library has a corresponding header file
� Header files contain function prototypes and other definitions
� Can also create library of your own functions
� There’s a list of available functions in many Libraries
� stdio.h, math.h, string.h, conio.h etc…� stdio.h, math.h, string.h, conio.h etc…
clrscr() in conio.hClears text mode window
15 Dept. of CSE&IT, DBCET, Guwahati
abs acos acosl asin asinl
atan atanl atan2 atan2l atof _atold
cabs cabsl ceil ceill cos cosl
cosh coshl exp expl fabs fabsl
floor floorl fmod fmodl frexp frexpl
Math.h
hypot hypotl labs ldexp ldexpl
log logl log10 log101 matherr _matherrl
modf modfl poly polyl pow powl
pow10 pow10l sin sinl sinh sinhl
sqrt sqrtl tan tanl tanh tanhl
16 Dept. of CSE&IT, DBCET, Guwahati
stdio.h
clearerr fclose fcloseall fdopen feof ferror
fflush fgetc fgetchar fgetpos fgets fileno
flushall fopen fprintf fputc fputchar fputs
fread freopen fscanf fseek fsetpos ftell
fwrite getc getchar gets getw perror
printf putc putchar puts putw removeprintf putc putchar puts putw remove
rename rewind rmtmp scanf setbuf setvbuf
sprintf sscanf strerror _strerror tempnam tmpfile
tmpnam ungetc unlink vfprintf vfscanf vprintf
vscanf vsprintf vsscanf
17 Dept. of CSE&IT, DBCET, Guwahati
Different ways of calling a function
with arguments
When calling a function, arguments can be passed to a function in two ways�Call by value�Call by reference
18 Dept. of CSE&IT, DBCET, Guwahati
Call By ValueCall By ValueCall By ValueCall By Value
Here arguments are being passed by value� temporary copy of argument (constant, variable, expression) is provided to function (by way of a stack)
� function can change the copy, but not the original value in calling function
� Call by value results in greater independence between � Call by value results in greater independence between modules
19 Dept. of CSE&IT, DBCET, Guwahati
20 Dept. of CSE&IT, DBCET, Guwahati
#include<stdio.h>void callbyval(int,int);void main(){
int a,b;a=b=10;printf(“\n The values of a and b before calling the function is %d and %d”,a,b);
Example
callbyval(a,b);printf(“\n Atfer the function is executed the values of a is %d and b is %d”,a,b);
}void callbyval(int a,int b){
a=a * a;b=b * b;printf(“\n The values of a and b inside the callbyval function is %d and %d”,a,b);
}
21 Dept. of CSE&IT, DBCET, Guwahati
Scope Rules
� Scope of a variable is that part of a program in which the variable can bereferenced
� visible only in the block in which they are declared
void display(int); 1. Variable accessible in main() is ivoid display(int); void main(){ int i=10;display(i);
}void display(int j){ int k=27;printf(“\n %d %d”,j,k);
}
1. Variable accessible in main() is i
2. Variables accessible in display is j and k
3. Scope of i is within the main() and scope of j and k is in the display()
22 Dept. of CSE&IT, DBCET, Guwahati
An Introduction to pointersAn Introduction to pointersAn Introduction to pointersAn Introduction to pointers
2
a
4885
Location name
Value at location
Location address
This declaration tell the C compiler to:
1. Reserve space in memory to hold an integer value
2. Associate the name “a” with this memory location
3. Store the value 2 at this location
int a=2;
� A pointer is a variable that contains the address of a variable � Pointers are declared to "point" to a variable of a particular type (int, double, etc.)
� When we use a pointer to access the value stored in the variable to which it points, we are using indirect addressing
23 Dept. of CSE&IT, DBCET, Guwahati
2
a
4885
4885
b
3376
int a=2;int *b;
Is a pointer to an integer
int *b;b=&a;printf(“\n Address of a=%u”,&a);printf(“\n Address of a=%u”,b);printf(“\n Address of b=%u”,&b);printf(“\n Value of b=%u”,b);printf(“\n Value of a=%d”,a);printf(“\n Value of a=%d”,*(&a));printf(“\n Value of a=%d”,*b);
Address of a=4885Address of a=4885Address of b=3376Value of b=4885Value of a=2Value of a=2Value of a=2
24 Dept. of CSE&IT, DBCET, Guwahati
Call By ReferenceCall By ReferenceCall By ReferenceCall By Reference
passed by reference� temporary copy of the address of argument is provided to function
� called function can change value of the local variable in the calling function because it knows where in memory it is function because it knows where in memory it is
� pass by reference simulated in C by using the address operator (&), an array name, or a pointer variable
25 Dept. of CSE&IT, DBCET, Guwahati
void swap(int *x,int *y);void main(){int a=10,b=20;swap(&a,&b);printf(“\n a=%d b=%d”,a,b);
20
b
8682
10
a
4885
}void swap(int *x,int *y){int t;t=*x;*x=*y;*y=t;
}
10
t
2416
4885
x
6612
8682
y
4216
10
b
8682
20
a
4885
26 Dept. of CSE&IT, DBCET, Guwahati
Recursion�In C, a function that calls itself repeatedly, is called a recursion.
�Using recursion sometimes makes coding more straightforward; consider the calculation of n!,
27 Dept. of CSE&IT, DBCET, Guwahati
Recursion Example
#include<stdio.h>long int fact( unsigned int num);void main();{ long f;
unsigned int n;printf(“Enter an integer number:”);scanf(“%u”,&n);f=fact(n);printf(“The factorial of a number is %ld \n”,f);printf(“The factorial of a number is %ld \n”,f);
}long int fact(unsigned int num){
if(num==0)return(1);
elsereturn ( num * fact(num-1));
}
28 Dept. of CSE&IT, DBCET, Guwahati
f=fact(4);
1st call to fact
num=4;
return(4 * fact(3));
2nd call to fact
num =3;
return(3 * fact(2));2
6
24
long int fact(unsigned int num)
{
if(num==0)
return(1);
else
return ( num * fact(num-1)); return(3 * fact(2));
3rd call to fact
num =2;
return(2 * fact(1));
4th call to fact
num =1;
return(1 * fact(0));
5th call to fact
num =0;
return(1)
1
1
return ( num * fact(num-1));
}
29 Dept. of CSE&IT, DBCET, Guwahati