120 likes | 234 Views
Today’s Agenda. Preprocessor Directives Introduction to Recursion. Preprocessors Directives. It’s a program that processes the source code before it passes through the compiler These directives are placed in the source program before main line. Syntax is #<preprocessor directive> Example
E N D
Today’s Agenda • Preprocessor Directives • Introduction to Recursion
Preprocessors Directives • It’s a program that processes the source code before it passes through the compiler • These directives are placed in the source program before main line. • Syntax is • #<preprocessor directive> • Example • #include • #define (do not terminate it with semicolon)
Three categories of directives • Macro substitution directive • Simple Macro Substitution • Macro substitution with argument • Nested Macro Substitution • File inclusion directive • Compiler control directive
Simple Macro Substitution • Syntax • #define <identifier string> • Examples • #define COUNT 100 • #define PI 3.1415 • #define CAPITAL “DELHI” • #define TWO-PI 2.0*3.1415 • #define D (45-22) • #define AND &&
Macro substitution with argument • Syntax • #define identifier(f1,f2,….fn) <string> • Example • #define SQR(x) ((x)*(x)) • square = SQR(a+b); • #define CUBE(x) (SQR(x) * (x)) //nested macros • Volume = CUBE(a+b); • Volume = (SQR(a+b) * (a+b)); • Volume = CUBE(((a+b) * (a+b)) *(a+b));
More examples • #define MAX(a,b) (((a)>(b)) ? (a) : (b)) • # define MIN(a,b) (((a)<(b)) ? (a) : (b)) • #define STREQ(s1,s2) (strcmp((s1),(s2)) == 0)
File inclusion • #include<stdio.h> • #include<stdlib.h> • More on file inclusion later • Compiler control directives will be discussed later during multi-file compilation techniques are discussed.
What is Recursion? Mathematical Definition: RunningSum(1) = 1RunningSum(n) = n + RunningSum(n-1) Recursive Function: int RunningSum(int n) { if (n == 1) return 1; else return n + RunningSum(n-1);} • A recursive function is one that solves its taskby callingitself on smaller pieces of data. • Similar to recurrence function in mathematics. • Like iteration -- can be used interchangeably;sometimes recursion results in a simpler solution. • Example: Running sum ()
Executing RunningSum Recursive Function: int RunningSum(int n){ if (n == 1) return 1; else return(n + RunningSum(n-1)); } res = RunningSum(4); return value = 10 RunningSum(4) return 4 + RunningSum(3); RunningSum(3) return value = 6 return 3 + RunningSum(2); RunningSum(2) return value = 3 return 2 + RunningSum(1); RunningSum(1) return value = 1 return 1;
examples discussed in class • sum of n natural numbers • factorial • reverse a string of words • nth fibbonacci number • Exercise • gcd of two numbers