Unit 7. Functions

66
UNIT 7 FUNCTIONS

Transcript of Unit 7. Functions

Page 1: Unit 7. Functions

UNIT 7FUNCTIONS

Page 2: Unit 7. Functions

05/01/2023 Ashim Lamichhane 2

• A function is a group of statements that together perform a task.

• Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

• You can divide up your code into separate functions.

• How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.

Page 3: Unit 7. Functions

05/01/2023 Ashim Lamichhane 3

• Suppose a program where a set of operations has to be repeated often, though not continuously.

• Loops seems like a better option.

• Instead of inserting the program statements for these operations at so many places, a separate program segment is written and compiled it separately.

• As many times as it is needed, the segment program is called.

• The separate program segment is called a function.

Page 4: Unit 7. Functions

05/01/2023 Ashim Lamichhane 4

• Suppose we have to calculate a nCr

nCr = n!/(n-r)!r!

• Without using function:for(i=1;i<=n;i++){

f1*=1;}for(i=1;i<=(n-r);i++){

f2*=1;}for(i=1;i<=r;i++){

f3*=1;}comb=f1/(f2*f3);

Page 5: Unit 7. Functions

05/01/2023 Ashim Lamichhane 5

Advantages of Function• Manageability• Easier to write and keep track of.• Easier to understand and maintain

• Code Reusability• Can be used multiple times

• Non-redundant programming• Same function can be called when needed.

• Logical Clarity• Reduced number of code in main function.

• Easy to divide the work to many different programmers.• Large work can be divided by writing different functions.

Page 6: Unit 7. Functions

05/01/2023 Ashim Lamichhane 6

• The C Functions can be classified into two categories:

1. User defined function

2. Library Functions

Page 7: Unit 7. Functions

05/01/2023 Ashim Lamichhane 7

Library functions (Built-in functions)• These are the functions which are already written,

compiled and placed in C library and they are not required to be written by a programmer.

• The function’s name, its return type, their argument number and types have been already defined.

• We can use these functions as required.

• Ex: printf(), scanf(), sqrt(), getch() are example of library functions.

Page 8: Unit 7. Functions

05/01/2023 Ashim Lamichhane 8

User – defined functions• These are functions which are defined by user at the

time of writing a program.

• The user has choice to choose its name, return type, arguments and their types.

• The job of each user-defined function is as defined by the user

• A complex C problem can be divided into a number of user-defined functions.

Page 9: Unit 7. Functions

05/01/2023 Ashim Lamichhane 9

main() function• The function main() is an user defined function except

that the name of function is defined or fixed by the language.

• The return type, argument and body of the function are defined by the programmer as required.

• The function is executed first, when the program starts execution.

Page 10: Unit 7. Functions

05/01/2023 Ashim Lamichhane 10

Components associated with function• Function Definition• Function declaration or prototype• Return Statement• Accessing/Calling a function

Page 11: Unit 7. Functions

05/01/2023 Ashim Lamichhane 11

Function definition• The collection of program statements that describes the specific task to

be done by the function is called function definition.

• It consists of function header, which defines function’s name, its return type and its argument list and a function body, which is a block of code enclosed in parenthesis.

• Syntax:return_type function_name(data_type variable1, data_type variable2,…..) { …...statements;.....}

Page 12: Unit 7. Functions

05/01/2023 Ashim Lamichhane 12

All the parts of a function• Return Type:• A function may return a value. • The return_type is the data type of the value the function

returns.• Some functions perform the desired operations without

returning a value. In this case, the return_type is the keyword void.

• Function Name• This is the actual name of the function. • The function name and the parameter list together constitute

the function signature.

Page 13: Unit 7. Functions

05/01/2023 Ashim Lamichhane 13

• Parameters (data_type variable1, data_type variable2,….. )• A parameter is like a placeholder. • When a function is invoked, you pass a value to the

parameter. • This value is referred to as actual parameter or argument. • The parameter list refers to the type, order, and number of the

parameters of a function. • Parameters are optional; that is, a function may contain no

parameters.

• Function Body• The function body contains a collection of statements that

define what the function does.

