130 likes | 195 Views
Today’s Agenda. Function Pointers Command Line Arguments Introduction to File Handling in C. Function pointer. Syntax type (*fp) (); Example float mul(int a,int b); float (fp *)(); fp = mul; Function call res = mul(a,b); res = (fp*)(a,b);. int add(int a,int b);
E N D
Today’s Agenda Function Pointers Command Line Arguments Introduction to File Handling in C
Function pointer • Syntax • type (*fp) (); • Example • float mul(int a,int b); • float (fp *)(); • fp = mul; • Function call • res = mul(a,b);res = (fp*)(a,b);
int add(int a,int b); int sub(int a,int b); int mul(int a,int b); int arithFuns(int(*pf)(),int a,int b);
int main() { int x =10,y = 4; int res; res = arithFuns(add,x,y); printf("%d + %d = %d\n",x,y,res); res = arithFuns(sub,x,y); printf("%d - %d = %d\n",x,y,res); res = arithFuns(mul,x,y); printf("%d * %d = %d\n",x,y,res); }
int add(inta,int b) { return(a+b); } int sub(inta,int b) { return(a-b); } intmul(inta,int b) { return(a*b); } intarithFuns(int (*pf)(),inta,int b) { int res; res = (*pf)(a,b); return res; }
int linsearch(int arr[],int n,int key); • int binsearch(int arr[],int n,int key); • int searchAlgo(int(*s)(),int arr[],int n,int key);
int searchAlgo(int (*s)(),int a[],int n,int key) • { • int found; • found = (*s)(a,n,key); • return found; • }
intlinsearch(int a[],intn,int key) { inti=0; while(i<n) { if(a[i] == key) return i; else { i++; continue; } } return -1; }
intbinsearch(int a[],intn,int key) { int l =0,h = n-1; int mid; while(l<h) { mid = (l+h)/2; if(a[mid] == key) return mid; else if(a[mid] > key) h = mid-1; else if(a[mid] < key) l = mid+1; } return -1; }
output [Mayuri@localhost cp2_15Sept]$ ./a.out 10 + 4 = 14 10 - 4 = 6 10 * 4 = 40 Use Linear Search number found at index 3 Use Binary Search number found at index 3
Command line Arguments #include<stdio.h> #include<stdlib.h> #include<string.h> int main(intargc,char *argv[]) { int sum=0; inti; if(argc != 4) { printf("invalid argument\n"); exit(0); } for(i=0;i<argc;i++) printf("%s\t",argv[i]); printf("\n"); for(i=1;i<argc;i++) sum = sum + atoi(argv[i]); printf("sum = %d\n",sum); }
output [Mayuri@localhost processes_new]$ ./a.out 10 20 30 ./a.out 10 20 30 sum = 60
First program on files int main(intargc,char *argv[]) //counting number of characters stored in a file { FILE *fp; char ch; intnoc = 0; fp = fopen(argv[1],"r"); while(1) { ch = fgetc(fp); if(ch == EOF) break; noc++; } fclose(fp); printf("number of characters = %d\n",noc); } //output /*[Mayuri@localhost cp2_15Sept]$ ./a.out sample.txt number of characters = 15 */