Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dr Tripty Singh Tutorial for Fuctions

Similar presentations


Presentation on theme: "Dr Tripty Singh Tutorial for Fuctions"— Presentation transcript:

1 Dr Tripty Singh Tutorial for Fuctions
FUNCTIONS Dr Tripty Singh Tutorial for Fuctions

2 Function definitions return_type function_name (formal parameter list) { local declarations .... statements } A function in C can have a return value, side effect or both. The functions value is the value in the expression of the return statement. A function side effect is an action that results in the change in the state of the program. The side effect occurs before the value is returned

3 void functions without parameters
#include <stdio.h> void greeting( void) { printf(“Hello world”); return; } int main(void) greetings(); return 0; This function receives nothing and returns nothing

4 void functions parameters
#include <stdio.h> void printone( int x) // x is formal parameter { printf(“%d\n”,x); return; } int main(void) int a; a = 5; printone(a); // a is actual parameter printone(20); // a value can be directly passed return 0;

5 void functions with parameters
#include <stdio.h> void area( int x),int y) { int area; area = x * y; printf(“rea is %\dn”,area; return; } int main(void) int a=5, b=10; area(a,b); return 0; Output is area is 50 X,y is formal parameter Output is area is 50 a ,b is actual parameter

6 functions without parameters that returns a value;
/*A functions that gets an option from user and returns it */ char get_option(void) { chat ch; printf(“Enter operation \n”); printf(“ * for multiplication\n”); printf(“ + for addition\n”); printf(“ – for subtraction\n”); printf(“ / for division\n”); printf(“ q to quit\n”); scanf(“ %c”, &ch); return ch; }

7 Sample program #include <stdio.h> //include function definition here int main(void) { int num1, num2, result; char option; option = get_option(); while (option != ‘q’) printf(“Enter the numbers”); scanf((“%d%d”, &num1, &num2); switch (option) { case ‘+’: result = num1+num2; break; case ‘*’: result = num1*num2; break; case ‘-’: result = num1-num2; break; case ‘/’: result = num1/num2; }

