fundamental of programming (c) group...
TRANSCRIPT
Lecturer: Vahid Khodabakhshi
Sharif University of TechnologyDepartment of Computer Engineering
Bo
rro
wed
fro
m le
ctu
rer
no
tes
by
Om
id J
afar
ine
zhad
Fundamental of Programming (C) Group 4
Lecture 6
Modular programming
CE 40153 - Spring 99
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 2/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 3/77
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, thevalue is actually placed to the memory thatwas allocated– x=3;
00000000
00000000
00000000
00000011
x
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 4/77
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 ……
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 5/77
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 */
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 6/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 7/77
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
0x1008
ptr1:
ptr2:
0x100C
0x1010
0x1014
1
2
0x1000
0x1000
3
3
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 8/77
An Exampleint m=3, n=100, *p, *q;
p=&m;
printf("m is %d\n",*p); // 3
m++;
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
qpnm
....??1003
qpnm
....?1003
qpnm
....?1004
*p
qpnm
....?1004
*pqpnm
....5004
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 9/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 10/77
Functions - Mathematical View
32)( 2
xxxf
11 is )2(
113443)2(2)2()2( 2
f
f
f(2)? isWhat
)(xf2 11
X FunctionReturned
value
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 11/77
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(){
…}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 12/77
Pre-defined library functions • The C standard library is a standardized
collection of header files and libraryfunctions, which are used to implementcommon operations
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 13/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 14/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 15/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 16/77
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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 17/77
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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 18/77
Random numbers generation functions• int rand();
– Returns a uniformly distributed pseudo-random integral valuebetween 0 and RAND_MAX (0 and RAND_MAX included)
– RAND_MAX : Expands to an integer constant expression equal to themaximum value returned by the function rand(). This value isimplementation dependent.• #define RAND_MAX 32767 /*implementation defined*/
– srand() should be called before any calls to rand() to initialize therandom number generator
• void srand( unsigned seed );– Initializes the built-in random number generator used to generate
values for rand() with the seed value seed
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 19/77
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. */}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 20/77
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. */}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 21/77 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;
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 22/77
User- defined
OR
Programmer-defined function
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 23/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 24/77
An ExampleFunction 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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 25/77
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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 26/77
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 thenumber of formal parameters in the function definition
• A one-to-one correspondence must occur among the actual and formalparameters. The first actual parameter must correspond to the first formalparameter 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 correspondingformal parameter
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 27/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 28/77
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 specifiedorder
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 29/77
Functions that do not return a value
• Use the return type of void
– void functionName( DataType arg_1,…)
– void functionName()
– void functionName( void)
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 30/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 31/77
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( ));
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 32/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 33/77
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: 5
Enter a number: 4
Sum is 9
Press any key to continue
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 34/77
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: 5
Enter a number: 4
Sum is 9
Press any key to continue
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 35/77
Call by value And Call by reference• Call by value
– In this method, only the copy of variable’s value (copy ofactual parameter’s value) is passed to the function. Anymodification to the passed value inside the function willnot affect the actual value
– In all the examples that we have seen so far, this is themethod that has been used
• Call by reference– In this method, the reference (memory address) of the
variable is passed to the function. Any modificationpassed done to the variable inside the function will affectthe actual value
– To do this, we need to have knowledge about pointers andarrays
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 36/77
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 notchanged
#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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 37/77
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:
4
9
4 + 9 = 13
Press any key to continue
?num2
?num1
?sum
4num2
9num1
?sum
4val2
9val1
?sum
4val2
9val1
13sum
100val2
9val1
13sum
4num2
9num1
13sum
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. */
}
main5b
1a
CalByVal5b
1a
CalByVal10b
0aCalByRefb
a
main-5b
0a
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;
}
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;}
}
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;
}
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’
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 isactive (i.e., can access the variable, function, label,etc.)
• Five types of scope:– Program (global scope)– File– Function prototype– Function– Block ("between the { } scope")
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 44/77
Scope of Identifiers - Program Scope• Program (global) scope
– if declared outside of allfunctions
– "Visible" to all functions from point of declaration
– Visible to functions in other source files
– Use only when necessaryand then very carefully!!
– If there exist a local variableand a global variable withthe same name, thecompiler will refer to thelocal 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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 45/77
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.c
extern int a = 10;
/* function definition */
void TestExtern()
{
// …
a = 90;
// …
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 46/77
Scope of Identifiers - File Scope
• File scope
– Keyword static• Makes variable a ‘visible’
only within this source file
– Use file scope to avoidnaming conflict if multiplesource 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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 47/77
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.c
extern int a = 10;
/* function definition */
void TestExtern()
{
// …
a = 90;
// …
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 48/77
• Function prototype scope– Identifiers x and y are not
visible outside the prototype
– Thus, names in the prototypedo not have to match names inthe 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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 49/77
• 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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 50/77
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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 51/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 52/77
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)
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 53/77
Auto storage class• Variables with automatic storage duration are
created when the block in which they aredeclared is entered, exist when the block is activeand destroyed when the block is exited.
• The keyword auto explicitly declares variables ofautomatic storage duration. It is rarely usedbecause when we declare a local variable, bydefault it has class storage of type auto.– int a, b; // is the same as– auto int a, b;
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 54/77
Static storage class• However the static keyword can be applied to
a local variable so that the variable still existeven though the program has gone out of thefunction. As a result, whenever the programenters the function again, the value in thestatic variable still holds
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 55/77
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:
1
1
1
Press any key to continue
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 56/77
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:
1
3
5
Press any key to continue
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 57/77
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 simplestcase 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 knowhow to solve
if (stopping case)solve it
elsereduce the problem using recursion
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 58/77
Recursion• Any problem that can be solved recursively can also be
solved iteratively (using loop)
• Recursive functions are slow and takes a lot of memoryspace 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 anddebug
– Iterative solution might not be apparent
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 59/77
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 as24 = 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)
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 60/77
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;
else
return x * XpowerY(x, y-1);
}
Enter the value of x and y:
2
3
2.00 to the power of 3 is 8.00
Press any key to continue
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 61/77 10-61
How C Maintains the Recursive Steps
• C keeps track of the values of variables by thestack data structure.
– Recall that stack is a data structure where the lastitem added is the first item processed
– There are two operations (push and pop) associatedwith stack
a
b
c
b
c
d
b
c
pop push d
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 62/77
How C Maintains the Recursive Steps
• Each time a function is called, the executionstate of the caller function (e.g., parameters,local variables, and memory address) arepushed onto the stack
• When the execution of the called function isfinished, the execution can be restored bypopping up the execution state from the stack
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 63/77
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;
else
return 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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 64/77
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 twostages for n!:– Simplest case: if (n <= 1), answer is 1– Recursive case: we need to solve for n * (n-1)!
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 65/77
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: 3
3! = 6.00
Press any key to continue
int fact(int n){
int factres = 1;while(n>1){
factres = factres*n;n--;
}return (factres);
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 66/77
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!*!
DK
ZXy
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 67/77
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
n
k
n
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 68/77
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)
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 69/77
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);
}
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 70/77
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;
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 71/77
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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 72/77
Exercise• Write a function to compute logba
# include <math.h>
double log_any_base(double a, double b)
{
return log(a) / log(b);
}
b
aab
10
10
log
loglog
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 73/77
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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 74/77
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
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 75/77
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.14
double area(double radius, double height)
{
return 2 * PI * radius * (radius+height);
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 76/77
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;
}
Modular programming – Lecture 6
Sharif University of TechnologyDepartment of Computer Engineering 77/77
Exercise• Recursive Definitions of gcd
– A: Euclid’s algorithm makes use of the fact that gcd(x,y ) = gcd(y, x mod y)
otherwise
if
),mod,gcd(
0 ,),gcd(
yxy
yxyx
int gcd (unsigned int x, unsigned int y) {
if (y == 0 ) return x;return gcd(y, x % y);
}