120 likes | 131 Views
This lecture covers topics such as functions, macros, conditional compilations, prototypes, variable scope, recursion, and more in the C programming language.
E N D
Lecture-3 Functions and Recursion
C Preprocessor • Includes header files like stdio.h • Expands macros defined • Handles conditional compilations prog.c Preprocessor Processor a.out
Example #include <stdio.h> #define PI 3.142 int main() { float rad=0.0; printf(“Enter the radius of Circle: “); scanf(“%f”, &rad); #ifdef chk_rad if(rad<0) { printf(“Error!\n”); return 1;} #endif printf(“Area of Circle= %f”, PI*rad*rad); return 0; }
Functions • “Subprograms” with parameters, program statements, and a result • Break code into simpler pieces • Promote “reuse” of code in both the same and other programs • Link to code written in other programming languages
Prototypes and Definitions • Prototypes tell the compiler to expect a function with the specified signature • Definition also includes the body of the function • May have more than one parameter Follow this link to the programfunc.c
Miscellaneous • Libraries included in the C programming environment are a collection of header files, e.g. stdio.h, math.c, etc. • Functions not taking any parameters should use keyword “void” in the parameter list • Functions with no return type should use return type of “void”
Variable scope • Only one function is active in the memory at any time • Thus it may use only those variables that it declares • Functions can re-declare the same variables within its scope
In-class exercise 3-1 • Write a program which finds the largest number from three numbers given to it • The main function will prompt the user for three numbers and pass them onto a function which computed the largest • The function will return the largest number to the main, which will then print out the result
Call by Value • C uses “call by value” to pass parameters between functions by duplicating the values • Changing the originally passed parameter in the calling function, does not change the variable value in the called function
Recursion • Recursion is when the function calls itself , either directly or indirectly • Each recursion has a “base case” which will make the recursion stop. • Some conditional statement, like an “if-else” is required to test for the base case for the recursion to stop Follow this link to an example ofrecursion
In-class exercise 3-2 • Create a program which computes the Greatest Common Divisor for given two numbers • Use the method of eigen values • Pass the original values to a function • The function computes (num1%num2) and recursively calls itself with num2, and the remainder as parameters till the remainder becomes zero(base case!). Then it returns the first parameter as the GCD.
Homework 3 Follow this link to Homework 3