Page 14: Unit 7. Functions

05/01/2023 Ashim Lamichhane 14

int add(int a,int b){ //function headerint sum; // function body (statements)sum=a+b; // function body (statements)return sum; // returns value of sum to

whoever called}----------------------------------------------------------------------------------------------float areaOfCircle(float radius){ //function header

return 3.1428*radius*radius; // returns radius to whoever called

}

Page 15: Unit 7. Functions

05/01/2023 Ashim Lamichhane 15

Function Declaration or Prototype• The function declaration or prototype is model or

blueprint of the function.

• If functions are used before they are defined, then function declaration or prototype is necessary which provides the following information to the compiler• The name of the function• The type of the value returned by the function• The number and the type of arguments that must be supplied

when calling the function.

Page 16: Unit 7. Functions

05/01/2023 Ashim Lamichhane 16

Function Declaration or Prototype (cont…)• A function declaration tells the compiler about a function name and how to

call the function. The actual body of the function can be defined separately.

• A function declaration has the following parts −return_type function_name( parameter list );

• For the above defined function add(),the function declaration is as follows−int add(int num1, int num2);

float areaOfCircle(float radius);int max(int n1,int n2);

Page 17: Unit 7. Functions

05/01/2023 Ashim Lamichhane 17

Return Statement• It is the statement that is executed just before the function

completes its job and control is transferred back to the calling function.• The job of return statement is to hand over some value given by

function body to the point where the call was made.• Two purposes of return statement:• Immediately transfer the control back to the calling program• It returns the value to the calling function.

• SYNTAX:return (expression);

• A function may or may not return a value. If a function doesn't return a value the return type in the function definition and declaration is specified as void.

Page 18: Unit 7. Functions

05/01/2023 Ashim Lamichhane 18

Accessing/Calling a function• A function can be called or accessed by specifying its name, followed by a

list of arguments enclosed in parenthesis and separated by commas.

• Ex:• a function add() with two arguments is called by add(a,b) to add two numbers.• If function call doesn’t require any arguments any empty pair of parenthesis must

follow the name of function.

• General Form:• If function has parameters but it doesn’t return value

• function_name(variable1, variable2…);• If function has no arguments and it doesn’t return value

• function_name();• If function has parameters but it returns value

• variable_name=function_name(variable1, variable2…);• If function has no arguments and it does return value

• variable_name=function_name();

Page 19: Unit 7. Functions

05/01/2023 Ashim Lamichhane 19

/* function definition of add() function which takes two integers and returns sum of them as integer */#include <stdio.h> int add(int a,int b){

int sum; sum=a+b; return sum; }

float areaOfCircle(float radius){return 3.1428*radius*radius;}

int main(void){ int a,b,mysum; float myfloat; printf("Enter two numbers\n"); scanf("%d%d",&a,&b); mysum=add(a,b); printf("VALUE: %d\n", mysum); myfloat=areaOfCircle(mysum); printf("So area of circle is: %f\n",myfloat );

}

/* function definition of add() function which takes two integers and returns sum of them as integer */#include <stdio.h> int add(int , int ); // Int add(int a, int b);float areaOfCircle(float ) //float areaOfCircle(float r)int main(void){

int a,b,mysum; float myfloat; printf("Enter two numbers\n"); scanf("%d%d",&a,&b); mysum=add(a,b); printf("VALUE: %d\n", mysum); myfloat=areaOfCircle(mysum); printf("So area of circle is: %f\n",myfloat );

}int add(int a,int b){

int sum; sum=a+b; return sum; }

float areaOfCircle(float radius){return 3.1428*radius*radius;}

Page 20: Unit 7. Functions

05/01/2023 Ashim Lamichhane 20

Question• Define a function whatIsYourName() which asks for your

and returns your name to main function and you print that name in the main function.

• Define a function myPercentage() which calculates the percentage of the marks in two subjects and marksGotInExams() asks for marks in two subjects and returns your marks and percentage to the main function.

Page 21: Unit 7. Functions

05/01/2023 Ashim Lamichhane 21

#include <stdio.h> int total(float a,float b){ return a+b; }float percentage(float total){