8 Functions with parameters that returns value
/*A functions that accepts three sides of a triangle as its parameters and returns the area of the triangle */ float t_area(float a, float b, float c) { float area, s; // local variables s = (a + b+ c) /2.0; area = s qrt(s * (s-a) * (s-b) * (s-c) ) return area } Main Program #include <stdio.h> //include function definition here int main(void) { float s1,s2,s3,ar; printf(“Enter three sides:”); scanf(“%f%f%f”, &s1, &s2, &s3); ar=t_area(s1,s2,s3); printf(“area is %f\n”,ar); }

9 Function name - usage Function declaration Function definition
Function call

10 Function to find largest of three numbers
What should be the function prototype of a function that returns the largest of three numbers passed to it?

11 Function to find largest of three numbers
What should be the function prototype of a function that returns the largest of three numbers passed to it? int largest (int a, int b, int c);

12 Function to find largest of three numbers
#include <stdio.h> int largest(int a, int b, int c); // function declaration main() { int l, i,j,k; printf("Enter three numbers"); scanf("%d%d%d", &i, &j, &k); l = largest(i,j,k); // Function call printf("largest is %d\n", l); } int largest(int a, int b, int c) // Function definition if (a>=b && a>=c) return a; else if (b>= a && b >=c) return b; else return c;

13 Function to find largest of three numbers
#include <stdio.h> int largest(int , int , int ); // variable names can be omitted in declaration main() { int l, i,j,k; printf("Enter three numbers"); scanf("%d%d%d", &i, &j, &k); l = largest(i,j,k); printf("largest is %d\n", l); } int largest(int a, int b, int c) if (a>=b && a>=c) return a; else if (b>= a && b >=c) return b; else return c;

14 Function to check prime
#include <stdio.h> #include <math.h> int prime(int num); main() { int l; printf("Enter a numbers"); scanf("%d", &i); if (prime(i)) printf("%d is prime \n", i); else printf("%d is not prime \n", i); } int prime(int n) int i = 1; int end = sqrt(n) + 1; while (++i < end) if (n%i == 0) return 0; return 1;

15 Number of prime numbers between two given numbers
#include <stdio.h> int prime(int num); main() { int low, upper,i,count=0; printf("Enter the lower and upper range”); scanf("%d", &iower, &upper; for (i=lower; i<= upper; i++) if (prime(i)==1 ) count++; printf(“Number of prime numbers between “); printf(“ %d and %d is %d\n”, lower, upper, count); } int prime(int n) int i = 1, prime = 1; for (i=2; i<n; i++) if (n%i == 0) { prime =0; break; } // come out of loop as soon as a divisor is found return prime; // prime will be 1 if no divisor is found

16 Specifying function requirements
We can see that a more general function might require arguments; but how do we know what the requirements are? A general method for specifying the requirements for a function call is called function declaration or function prototyping

17 C – Argument, return value
All C functions can be called either with arguments or without arguments in a C program. These functions may or may not return values to the calling function. Now, we will see simple example C programs for each one of the below. C function with arguments (parameters) and with return value. C function with arguments (parameters) and without return value. C function without arguments (parameters) and without return value. C function without arguments (parameters) and with return value.

18 Function prototype Declaration statement for function
Provides information necessary to call function Data type of function’s return value (if any) Data type(s) of any required argument(s), listed in the order required: this is called the parameter list Usually appears above main() or in a header file Function prototypes are declaration statements – each one ends with a semicolon

19 Function prototype examples
The function prototypes for some familiar functions are listed below: int rand(); // appears in the stdlib.h header file double sqrt (double); // appears in math.h double pow (double, double); // also in math.h

20 Function prototypes A function prototype includes the following parts:
The function’s return type; can be any data type, including void (meaning no return value) The function name (must be a valid C identifier – same rules apply for functions and variables) The function’s parameter list, which specifies the data type of each required argument, and optionally includes a name for each parameter

21 Examples int rand(); double pow (double, double); parameter list
name of function type of value returned double pow (double, double); Note: a function’s parameter list may, but does not have to, include a name for each parameter; the parameters are not named in the examples above

22 More examples Previously, we considered 3 possible versions of a drawSquare function; the prototypes for each version are shown below: void drawSquare(); // draws a 4x4 square made of asterisks void drawSquare(int); // draws a square of the specified size, made of asterisks void drawSquare(int size, char pixel); // draws a square of the specified size using the specified // picture element Note that these are examples of overloaded functions – their prototypes differ only in their parameter lists

23 More examples Previously, we considered 3 possible versions of a drawSquare function; the prototypes for each version are shown below: void drawSquare(); // draws a 4x4 square made of asterisks void drawSquare(int); // draws a square of the specified size, made of asterisks void drawSquare(int size, char pixel); // draws a square of the specified size using the specified // picture element Note that these are examples of overloaded functions – their prototypes differ only in their parameter lists

24 C functions aspects syntax
1. With arguments and with return values function declaration: int function ( int ); function call: function ( a ); function definition:        int function( int a ) { statements; return a; } 2. With arguments and without return values function declaration: void function ( int ); function call: function( a ); function definition: void function( int a ) { statements; }

25 C functions aspects syntax 3. Without arguments and without return values function declaration: void function(); function call: function(); function definition: void function() { statements; } 4. Without arguments and with return values function declaration: int function ( ); function call: function ( ); function definition: int function( ) { statements; return a; }

26 #include<stdio.h>
// function prototype, also called function declaration float square ( float x );                               // main function, program starts from here int main( )               {     float m, n ;     printf ( "\nEnter some number for finding square \n");     scanf ( "%f", &m ) ;     // function call     n = square ( m ) ;                           printf ( "\nSquare of the given number %f is %f",m,n ); } float square ( float x )   // function definition     float p ;     p = x * x ;     return ( p ) ; Enter some number for finding square 2 Square of the given number is

27 Function with no Arguments but Return Value In C

28 Function with no arguments and no Return Value In C

29 Note: If the return data type of a function is “void”, then, it can’t return any values to the calling function. If the return data type of the function is other than void such as “int, float, double etc”, then, it can return values to the calling function.

30 Function with argument and return type

31 Storage Classes auto static extern register
Automatic. Also called local variable static extern External. Also called global variables register Storage class determines life time of a variable

32 Scope Scope /life / visibility of a variable starts from where it is declared and continues till the end of the block where it is declared. If a variable is declared outside of any block, such variables ( typically global variables) are visible till the end of the file.

33 auto storage class. Automatic variables are always declared within a function or a block. They are local to the function (i.e., their scope is confined to the function). Formal parameters are local to the function. Any variable declared within a block (pairs of { } ) without explicit storage class specifier is a local variable. Its scope is only up to the end of the block (variable gets destroyed at the end of the block and memory allocated for it is released) It is a common practice to omit storage class specifier when local variables are declared. Local variables can be initialized

34 auto storage class. Automatic variables are always declared within a function or a block. They are local to the function (i.e., their scope is confined to the function). Formal parameters are local to the function. Any variable declared within a block (pairs of { } ) without explicit storage class specifier is a local variable. Its scope is only up to the end of the block (variable gets destroyed at the end of the block and memory allocated for it is released). it is not available outside the block. It is a common practice to omit storage class specifier when local variables are declared.

35 auto storage class. int bigger( int a, int b) { int large; auto char option = ‘a’; if (a > b) large = a; else large = b; return large; } a, b , large and option are auto (also called local) variables. The value of a local variable is unspecified unless it is initialized or until a value a value is assigned to it.

36 #include <stdio.h>
main() { int i=30,j, k; if (i > 20) int sum = 10; sum = sum +10; printf("sum is %d \n", sum); } printf("sum is %d \n", sum);// error

37 #include <stdio.h>
main() { int i,j, k; int sum=20, i = 30; if (i > 10) int sum = 10; printf("sum is %d \n", sum); }

38 static storage class static storage class specifier causes a memory to be allocated to the variable till the end of program execution. Though the variable is not destroyed at the end of block, it is not visible outside the block. The value of the variable is retained.

39 #include <stdio.h> main() { int i,j, k,l; int sum=20; for (i = 0; i<=1; i++) int sum = 10; sum = sum + 2; printf("sum is %d \n", sum); }

40 #include <stdio.h> main() { int i,j, k,l; int sum=20; for (i = 0; i<=1; i++) static int sum = 10;//initialized only once sum = sum + 2; printf("sum is %d \n", sum); }

41 Global variables Variables declared outside of any function definition is a global variable The visibility of a global variable start from where it is declared and is visible till the end of the file. Life of the variable till the end of program execution If the variable not explicitly initialized, it gets an initial value of zero. Initialization, if done, has to be with a constant value (it cannot be an expression involving variables) Storage class specifier extern is used to declare a variable which is defined in another file (variable is external to the current file)

42 #include <stdio. h> int count; // global variable
#include <stdio.h> int count; // global variable. initial value 0 int num = 1000; extern max; // max is defined in another file. void mesage(); int main() { printf("%d %d %d\n", count, num, max); num = num + 500; message(); printf("%d\n", count); } void message(void) printf(“num is %d\n", num); count++;

43 #include <stdio.h> int count; int num = 1000; void mesage(); int main() { printf("%d %d\n", count, num); // num = num + 500; message(); printf("%d\n", count); // 1 } void message(void) printf(“num is %d\n", num);// 1500 count++; 0 1000 num is 1500 1

44 register variables register storage class is same as auto class except that it contains a recommendation to the compiler to allocate a CPU register for the variable.

45 Some standard (builtin) functions
Math functions To calculate absolute value int abs ( int number); // stdlib.h long labs (long number) // stdlib.h long long llabs (long long number) // stdlib.h double fabs (double number) //math.h float fabsf (float number) //math.h long double fabsl (long double number) //math.h

46 Additional math functions
Ceiling functions (smallest integral value greater than or equal to number) double ceil ( double number) float ceilf ( float number) long double ceill ( long double number) floor functions (largest integral value smaller than or equal to number) double float( double number) float floatf( float number) long double floatl( long double number)

47 Additional math functions
Truncate functions (returns the integer in the direction of zero) double trunc ( double number) float truncf ( float number) long double truncl( long double number) round functions (returns the nearest integral value) double round( double number) float roundf( float number) long double roundl( long double number)

48 Additional math functions
Power function double pow ( double n1, double n2) float powf (float n1, float n2) long double powlf (long double n1, long double n2) Square root functions double sqrt( double number) float sqrtf( float number) long double sqrtlf( long double number)

49 Recursion A function calling itself
A function calling some function higher in the calling hierarchy.

50 Recursion function1

51 Recursion function1 function2 function3

52 Recursion - Examples Fibonacci numbers Facttorial
F(n) = F(n-1) + F(n-2) Facttorial n! = (n-1)! * n

53 Recursion


Download ppt "Dr Tripty Singh Tutorial for Fuctions"

Similar presentations


Ads by Google