110 likes | 200 Views
Today’s Agenda. Recursion Array of Structures Introduction to Pointers. Recursion. Binary Search Power Series Maximum in an array Factorial using accumulator method Exercise Minimum in an array. Binary Search. int main() { int a[10] = {1,2,3,4,5,6,7,8,9,10}; int x=2; int index;
E N D
Today’s Agenda Recursion Array of Structures Introduction to Pointers
Recursion • Binary Search • Power Series • Maximum in an array • Factorial using accumulator method • Exercise • Minimum in an array
Binary Search int main() { int a[10] = {1,2,3,4,5,6,7,8,9,10}; int x=2; int index; index = bSearch(a,0,9,x); if(index == -1) printf("number not found\n"); else printf("number found at location %d\n",index); }
intbSearch(int a[],intlow,inthigh,int x) { intmid,index; mid = (low + high)/2; if(low>high) index = -1; else if(x > a[mid]) { low = mid+1; index = bSearch(a,low,high,x); } else if(x < a[mid]) { high = mid-1; index = bSearch(a,low,high,x); } else if(x == a[mid]) index = mid; return index; }
Power Series (1 + x^2 + x^3 + …+ x^n) int main() { int n=5,x=2; int sum; sum = recSum(x,n); printf("Sum = %d\n",sum); }
Power Series (1 + x^2 + x^3 + …+ x^n) int recSum(int x,int n) { int ans; if(n == 0) ans = 1; else ans = pow(x,n) + recSum(x,n-1); return ans; }
Maximum in an array int main() { int a[5] = {12,21,78,9,7}; int max; max = maxm(a,5); printf("max = %d\n",max); }
Maximum in an array intmaxm(int a[],int n) { int max; if(n == 1) max = a[n-1]; else { max = maxm(a,n-1); if(max < a[n-1]) max = a[n-1]; } return max; }
Factorial using accumulator method int main() { int n=5,acc=1,f; f = fact(n,acc); printf("%d! = %d\n",n,f); } int fact(intn,int acc) { if(n == 1) return (acc*1); else return fact(n-1,n*acc); }
Revisit Student Record typedefstruct { intidno; char name[20]; float marks[7]; discipline d; //declare enum for discipline float percent; grade g; //declare enum for grade }student; student s[10];
Operations: • void getStudent(student s[],int size); • void readMarks(student s); • void printStudent(student s[],int size); • void printMarks(student s); • float findPercent(student s[],int size); • grade findGrade(float percent);