return total/2;} int main(void){ float a,b,mysum; float myfloat; printf("Enter marks in two subjects: \n"); scanf("%f%f",&a,&b); mysum=total(a,b); printf("My total in two subjects: %.2f\n", mysum); myfloat=percentage(mysum); printf("My percentage is: %.2f \n",myfloat ); }

Page 22: Unit 7. Functions

05/01/2023 Ashim Lamichhane 22

Category of functions according to the return value and arguments

• Category 1: Functions with no arguments and no return values

• Category 2: Functions with arguments and no return values

• Category 3: Function with arguments and return values

Page 23: Unit 7. Functions

05/01/2023 Ashim Lamichhane 23

Category 1: Functions with no arguments and no return values

• When function has no arguments, it does not receive any data from the calling function.

• Similarly when it doesn’t return a value, the calling function does not receive any data from the called function.

• Thus, in such type of function’s there is no data transfer between the calling function and the called function.

Page 24: Unit 7. Functions

05/01/2023 Ashim Lamichhane 24

void function_name(){

/* body of function */

}

• Keyword void means the function doesn’t return any value.• There is no arguments within parenthesis which implies

function has no argument and it doesn’t receive any data from the called function.

Page 25: Unit 7. Functions

05/01/2023 Ashim Lamichhane 25

Ex:void addition(){Int a,b,sum;Printf(“enter any two numbers: \t”);Scanf(“%d%d”,&a,&b);sum=a+b;Printf(“\n the sum is : \t”,sum);}

void main(){clrscr();addition();getch();}

Page 26: Unit 7. Functions

05/01/2023 Ashim Lamichhane 26

Category 2: functions with arguments but no return value

void function_name(argument list){Body of a function}

• We pass arguments while calling a function but nothing is returned to the calling function from.

Page 27: Unit 7. Functions

05/01/2023 Ashim Lamichhane 27

Ex:void addition(int a,int b){int sum=0;sum=a+b;printf(“\n the sum is : \t”,sum);}

void main(){int a ,b;clrscr();printf(“enter any two numbers: \t”);Scanf(“%d%d”,&a,&b);addition(a,b);getch();}

Page 28: Unit 7. Functions

05/01/2023 Ashim Lamichhane 28

Category 3: Function with arguments and return values

• We pass arguments • We expect a return value

return_type function_name(argument_list){

/* Body of the function */

return something;}

Page 29: Unit 7. Functions

05/01/2023 Ashim Lamichhane 29

Ex:int addition(int a,int b){int sum=0;sum=a+b;return sum;}

void main(){int a ,b,sum;clrscr();printf(“enter any two numbers: \t”);scanf(“%d%d”,&a,&b);sum=addition(a,b);printf(“\n the sum is : ”,sum);getch();}

Page 30: Unit 7. Functions

05/01/2023 Ashim Lamichhane 30

Passing arrays to function• It is possible to pass the value of an array element and even an entire

array as an argument to a function.

• To pass an entire array to a function, the array name must appear by itself, without brackets or subscripts, as an actual argument in function call statement.

• When declaring a one-dimensional array as a formal argument, the array name is written with a pair of empty square brackets. The size of the array is not specified within the formal argument declaration.

Page 31: Unit 7. Functions

05/01/2023 Ashim Lamichhane 31

• Syntax for function call passing array as argument,function_name(array_name)

• Syntax for function prototype which accepts arrayreturn_type function_name(data_type array_name[]);Orreturn_type function_name(data_type *pointer_variable);

• When array is passed to a function, the values of the array elements are not passed to the function rather the array name is interpreted as the address of the first array element.• The address assigned to the corresponding formal argument when

the function is called.• The formal argument therefore becomes a pointer to the first array

element.

Page 32: Unit 7. Functions

05/01/2023 Ashim Lamichhane 32

#include <stdio.h>void display(int n){

printf("%d\t", n );}

int main(void){int nums[5]={100,23,44,3,65},i;printf("\nThe content of array is: \n");for (int i = 0; i < 5; i++){

display(nums[i]);}

}

Page 33: Unit 7. Functions

