fundamental of programming (c)
DESCRIPTION
Fundamental of Programming (C). Lecture 7 Modular programming. Outline. Introduction to pointer Introduction to function User define function Function prototype (declaration) Function definition Function call and return Formal and Actual Parameters Scope of Identifiers Storage classes - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/1.jpg)
Lecturer: Omid Jafarinezhad
Sharif University of TechnologyDepartment of Computer Engineering 1
Fundamental of Programming (C)
Lecture 7Modular programming
![Page 2: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/2.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 2
Outline• Introduction to pointer• Introduction to function• User define function
– Function prototype (declaration)– Function definition– Function call and return
• Formal and Actual Parameters• Scope of Identifiers• Storage classes• Recursion
![Page 3: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/3.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 3
Pointer Fundamentals• When a variable is defined the
compiler (linker/loader actually) allocates a real memory address for the variable– int x;
• When a value is assigned to a variable, the value is actually placed to the memory that was allocated– x=3;
00000000000000000000000000000011
x
![Page 4: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/4.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 4
Pointers• When the value of a variable is used, the contents in the
memory are used– y=x; will read the contents in the 4 bytes of memory, and
then assign it to variable y• &x can get the address of x (referencing operator &)• The address can be passed to a function:
– scanf("%d", &x);• The address can also be stored in a variable ……
![Page 5: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/5.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 5
Pointers• To declare a pointer variable
type * pointername;
• For example:– int x, k;– int * p1; //(or p1 is a int pointer)– char *p2; – p1 = &x; /* Store the address in p1 */
![Page 6: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/6.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 6
Using Pointers• You can use pointers to access the values of other variables, i.e.
the contents of the memory for other variables
• To do this, use the * operator (dereferencing operator)– Depending on different context, * has different meanings
• For example:int n, m=3, *p;p=&m;n=*p;printf("%d\n", n); // 3printf("%d\n",*p); // 3
![Page 7: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/7.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 7
Using Pointersint i1;int i2;int *ptr1;int *ptr2;
i1 = 1;i2 = 2;
ptr1 = &i1;ptr2 = ptr1;
*ptr1 = 3;i2 = *ptr2;
i1:
i2:0x1000
0x1004
0x1008ptr1:
ptr2:
0x100C
0x1010
0x1014
1
2
0x1000
0x1000
3
3
![Page 8: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/8.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 8
An Exampleint m=3, n=100, *p, *q;p=&m;printf("m is %d\n",*p); // 3m++;printf("now m is %d\n",*p); // 4
p=&n;printf("n is %d\n",*p); // 100*p=500; printf("now n is %d\n", n); // 500
q=&m;*q = *p;printf("now m is %d\n", m); // 500
q p n m
.... ? ? 100 3q p n m
.... ? 100 3
q p n m
.... ? 100 4*pq p n m
.... ? 100 4*p
q p n m
.... 500 4
![Page 9: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/9.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 9
Modular Programming• Break a large problem into smaller pieces
– Smaller pieces sometimes called functions
• Why?– Helps manage complexity
• Smaller blocks of code• Easier to read
– Encourages re-use of code• Within a particular program or across different programs
– Allows independent development of code– Provides a layer of ‘abstraction’
Divide and Conquer
![Page 10: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/10.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 10
Functions - Mathematical View
32)( 2
xxxf
11 is )2(113443)2(2)2()2( 2
ff
f(2)? isWhat
)(xf2 11X Function
Returnedvalue
![Page 11: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/11.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 11
Functions• Every C program starts with main() function
• Functions could be – Pre-defined library functions
• e.g., printf, sin, tan– Programmer-defined functions
• e.g., my_printf, area
int main(){ …}
![Page 12: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/12.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 12
Pre-defined library functions • The C standard library is a standardized
collection of header files and library functions, which are used to implement common operations
![Page 13: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/13.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 13
Pre-defined library functions • <math.h>
– Defines common mathematical functions– e.g. sin, cos. sqrt, pow
• <stdio.h>– Defines core input and output functions– e.g. printf, scanf, puts, gets
• <time.h>– Defines date and time handling functions– e.g. time, clock
• <stdlib.h>– Defines pseudo-random numbers generation functions– e.g. rand, srand
![Page 14: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/14.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 14
C mathematical functions• double fmod( double x, double y );
– Computes the remainder of the division operation x/y
• double exp( double arg );– Computes the e (Euler's number, 2.7182818) raised to the given power arg
• double log( double arg );– Computes the natural (base e) logarithm of arg
• double log10( double arg );– Computes the common (base 10) logarithm of arg
• double sqrt( double arg );– Computes square root of arg
• double pow( double base, double exp);– Computes the value of base raised to the power exp
![Page 15: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/15.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 15
C mathematical functions• double sin( double arg );
– Computes sine of arg (representing angle in radians)
• double cos( double arg );• Computes cosine of arg (representing angle in radians)
• double tan( double arg );– Computes tangent of arg (representing angle in radians)
• overview of math functions in http://en.wikipedia.org/wiki/C_mathematical_functions#stdlib.h
![Page 16: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/16.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 16
An example#include <stdio.h>#include <math.h>int main(void){ double angle; printf("Input angle in radians: \n"); scanf("%lf", &angle); printf("The sine of the angle is %f\n", sin(angle) ); return 0;}
![Page 17: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/17.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 17
An example#include <stdio.h>#include <math.h>
int main(void){ double x1,y1,x2,y2, dist; printf("Enter x1 y1 x2 y2 :"); scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2);
dist = sqrt(pow((x2-x1),2) + pow((y2-y1),2)); //
printf("Distance is %lf\n", dist); return 0;}
![Page 18: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/18.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 18
Random numbers generation functions• int rand();
– Returns a uniformly distributed pseudo-random integral value between 0 and RAND_MAX (0 and RAND_MAX included)
– RAND_MAX : Expands to an integer constant expression equal to the maximum value returned by the function rand(). This value is implementation dependent.
• #define RAND_MAX 32767 /*implementation defined*/
– srand() should be called before any calls to rand() to initialize the random number generator
• void srand( unsigned seed );– Initializes the built-in random number generator used to generate values for
rand() with the seed value seed
![Page 19: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/19.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 19
An Example#include <stdio.h>#include <stdlib.h>
int main(void){ unsigned int seed; /* Declare variables. */ int k; /* Get seed value from the user. */ printf("Enter a positive integer seed value: \n"); scanf("%u",&seed); srand(seed); /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */}
![Page 20: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/20.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 20
An Example#include <stdio.h>#include <stdlib.h>#include <time.h>
int main(void){ srand(time(0)); //use current time as seed for random generator /* Generate and print ten random numbers. */ printf("Random Numbers: \n"); for (k=1; k<=10; k++) printf("%i ", rand()); printf("\n"); return 0; /* Exit program. */}
![Page 21: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/21.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 21 21
Random Numbers in [a b]• Generate a random number [0 .. 7]
– x = rand() % 8;
• Generate a random number [10 ..17]– x = 10 + rand() % 8;
• rand() % (b-a+1) + a;
![Page 22: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/22.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 22
User- definedOR
Programmer-defined function
![Page 23: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/23.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 23
Functions - Definition Structure• Function 'header'
– Return data type (if any)
– Name• Descriptive
– Arguments (or parameter list)• Notice: data type and name
• Statements– Variable declaration– Operations– Return value (if any)
type function_name (type arg1, type arg2 ){
statements;}
double product(double x, double y)
{ double result;
result = x * y; return result; }
A function that calculates the product of two numbers
![Page 24: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/24.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 24
An Example• Function prototype
– Like a variable declaration• Tells compiler that the function will be defined later• Helps detect program errors• Note semicolon!!
• Function definition– See previous slide– Note, NO semicolon
• Function return– return statement terminates execution of the
current function– Control returns to the calling function– if return expression;
• then value of expression is returned as the value of the function call
• Only one value can be returned this way• Function call
– main() is the 'calling function'– product() is the 'called function'– Control transferred to the function code– Code in function definition is executed
#include <stdio.h>/* function prototype */double product(double x, double y);int main(){ double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans); return 0;}/* function definition */ double product(double x, double y){ double result; result = x * y; return result;}
![Page 25: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/25.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 25
Function – An Example• Write a function named 'sum'
– sums two integers– returns the sum
Steps1. Function header
• return data type• function name• argument list with data types
2. Statements in function definition• variable declaration• operations• return value
int sum_int(int x, int y)
{ int result;
result = x + y; return result; }
![Page 26: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/26.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 26
Formal and Actual Parameters• Formal parameter– Variables declared in the formal list of the function header (written in function prototype &
function definition)
• Actual parameter– Constants, variables, or expression in a function call that correspond to its formal parameter
• The number of actual parameters in a function call must be the same as the number of formal parameters in the function definition
• A one-to-one correspondence must occur among the actual and formal parameters. The first actual parameter must correspond to the first formal parameter and the second to the second formal parameter, an so on
• The type of each actual parameter must be the same as that of the corresponding formal parameter
![Page 27: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/27.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 27
An Example#include <stdio.h>int calSum(int,int); /*function prototype*/int main(void){
…..…..sum = calSum(num1,num2); /* function call */…..
}int calSum(int val1, int val2) /*function header*/{
………………
}
Formal Parameters
Formal Parameters
Actual Parameters
![Page 28: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/28.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 28
An Example• If the function requires some arguments to be passed along, then the arguments
need to be listed in the bracket ( ) according to the specified order
void Calc(int, double, char, int);
int main(void) { int a, b; double c; char d; … Calc(a, c, d, b);return (0);}
Function Call
![Page 29: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/29.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 29
Functions that do not return a value• Use the return type of void
– void functionName( DataType arg_1,…)– void functionName()– void functionName( void)
![Page 30: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/30.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 30
Function Call – An Example#include <stdio.h>
//function prototype//global variable declaration
int main(void){
local variable declaration;statements;fn1( );fn2( );
return (0);}
void fn1(void){
local variable declaration;statements;
}
void fn2(void){
local variable declaration;statements;return;
}
1
2
3
4
![Page 31: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/31.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 31
Function Call – An Example• If the function returns a value, then the returned value need to be assigned to a
variable so that it can be stored
int GetUserInput (void); /* function prototype*/int main(void) { int input; input = GetUserInput( ); return(0); /* return 0; */}
• However, it is perfectly okay (syntax wise) to just call the function without assigning it to any variable if we want to ignore the returned value
• We can also call a function inside another functionprintf("User input is: %d", GetUserInput( ));
![Page 32: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/32.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 32
Receive nothing and return nothing#include <stdio.h>void greeting(void); /* function prototype */
int main(void){
greeting( );greeting( );return(0); // return 0;
}
void greeting(void){
printf("Have fun!! \n");}
Have fun!!Have fun!!Press any key to continue
![Page 33: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/33.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 33
Receive nothing and return nothing#include <stdio.h>int getInput(void) /* ignore function prototype */{
int number;printf("Enter a number:");scanf("%d",&number);return number;
}int main(void){
int num1, num2, sum;num1 = getInput( );num2 = getInput( );sum = num1 + num2;printf("Sum is %d\n",sum);return(0);
}
Enter a number: 5Enter a number: 4Sum is 9Press any key to continue
![Page 34: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/34.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 34
Receive parameter(s) and return nothing#include <stdio.h>int getInput(void);void displayOutput(int); int main(void){
int num1, num2, sum;num1 = getInput();num2 = getInput();sum = num1 + num2;displayOutput(sum);return(0);
}int getInput(void){
int number;printf("Enter a number:");scanf("%d",&number);return number;
}void displayOutput(int sum){
printf("Sum is %d \n",sum);}
Enter a number: 5Enter a number: 4Sum is 9Press any key to continue
![Page 35: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/35.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 35
Call by value And Call by reference• Call by value
– In this method, only the copy of variable’s value (copy of actual parameter’s value) is passed to the function. Any modification to the passed value inside the function will not affect the actual value
– In all the examples that we have seen so far, this is the method that has been used
• Call by reference– In this method, the reference (memory address) of the variable is
passed to the function. Any modification passed done to the variable inside the function will affect the actual value
– To do this, we need to have knowledge about pointers and arrays
![Page 36: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/36.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 36
Call by value – An Example• How are the arguments passed
into functions?– 'Pass by value'– function arguments are
expressions
– In the function call:• Expressions are evaluated and
copies of their values are put into temporary memory locations
• The names of the corresponding parameters in the function definition are made to be the names of the copies
– The values of the expressions in the function call are not changed
#include <stdio.h>double product(double x, double y);
int main(){ int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans);}/* function definition */ double product(double A, double B) { double result; result = A * B; return result; }
![Page 37: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/37.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 37
Call by value – An Example#include <stdio.h>int calSum(int,int); /*function protototype*/
int main(void){
int sum, num1, num2;printf("Enter two numbers to calculate its sum:\n");scanf("%d%d",&num1,&num2);sum = calSum(num1,num2); /* function call */printf("\n %d + %d = %d", num1, num2, sum);return(0);
}int calSum(int val1, int val2) /*function definition*/{
int sum; sum = val1 + val2;
val2 = 100;return sum;
}
Enter two numbers to calculate its sum: 494 + 9 = 13Press any key to continue
? num2
? num1
? sum
4 num2
9 num1
? sum
4 val2
9 val1
? sum
4 val2
9 val1
13 sum
100 val2
9 val1
13 sum
4 num2
9 num1
13 sum
![Page 38: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/38.jpg)
Array and String – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 38
Call by reference#include <stdio.h>void CalByVal(a, b){ a = 0; b = 10;}void CalByRef(int *a, int *b) // CalByRef(int *p, int *q) { *a = 0; *b = -5; // a = 0; !!!!}int main(void){ int a = 1, b = 5; printf("Before cal CalByVal: a = %d, b = %d\n", a, b); CalByVal(a, b); printf("After cal CalByVal: a = %d, b = %d\n", a, b); printf("Before cal CalByRef: a = %d, b = %d\n", a, b); CalByRef(&a, &b); printf("After cal CalByRef: a = %d, b = %d\n", a, b); getch(); return 0; /* Exit program. */}
main 5 b
1 a
CalByVal 5 b
1 a
CalByVal 10 b
0 aCalByRef b
a
main -5 b
0 a
![Page 39: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/39.jpg)
Array and String – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 39
Call by reference• Instead of product()
– prod_sum()– How can I get the
function to give both product and sum?
• put * in front of variable name in prototype and function definition
• put & in front of variable names in function call
#include <stdio.h>void prod_sum(double x, double y, double *ptr1, double *ptr2);int main(){ double var1 = 3.0, var2 = 5.0; double prod, sum; prod_sum(var1, var2, &prod, &sum);
printf("var1= %g\n" "var2= %g\n",var1, var2); printf("prod= %g\n" "sum= %g\n", prod, sum);}/* function definition */ void prod_sum(double A, double B, double *rslt_prod, double *rslt_sum) { *rslt_prod = A * B; *rslt_sum = A + B; }
![Page 40: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/40.jpg)
Array and String – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 40
Pointers and Arrays • Recall that the value of an array name is also an address
void main(){
int x[10];ReOrder(x); // ReOrder(&x);
}void ReOrder(int *x){
int i, j, t;for(i = 0; i < 9; i++) for(j = i + 1; i < 10; ++j) if(x[i] < x[j]) { t = x[i]; x[i] = x[j]; x[j] = t; }
}
![Page 41: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/41.jpg)
Array and String – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 41
Organizing Multi-File Programs• A large C program should be divided into multiple files
// main.c#include <stdio.h>void Test(){ // …}int main(){ // … return 0;}
// math.cdouble mathVar;double sin(){ double tempSin; // … return tempSin;}
![Page 42: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/42.jpg)
Array and String – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 42
Identifiers and Scope• Identifier
– The name of a variable, function, label, etc.• int my_var1; /* a variable */• pow_table(); /* a function */• start: /* a label */
• Question:– Does it make a difference where in a program an
identifier is declared?YES! --> concept of ‘scope’
![Page 43: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/43.jpg)
Array and String – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 43
Scope of Identifiers• Scope of a declaration of an identifier
– The region of the program that the declaration is active (i.e., can access the variable, function, label, etc.)
• Five types of scope:– Program (global scope)– File– Function prototype– Function– Block ("between the { } scope")
![Page 44: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/44.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 44
Scope of Identifiers - Program Scope• Program (global) scope
– if declared outside of all functions
– "Visible" to all functions from point of declaration
– Visible to functions in other source files
– Use only when necessary and then very carefully!!
– If there exist a local variable and a global variable with the same name, the compiler will refer to the local variable
#include <stdio.h>int a = 10;double product(double x, double y);
int main(){ double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); // …}/* function definition */ double product(double x, double y){ double result; a = 20; result = x * y; return result;}
a = 10
a = 20
![Page 45: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/45.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 45
An Example// File name: main.c#include <stdio.h>int a = 10;
/* function definition */ double product(double x, double y){ double result; // … a = 70; return result;}
int main(){ a = 80;}
// File name: ExternFile.cextern int a = 10;/* function definition */ void TestExtern(){ // … a = 90; // …}
![Page 46: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/46.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 46
Scope of Identifiers - File Scope• File scope
– Keyword static• Makes variable a ‘visible’
only within this source file– Use file scope to avoid
naming conflict if multiple source files are used
#include <stdio.h>static int a = 10;double product(double x, double y);
int main(){ double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); // …}/* function definition */ double product(double x, double y){ double result; result = x * y; return result;}
![Page 47: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/47.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 47
An Example// File name: main.c#include <stdio.h>static int a = 10;
/* function definition */ double product(double x, double y){ double result; // … a = 70; return result;}
int main(){ a = 80;}
// File name: ExternFile.cextern int a = 10;/* function definition */ void TestExtern(){ // … a = 90; // …}
![Page 48: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/48.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 48
• Function prototype scope– Identifiers x and y are not
visible outside the prototype
– Thus, names in the prototype do not have to match names in the function definition
• MUST match types, however!
Scope of Identifiers - Function Prototype Scope#include <stdio.h>double product(double x, double y);
int main(){ int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); printf("var1 = %.2f\n" "var2 = %.2f\n",var1,var2); printf("var1*var2 = %g\n", ans);}/* function definition */ double product(double A, double B) { double result; result = A * B; return result; }
![Page 49: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/49.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 49
• Function scope– Active from the beginning to the end of a function
Scope of Identifiers - Function Scope
#include <stdio.h>
int main(){ int a; // … return 0;}
int FunctionScopeTest(){ int b; // … return 0;}
![Page 50: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/50.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 50
Scope of Identifiers - Block Scope• Block (local) scope
– A block is a series of statements enclosed in braces { }
– The identifier scope is active from the point of declaration to the end of the block ( } )
– Nested blocks canboth declare the same variable name and not interfere
#include <stdio.h>double product(double x, double y);
int main(){ int a = 10; double var1 = 3.0, var2 = 5.0; double ans; ans = product(var1, var2); // … }/* function definition */ double product(double x, double y){ double result; // a = 60; Error result = x * y; return result;}
![Page 51: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/51.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 51
An Example#include <stdio.h>int a = 10;int f1(){ int a; a = 70; { int a;
a = 100; } return a;}
void main(){ a = 80; f1();}
a = 10
a = 80
a = ?
a = 70
a = 100
a = 70
![Page 52: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/52.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 52
Storage Classes• Refers to the lifetime of a variable
• Local variables only exist within a function by default. When calling a function repeatedly, we might want to– Start from scratch – reinitialize the variables
• The storage class is ‘auto’– Continue where we left off – remember the last value
• The storage class is ‘static’
• Another two storage classes (seldomly used)– register (ask to use hardware registers if available)– extern (global variables are external)
![Page 53: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/53.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 53
Auto storage class• Variables with automatic storage duration are created
when the block in which they are declared is entered, exist when the block is active and destroyed when the block is exited.
• The keyword auto explicitly declares variables of automatic storage duration. It is rarely used because when we declare a local variable, by default it has class storage of type auto.– int a, b; // is the same as – auto int a, b;
![Page 54: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/54.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 54
Static storage class• However the static keyword can be applied to
a local variable so that the variable still exist even though the program has gone out of the function. As a result, whenever the program enters the function again, the value in the static variable still holds
![Page 55: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/55.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 55
Auto - Example#include <stdio.h>void auto_example(void);
int main(void){
int i;
printf("Auto example:\n");
auto_example( );auto_example( );auto_example( );
return(0);
}void auto_example(void){
auto int num = 1;
printf(" %d\n",num);num = num + 2;
}
Auto example:111Press any key to continue
![Page 56: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/56.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 56
Static - Example#include <stdio.h>void auto_example(void);
int main(void){
int i;
printf("Static example:\n");static_example( );static_example( );static_example( );return(0);
}void static_example(void){
static int num = 1;
printf(" %d\n",num);num = num + 2;
}
Static example:135Press any key to continue
![Page 57: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/57.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 57
Recursion• Recursion is a technique that solves a problem by solving a smaller problem of the
same type
• A recursive function is a function invoking itself, either directly or indirectly– Recursion: A → B → C → D → A
• Concept of recursive function (generally):– A recursive function is called to solve a problem
– The function only knows how to solve the simplest case of the problem. When the simplest case is given as an input, the function will immediately return with an answer
– However, if a more complex input is given, a recursive function will divide the problem into 2 (or more) pieces: a part that it knows how to solve and another part that it does not know how to solve
if (stopping case) solve itelse reduce the problem using recursion
![Page 58: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/58.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 58
Recursion• Any problem that can be solved recursively can also be
solved iteratively (using loop)
• Recursive functions are slow and takes a lot of memory space compared to iterative functions
• So why bother with recursion? There are 2 reasons:– Recursion approach more naturally resembles the problem
and therefore the program is easier to understand and debug– Iterative solution might not be apparent
![Page 59: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/59.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 59
An Example: xy
• In this example, we want to calculate x to the power of y – i.e. xy
• If we analyze the formula for xy, we could see that xy could be written as (x being multiplied to itself, y times)– An example is 24, which can be written as
24 = 2 x 2 x 2 x 2 (in this case, x = 2, y = 4)– 24 could also be rewritten as
24 = 21 x 23 where 21 = 2 (i.e the number itself)
• Therefore, we could divide the problem into two stage:– Simplest case: when y = 1, the answer is x– Recursive case, we need to solve for x * x(y-1)
![Page 60: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/60.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 60
Recursion solution of xy
#include <stdio.h>double XpowerY(double, int);int main(void){
double power, x; int y;printf("Enter the value of x and y:\n");scanf("%lf%d", &x, &y);power = XpowerY(x, y);printf("%.2f to the power of %d is %.2f\n\n", x, y, power);return(0);
}double XpowerY(double x, int y){
if (y ==1)return x;
elsereturn x * XpowerY(x, y-1);
}
Enter the value of x and y:232.00 to the power of 3 is 8.00Press any key to continue
![Page 61: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/61.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 61 10-61
How C Maintains the Recursive Steps• C keeps track of the values of variables by the
stack data structure.– Recall that stack is a data structure where the last
item added is the first item processed– There are two operations (push and pop) associated
with stack
abc
bc
dbc
pop push d
![Page 62: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/62.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 62
How C Maintains the Recursive Steps• Each time a function is called, the execution
state of the caller function (e.g., parameters, local variables, and memory address) are pushed onto the stack
• When the execution of the called function is finished, the execution can be restored by popping up the execution state from the stack
![Page 63: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/63.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 63
Recursive Steps of xy
#include <stdio.h>double XpowerY(double, int);int main(void){
double power, x; int y;printf("Enter the value of x and y:\n");scanf("%lf%d", &x, &y);power = XpowerY(x, y);printf("%.2f to the power of %d is %.2f\n\n", x, y, power);return(0);
}double XpowerY(double x, int y){
if (y ==1)return x;
elsereturn x * XpowerY(x, y-1);
}
x = 2; y = 4;x * XpowerY(2, 3)
x = 2; y = 3;x * XpowerY(2, 2)
x = 2; y = 2;x * XpowerY(2, 1)
x = 2; y = 2;return x;
2 * 8
2
2 * 2
2 * 4
![Page 64: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/64.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 64
Factorial• Analysis:
– n!= n * (n-1) * (n-2) * (n-3) * (n-4) ……… * 1– n! could be rewritten as n * (n-1)!– Example: 5! = 5 * 4 * 3 * 2 * 1 = 5 * (4)!, where n = 5– Fact: 0! Or 1! is equal to 1
• Therefore, we could divide this problem into two stages for n!:– Simplest case: if (n <= 1), answer is 1– Recursive case: we need to solve for n * (n-1)!
![Page 65: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/65.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 65
Factorial#include <stdio.h>double fact(double);int main(void){
double n, result;printf("Please enter the value of n:");scanf("%lf", &n);
result = fact(n);printf(" %.f! = %.2f\n", n, result);return(0);
}double fact(double n){
if (n <= 1)return 1;
elsereturn n * fact(n-1);
}
Enter the value of n: 33! = 6.00Press any key to continue
int fact(int n){ int factres = 1; while(n>1) { factres = factres*n; n--; } return (factres);}
![Page 66: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/66.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 66
Reuse of factorial function• Write a statement to compute
// Enter X, Z, K, D…y = (fact(X) + fact(Z) * 5) / (fact(K) - fact(D));
!!5!*!
DKZXy
![Page 67: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/67.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 67
Reuse of factorial function• Write a select function that takes n and k and
computes "n choose k" where
int select(int n, int k){ return fact(n) / (fact(n-k) * fact(k));}
!)!(!kkn
nkn
![Page 68: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/68.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 68
Fibonacci• Fibonacci Sequence
1, 1, 2, 3, 5, 8, 13, 21, …1st 2nd 3rd 4th 5th 6th 7th 8th
– Fib(1) = 1 defined base case
– Fib(2) = 1 defined base case
– Fib(3) = 2 = 1 + 1– Fib(2) + Fib(1)
– Fib(7) = 13 = 8 + 5– Fib(6) + Fib(5)
• Fib(n) = Fib(n-1) + Fib(n-2)
![Page 69: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/69.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 69
Fibonacciint Fib (int n){ int temp = 1; /* handles base cases */ if (n > 2)
temp = Fib(n-1) + Fib(n-2); return temp;}
/* Iterative Version */int fibonacci(int k){ int a,b,c,i; if (k <= 1) return 1; else { a = 1; b = 1; i = 2; while (i <= k) {
c = a + b; a = b; b = c; i++;
} return(c); }}
![Page 70: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/70.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 70
Fibonacci
int Fib (int x){ /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (x > 2) /* other cases */ temp = Fib(x-1) + Fib(x-2); return temp;}
x = 5; temp = 1;
temp = Fib(4) + Fib(3);return temp;
x = 1; temp = 1;
return temp;
x = 4; temp = 1;
temp = Fib(3) + Fib(2);return temp;
x = 5; temp = 1;
temp = Fib(2) + Fib(1);return temp;
x = 1; temp = 1;
return temp;x = 1; temp = 1;
return temp;
x = 5; temp = 1;
temp = Fib(2) + Fib(1);return temp;
x = 1; temp = 1;
return temp;
x = 1; temp = 1;
return temp;
x = 5; temp = 1;
temp = 1 + Fib(1);return temp;
x = 5; temp = 1;
temp = 1 + 1;return temp;
x = 4; temp = 1;
temp = 2 + Fib(2);return temp;
x = 4; temp = 1;
temp = 2 + 1;return temp;
x = 5; temp = 1;
temp = 3 + Fib(3);return temp;
x = 5; temp = 1;
temp = 1 + Fib(1);return temp;
x = 5; temp = 1;
temp = 1 + 1;return temp;
x = 5; temp = 1;
temp = 3 + 2;return temp;
![Page 71: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/71.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 71
Fibonacci
fib(5)
fib(4) fib(3)
fib(3) fib(2)
fib(2) fib(1)
fib(2) fib(1)
1
1
1
12 1
3 2
5int Fib (int n){ /* handles base cases of */ /* Fib(1) and Fib(2) */ int temp = 1; if (n > 2) /* other cases */ temp = Fib(n-1) + Fib(n-2); return temp;}
![Page 72: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/72.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 72
Exercise• Write a function to compute logba
# include <math.h>double log_any_base(double a, double b){ return log(a) / log(b);}
baab
10
10
logloglog
![Page 73: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/73.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 73
Exercise#include <stdio.h>int function1(int x){ x = 2; return(x+1);}int function2(int *x){ *x = 2; return(*x+1);}int main(){ int x = 4, y1, y2; y1 = x + function1(++x); // y1? y2 = ++x + function2(&x); // y2? return 0;}
![Page 74: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/74.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 74
Exercise• What is the output of the following program
void function2(){ printf("In function 2\n");}void function1(){ function2(); printf("In function 1\n");}
#include <stdio.h>// function prototypes void function3(){ printf("In function 3\n"); function2();}
int main(){ function1(); function3(); return 0;}
In function 2In function 1In function 3In function 2
![Page 75: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/75.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 75
Exercise• Given radius and height of a cylinder. Write a
function to compute the surface area– A = 2*pi*r*(r*h)
#define PI 3.14double area(double radius, double height){
return 2 * PI * radius * (radius+height);}
![Page 76: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/76.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 76
Exercise• Write a function to compute the median of 3
numbers x, y and z• Possible order of numbers
– x<y<z -> median y– x<z<y -> median z– y<x<z -> median x– y<z<x -> median z– z<x<y -> median x– z<y<x -> median y
int median(int x, int y, int z){
if (((x < y) && (y < z)) || ((z < y) && (y < x))) return y;
else if (((y < x) && (x < z)) || ((z < x) && (x < y))) return x;
return z;}
![Page 77: Fundamental of Programming (C)](https://reader035.vdocuments.us/reader035/viewer/2022062501/568166ea550346895ddb31db/html5/thumbnails/77.jpg)
Modular programming – Lecture 7
Sharif University of TechnologyDepartment of Computer Engineering 77
Exercise• Recursive Definitions of gcd
– A: Euclid’s algorithm makes use of the fact that gcd(x,y ) = gcd(y, x mod y)
otherwiseif
),mod,gcd(0 ,
),gcd(yxy
yxyx
int gcd (unsigned int x, unsigned int y) { if (y == 0 ) return x; return gcd(y, x % y);}