QUIZ3 4 locations LHC 502-505 LHC 401 CSC PCLABS 1,2,3,5,6 GCL - BHARTI BUILDING (4TH FLOOR) TIME: 8 - 10PM ------- PRINCIPLES OF GOOD PROGRAMMING 1. COMMENT YOUR CODE 2. INDENT CODE 3. USE MANY SMALL FUNCTIONS INSTEAD OF ONE LARGE FUNCTION SCOPE num=3, y=5.6 ret_type (ex: char) func_name(int num, float y, int arr[]) { int c; float b; [LOCAL VARIABLES] int q[5]; b=10.5; arr[4]=7; ( nums[4] gets modified in main() ) arr[15]=8; (can get SEGMENTATION FAULT error) return 'f'; [function ends/exits at return] x=y+z; } SCOPE OF b,c in func_name is LOCAL to that function only int main() { int b=3; float c=5.6; char d; int q[6]; int nums[10]; d=func_name(b, c, nums); b=5; } PASSING OF PARAMETERS 1. PASSING BY VALUE: when variable is given as input, only the VALUE of variable is passed to the function 2. PASSING BY REFERENCE: when array is given as input, only the starting ADDRESS in memory of the array is passed to function Q. CAN WE DEFINE FUNCTIONS AFTER MAIN? DECLARATION: char func_name(int, float, int []); [not mentioned variable names, no body is given] int main() { func_name..... body } DEFINITION char func_name(int b, float c, int arr[]) { body of function} PASSING BY REFERENCE MEMORY ADD VARIABLE STORED 14 -- 15 -- 16 -- 17 nums[0] 18 nums[1] 19 nums[2] 20 nums[3] 21 nums[4] ..... 26 nums[9] ON CALLING func_name 34 b LOCAL VARIABLES OF func_name 35 c 36 arr ---> 17 gets stored (address of nums[0]) 37 q[0] 38 q[1] 39 q[2] .... arr[4] = 7 --- n C r = n!/( (n-r)! * r!) WRITE A C PROGRAM WHICH HAS FUNCTION int ncr(int n, int r) AND ANOTHER FUNCTION int fact(int n) MAIN FUNCTION TAKES USER INPUT FOR n,r AND PRINTS "n choose r" RECURSION 1. n! = n* (n-1)! 2. gcd(a, b) = gcd( b, a mod b) [ assuming a>b] int fact(int n) { int result; if (n>0) result=n*fact(n-1); [RECURSION, function calls itself] else result=1; return result; } WHAT HAPPENS? fact(3): result=3*fact(2) fact(2): result=2*fact(1) | fact(1): result=1*fact(0) | fact(0): result=1; return result; | fact(1): result=1*1;return result; | fact(2): result = 2*1; return result;