05/01/2023 Ashim Lamichhane 33

WAP to illustrate passing an entire array to a function#include <stdio.h>void change(int a[]){

a[0]=10;a[1]=20;a[2]=30;a[3]=40;a[4]=50;}

int main(void){int nums[5]={100,23,44,3,65},i;printf("\nBEFORE FUNCTION CALL: \n");for (int i = 0; i < 5; i++) {printf("\t%d",nums[i]);}printf("\n");change(nums); /* PASSING ARRAYS NUMS TO FUNCTION */printf("\nAFTER FUNCTION CALL\n");for (int i = 0; i < 5; i++) {printf("\t%d",nums[i]);

} printf("\n");}

Page 34: Unit 7. Functions

05/01/2023 Ashim Lamichhane 34

Passing Strings to Functions#include <stdio.h> void Display(char ch[]); int main(){

char c[50]; printf("Enter string: "); gets(c); Display(c); // Passing string c to function. return 0;

} void Display(char ch[]){

printf("String Output: "); puts(ch);

}• Here, string c is passed from main() function to user-defined function Display(). In function declaration, ch[] is

the formal argument.

Page 35: Unit 7. Functions

05/01/2023 Ashim Lamichhane 35

Different types of function call

• The arguments in function can be passed in two ways:• Pass arguments by value• Pass arguments by address or reference or points

Page 36: Unit 7. Functions

05/01/2023 Ashim Lamichhane 36

Function call by Value (Pass arguments by value)

• When values of actual arguments are passed to the function as arguments, its known as function call by value.

• In this call, the value of each actual argument is copied into corresponding formal argument of the function definition.

Page 37: Unit 7. Functions

05/01/2023 Ashim Lamichhane 37

/* A program to illustrate function call by value */#include <stdio.h>void swap(int, int); /* function prototype */int main(void){

int a=99,b=98;printf("BEFORE function calling a and b are: %d \t %d\n",a,b);swap(a,b); /* function call by value */printf("After calling function, a and b are: %d\t %d\n",a,b );

}void swap(int x, int y){

int temp;temp=x;x=y;y=temp;printf("The values within functions are %d\t%d\n",x,y);

}

Page 38: Unit 7. Functions

05/01/2023 Ashim Lamichhane 38

#include <stdio.h> void swap(int x, int y); /* function declaration */ int main () { int a = 100; int b = 200; /* local variable definition */ printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); swap(a, b); /* calling a function to swap the values */ printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0; }/* function definition to swap the values */ void swap(int x, int y) {

int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ return;

}

Page 39: Unit 7. Functions

05/01/2023 Ashim Lamichhane 39

Function Call by Reference (Pass argument by address)

• In this type of function call, the address of variable is passed as an argument instead of actual value of variable.

• Using this method, the original values are changed if they are changed within the function

• We need pointer for this. Detail study of pointer will be on next unit.

• Pointer: a pointer is a variable that stores a memory address of a variable.

• Pointer is declared in the same fashion like other variables but is always preceded by ‘*’ (asterisk) operator.

Ex. int *a; float *b; char *c;

• Here a,b and c are pointer variables which stores address of integer, float and char variables

Page 40: Unit 7. Functions

05/01/2023 Ashim Lamichhane 40

int *a; float *b ; char *c; int x; float y; char z;

/* now we can do */

a=&x; /* the address of x is assigned to pointer variable a */ b=&y; /* the address of float variable y is stored in pointer variable b */ c=&z; /* the address of char variable z is stored in pointer variable c */

Page 41: Unit 7. Functions

05/01/2023 Ashim Lamichhane 41

WAP to swap the values of two variables using call by reference

void swap(int *,int *); void main(){

int a=99,b=98;printf("BEFORE function calling a and b are: %d \t %d\n",a,b);swap(&a,&b); /* function call by reference*/printf("After calling function, a and b are: %d\t %d\n",a,b );

}void swap(int *x, int *y){

int temp;temp=*x;*x=*y;*y=temp;

}

Page 42: Unit 7. Functions

05/01/2023 Ashim Lamichhane 42

