110 likes | 202 Views
Chapter 7: Functions. Dr. Ameer Ali. Overview. A function is a self contained program segment that will carry some well defined and specific task A function will carry over its intended actions whenever it is accesses from some other portion of the program
E N D
Chapter 7: Functions Dr. Ameer Ali
Overview • A function is a self contained program segment that will carry some well defined and specific task • A function will carry over its intended actions whenever it is accesses from some other portion of the program • The same function can be accessed from several places within the program
Declaration void Name (void) { Statement; } Return_type Name (type_of_parameter Name_of_Parameter) { Statements; } Return_type Name (agr1, arg2, …, agrn) { Statements; }
Example • Lower case to upper case conversion #include<stdio.h> char lower_to_Upper(char c1) { char c2; c2=toupper(c1); return c2; } Void main(void) {char upper, lower; printf(“Enter your lower case letter”); scanf(“%c”,&lower); upper=lower-to_upper(lower); printf(“\n Your upper case char is %c”, upper); getch(); }
Accessing a function • Must be accessed in the similar way upper=lower-to_upper(lower);
Function Prototype • Lower case to upper case conversion #include<stdio.h> long int factorial(int n) { int i; long int prod; prod=1; if (n>0) { for(i=1;i<=n;i++) { prod*=i; } } return prod; }
Function Prototype Void main(void) {int n; long int fact; printf(“Enter your number”); scanf(“%d”,&n); fact=factorial(n); printf(“\n Factorial of n=%ld”, fact); getch(); }
Function Prototype #include<stdio.h> long int factorial(int n); //function prototype void main(void) {int n; long int fact; printf(“Enter your number”); scanf(“%d”,&n); fact=factorial(n); printf(“\n Factorial of n=%ld”, fact); getch(); }
long int factorial(int n) { int i; long int prod; prod=1; if (n>0) { for(i=2;i<=n;i++) { prod*=i; } } return prod; }