#include <stdio.h> void swap(int *x, int *y); /* function declaration */ int main () { int a = 100; int b = 200; /* local variable definition */

printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); /* calling a function to swap the values. &a indicates pointer to a ie. address of variable a and &b indicates pointer to b ie. address of variable b. */ swap(&a, &b); printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0;

}void swap(int *x, int *y) { /* function definition to swap the values */ int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */ return; }

Page 43: Unit 7. Functions

05/01/2023 Ashim Lamichhane 43

Recursive function

• A recursive function is one which calls itself. 

• Recursive functions are useful in evaluating certain types of mathematical function.

• The function is called recursive function if it calls to itself and recursion is a process by which a function calls itself repeatedly until some specified condition is satisfied.

Page 44: Unit 7. Functions

05/01/2023 Ashim Lamichhane 44

Recursive function• To solve a problem using recursive method, two

conditions must be satisfied. They are:

• Problem could be written or defined in term of its previous result.

• Problem statement must include a stopping condition i.e. we must have an if statement somewhere to force the function to return without the recursive call being executed, otherwise the function will never return.

Page 45: Unit 7. Functions

05/01/2023 Ashim Lamichhane 45

Ex: Suppose you have numbers from 0 to 9 and you need to calculate the sum of these numbers in the following way :

• you can see that we start with 0 and 1• sum them up and add the result into

next number ie 2• then again we add this result to 3

and continue like this.

• Now lets see the code….

0 + 1 = 1 1 + 2  = 3 3 + 3 = 6 6 + 4 = 10 10 + 5 = 15 15 + 6 = 21 21 + 7  =28 28 + 8 = 36 36 + 9 = 45

Page 46: Unit 7. Functions

05/01/2023 Ashim Lamichhane 46

#include <stdio.h> int count = 1; void func(int sum) {    

sum  = sum + count;     count ++;if(count <=9){         func(sum);     } else {         printf("\nSum is [%d] \n",

sum);     }     return;

} int main(void) {    

int sum = 0;     func(sum);return 0;

}

Explanation• When func() was called through main(),

‘sum’ was zero.

• For every call to func(), the value of ‘sum’ is incremented with ‘count’ (which is 1 initially), which itself gets incremented with every call.

• The condition of termination of this recursion is when value of ‘count’ exceeds 9. This is exactly what we expect.

• When ‘count’ exceeds 9, at this very moment, the value of ‘sum’ is the final figure that we want and hence the solution.

Page 47: Unit 7. Functions

05/01/2023 Ashim Lamichhane 47

#include <stdio.h> int func(int num) {

int res = 0; if(num <= 0){printf("\n Error \n"); }else if(num ==1){return num; }else {res = num * func(num -1); return res; }return 0;

} int main(void) { int num = 5 ; int fact = func(num); if (fact > 0) printf("\n The factorial of [%d] is [%d]\n", num, fact); return 0; }

• res = 5 * func(5 -1); // This is func() stack 1

• res = 4 *func(4-1); // This is func() stack 2

• res = 3 *func(4-1); // This is func() stack 3

• res = 2 *func(2-1); // This is func() stack 4

• return 1; // This is func() stack 5

Take an example of sumsum(5)

=5+sum(4)

=5+4+sum(3)

=5+4+3+sum(2)

=5+4+3+2+sum(1)

=5+4+3+2+1+sum(0)

=5+4+3+2+1+0

=5+4+3+2+1

=5+4+3+3

=5+4+6

=5+10

=15

Page 48: Unit 7. Functions

05/01/2023 Ashim Lamichhane 48

WAP a program to find the factorial of a number using recursive method#include <stdio.h> long int factorial(int i) {

if(i <= 1) return 1;else return i * factorial(i - 1);

} int main() { int i = 5; printf("Factorial of %d is %d\n", i, factorial(i)); return 0; }

5!

5*4!

5*4*3!

5*4*3*2!

5*4*3*2*1!

5*4*3*2*1

Page 49: Unit 7. Functions

05/01/2023 Ashim Lamichhane 49

Recursion IterationA function is called from the definition of the same function to do repeated task.

Loop is used to do repeated task

Recursion is a top-down approach to problem solving; it divides the problem into pieces

Iterations is like a bottom-up approach; it begins with what is known and from this it constructs the solution step by step

In recursion, a function calls to itself until some condition will be satisfied

In iteration, a function does not call to itself.

Problem could be written or defined in term of its previous result to solve a problem using recursion

It is not necessary to define a problem in term of its previous result to solve using iteration

All problems can not be solved using recursion All problems can be solved using iteration

Page 50: Unit 7. Functions

05/01/2023 Ashim Lamichhane 50

Types of variables• Local variable (automatic or internal variable)• Global variables(External)• Static variables• Register variables

Page 51: Unit 7. Functions

05/01/2023 Ashim Lamichhane 51

Local variables (automatic or internal)• Are always declared within a function or block.

• Are local to the particular function or block in which they are declared.

• Other functions cannot access these variables.

• Compiler shows errors in case other functions try to access the variables.

• Are created when the function is called and destroyed automatically when the function is exited.

•Scope of a variable can be defined as the region over which the variable is visible or valid

Page 52: Unit 7. Functions

05/01/2023 Ashim Lamichhane 52

long int fact(int n){int i;long int f=1;for(i=1; i<=n;i++){

f*=1;return f;

}void main(){

Int num=5;printf(“factorial of %d is

%ld”,num,f);getch()

}

• here the variables n, i and f are local to function fact() and are unknown to main() function.

• Similarly num is local variable to the function main() and unknown to the function fact()

Page 53: Unit 7. Functions

05/01/2023 Ashim Lamichhane 53

Global variables (External)• Variables that are both alive and active throughout the entire

program.

• These are declared outside any block or function

• Can be accessed by any function in the program

• The scope is global. i.e within the program

• The life time is as long as the program execution doesn’t come to an end.

Page 54: Unit 7. Functions

05/01/2023 Ashim Lamichhane 54

int roll;float marks;main(){

…..;…..;…..;

}

func1(){…..;…..;…..;

}

int a=10;Void fun(){

a=20;printf(“%d”,a++);

}Void main(){

printf(“%d”,a);fun();printf(“%d”,a)

}OUTPUT:102021

• Here, a is global variable and is recognized within main() as well as user-defined function fun() and can be used anywhere in the program.

Page 55: Unit 7. Functions

05/01/2023 Ashim Lamichhane 55

Static variable• Static variable can only be accessed from the function in which it is

declared, just like local variable.

• The static variable is not destroyed on exit from the function; instead its value is preserved and becomes available again when the function is next called.

• Eg. static int counter;

• Can be initialized as normal variable.

• Its scope is local to the block in which the variable is defined.

• Its lifetime is global i.e. its value persists between different function calls.

Page 56: Unit 7. Functions

05/01/2023 Ashim Lamichhane 56

/* With auto variables */increment(){

Int i=1;printf(“%d\t”,i);i++;

}Void main(){

increment();increment()increment()increment()

}OUTPUT1 1 1 1

/* With static variables */increment(){

static int i=1;printf(“%d\t”,i);i++;

}Void main(){

increment();increment()increment()increment()

}OUTPUT1 2 3 4

Page 57: Unit 7. Functions

05/01/2023 Ashim Lamichhane 57

Register Variable• Register variables are special case of automatic variables.

• Accessing data in memory is considerably slower than processing in the CPU.

• Computes often have small amounts of storage within the CPU itself where data can be stored and accessed quickly.

• These storage cells are called registers.

• C provides storage class register for some variables to be allocated to CPU registers , if possible.

• Thus register variables provide a certain control over efficiency of program execution.

Page 58: Unit 7. Functions

05/01/2023 Ashim Lamichhane 58

Register Variable• Variables which are used repeatedly or whose access

times are critical may be declared to be of storage register.

• It behaves just like automatic variables.

• They are allocated storage upon entry to a block and the storage is freed when the block is exited.

• Scope of register variable is local to the block in which they are declared.

Page 59: Unit 7. Functions

05/01/2023 Ashim Lamichhane 59

#include<stdio.h> int main() {

int num1,num2; register int sum; printf("\nEnter the Number 1 : "); scanf("%d",&num1); printf("\nEnter the Number 2 : "); scanf("%d",&num2); sum = num1 + num2; printf("\nSum of Numbers : %d",sum);

return(0); }

Page 60: Unit 7. Functions

05/01/2023 Ashim Lamichhane 60

Difference between local, global and static variablesLocal Variables Global Variables Static Variables

The variables are declared within function or blocks. The scope is only within the function or block in which they are defined

Global variables are defined outside the functions so that their scope is throughout the program

Static variables are special case of local variables. Thus, static variables are also defined inside the functions or blocks

The initial value is unpredictable or garbage value.

The initial value is zero The initial value is zero

The life time is till the control remains within the block or function in which the variable is defined. The variable is destroyed when function returns to the calling function or block ends

The life time is till programs execution doesn't come to an i.e. variables are created when program starts and destroyed when program ends.

Its value persists between different function calls. Thus life time is same as global variables.

The keyword auto is used The keyword extern is used The keyword static is used.

Page 61: Unit 7. Functions

05/01/2023 Ashim Lamichhane 61

Tower of Hanoi (TOH) problem• Well known game

• Played with three poles and number of different sized disks.

• Each disk has hole in the center, allowing it to be stacked around any of the poles.

• Initially disks are stacked on the leftmost pole in an order. i.e. Largest on the bottom and the smallest on the top

Page 62: Unit 7. Functions

05/01/2023 Ashim Lamichhane 62

Tower of Hanoi (TOH) problem

Page 63: Unit 7. Functions

05/01/2023 Ashim Lamichhane 63

Objective on TOH problem• Transfer the disks from the left most pole to the

rightmost pole without ever placing a larger disk on top of a smaller disk.

• Only one may be moved at a time and each disk must always be placed around one of the poles.

• The problem can be solved in recursive method in three steps.

1. Move the top n-1 disks from the left pole to the center pole2. Move nth disk(largest) to the right3. Move the n-1 disk on the center pole to the right pole

Page 64: Unit 7. Functions

05/01/2023 Ashim Lamichhane 64

TOH problem/*C program for Tower of Hanoi using Recursion */

#include <stdio.h>

void towers(int, char, char, char);

int main()

{

int num;

printf("Enter the number of disks : ");

scanf("%d", &num);

printf("The sequence of moves involved in the Tower of Hanoi are :\n");

towers(num, 'A', 'C', 'B');

return 0;

}

void towers(int num, char frompeg, char topeg, char auxpeg)

{

if (num == 1)

{

printf("Move disk 1 from peg %c to peg %c\n", frompeg, topeg);

return;

}

towers(num - 1, frompeg, auxpeg, topeg);

printf("Move disk %d from peg %c to peg %c\n", num, frompeg, topeg);

towers(num - 1, auxpeg, topeg, frompeg);

}

Page 65: Unit 7. Functions

05/01/2023 Ashim Lamichhane 65

Questions• Write a function CalculateRoots() which receives three coefficients

a,b,c of quadratic equation ax2+bx+c=0 as its arguments and then calculates and displays its roots.

• Write a recursive function like int findsum(int n) which receives an integer n and returns sum of first n natural numbers.

• Write three functions: convertFromFeetToInches() which converts feet value to inches, convertFromInchesToCentimeters() which converts inches to centimeters and convertFromCentimetersToMeter() which converts centimeters to meters. Write a program that prompts a user for a measurement in feet and then converts and displays this value in meters. [Hint: 1 feet = 12 inches, 1 inch=2.54cm and 100cm = 1m]

Page 66: Unit 7. Functions

05/01/2023 Ashim Lamichhane 66

Reference• http://www.tutorialspoint.com/cprogramming/c_functions.htm• http://www.cprogramming.com/tutorial/c/lesson4.html• http://www.cs.utah.edu/~

germain/PPS/Topics/C_Language/c_functions.html• http://www.programiz.com/c-programming/c-functions• http://fresh2refresh.com/c-programming/c-function/• http://www2.its.strath.ac.uk/courses/c/section3_9.html