0% found this document useful (0 votes)
4 views

c_unit_2

Uploaded by

principal.sbvrdc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

c_unit_2

Uploaded by

principal.sbvrdc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

UNIT-II

A C program is a set of statements, which are normally executed sequentially in the order in
which they appear. This happens when options or repetitions of certain calculations are not
necessary. We have a number of situations, where we may have to change the order of
execution of statements based on certain conditions, or repeat of group of statements until
certain specified conditions are met.

When a program breaks the sequential flow and jumps to another part of the code, it is called
branching. When the branching is based on particular condition, it is known as conditional
branching. If branching takes place without any decision, it is known as unconditional
branching.
Control or Decision making statements:
1. If statement
2. If..else statement
3. Nesting of if.. else
4. Else if ladder
5. Switch statement
6. Conditional operator

SIMPLE IF: The general form of the simple if statement is

The ‘statement - block’ may be a single statement or a group of statements. If the test
expression is true, the ‘statement – block’ will be executed, otherwise the ‘statement – block’
will be skipped and the execution will jump to ‘statement –x’.
#include<stdio.h>
Flowchart of simple if: #include<conio.h>
main()
{
int a;
printf(" Enter the value for a :");
scanf("%d",&a);
if(a==10)
{
printf(" SBVR Degree College");
}
getch();
}
IF-ELSE STATEMENT: The general form is

1
UNIT-II

If the test expression is true, then the true-block statement(s) immediately following if
statement, are executed. Otherwise, the false-block statement(s) are executed. In either case,
either true-block or false-block will be executed, not both.
Flow Chart:
#include<stdio.h>
#include<conio.h>
main()
{
int a;
printf(" Enter the value for a :");
scanf("%d",&a);
if(a==10)
{
printf(" SBVR Degree College");
}
else
{
printf(" Computer Language");
}
getch();
}

NESTING OF IF....ELSE STATEMENT: The general form of the nested if-else statement
is

If the test condition1 is false statement -3 will be executed, otherwise it continues to perform
the second test. If the condition – 2 is true, the statement -1 will be evaluated, otherwise the
statement -2 will be evaluated and the control is transferred to the statement – x.

2
UNIT-II

#include<stdio.h>
#include<conio.h>
main()
{
int a=325,b=12,c=4978;
if(a>b)
{

if(a>c)
printf("\n %d ",a);
else
printf("\n %d",c);
}
else
{

if(b>c)
printf(" \n %d",b);
else
printf("\n %d",c);
}
getch();
}

Flow chart:

ELSE IF LADDER: The general form is

3
UNIT-II

This construct is known as the else if ladder. The conditions are evaluated from top
downwards. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the ‘statement-x’ (skipping the rest of the ladder).
When all the n conditions become false, then the final else containing the default-statement
will be executed.

#include<stdio.h>
#include<conio.h>
main()
{
int mark;
printf(" Enter the mark ");
scanf("%d",&mark);
if(mark >= 75)
{
printf(" Distinction ");
}
else if(mark >=60 && mark <75)
{
printf(" First Class ");
}
else if (mark >=50 && mark <60)
{
printf(" Second Class ");
}
else if(mark >=35 && mark <50)
{
printf( " Third class");
}
else
{
printf(" Fail ");
}
getch();
}
Flow chart:

4
UNIT-II

SWITCH STATEMENT:

The switch statement tests the value of a given variable (or expression) against a list of case
values and when a match is found, a block of statements associated with that case is executed.
The expression is an integer expression or characters. Value-1, value-2... are constants or
constant expressions and are known as case labels.
Block-1, block-2 ... are statement lists and may contain zero or more statements. It is
important to note that case labels end with a colon (:).
The break statement at the end of each block signal the end of a particular case and causes an
exit from the switch statement. The default is an optional case.
The general form is :

#include<stdio.h>

5
UNIT-II

#include<conio.h>
main()
{
int dayno;
printf("Enter the day number");
scanf("%d",&dayno);
switch(dayno)
{
case 1: printf(" Sunday \n");
break;
case 2: printf(" Monday \n");
break;
case 3: printf(" Tuesday \n");
break;
case 4: printf(" Wednesday \n");
break;
case 5: printf(" Thrusday \n");
break;
case 6 : printf(" Friday \n");
break;
case 7: printf(" Saturday \n");
break;
default:
printf(" out of range");
}
getch();
}

Flow chart:

6
UNIT-II

DECISION MAKING AND LOOPING:

The process of repeatedly executing a block of statements is known as Looping.


The programme uses a loop construct to instruct the computer to perform repetitive tasks for
a finite number of times based on conditions. Each loop construct contains two parts namely
condition part and body part. The body part of the loop will be executed repeatedly as long as
the given condition evaluates to true.

Looping operations:
1. while Loop
2. do ..while Loop
3. for Loop

The while statement: The general form is #include<stdio.h>


#include<conio.h>
main()
{
int x=1,sum=0;
while(x<=10)
{
sum=sum+x;
x++;
}
printf(" The sum is %d ",sum);
getch();
}

The while is an entry-controlled loop statement. The simplest of all the looping structure in C
is the while statement. The test condition is evaluated and if the condition is true, then the
body of the loop is executed. After the execution of the body, the test condition is once again
evaluated and if it is true, the body is executed once again. This process is repeated until the
test condition becomes false and the control is transferred out of the loop.

7
UNIT-II

The do..while Statement: The general form is

do..while loop is an exit-controlled loop statement as it allows


the body of the loop to be executed for the first time without
any condition.

At the end of the loop, the test condition in the while statement is evaluated. If the condition
is true, the program continues to evaluate the body of the loop once again. This process
continues as long as the condition is true. When the condition becomes false, the loop will be
terminated and the control goes to the statement that appears immediately after the while
statement.
Example:

#include<stdio.h>
#include<conio.h>
main()
{
int x=1, sum=0;
do
{
sum=sum+x;
x++;
}
while(x<=10);
printf(" The sum is %d ",sum);
getch();
}

The for statement: The general form is

It is a entry-controlled loop.
Execution of the for statement is as follows
1. Initialization of the control variable is done first.
2. The value of the control variable is tested using the test condition. The test condition
is a relational expression. When the loop is true, the body of the loop is executed.
Otherwise the loop is terminated.
3. When the body of the loop is executed, the control is transferred back to the for
statement after evaluating the last statement in the loop. Now the control variable is
incremented or decremented. The new value of the control variable is tested again to
see whether it satisfies the loop condition. If the condition is satisfied, the body of the
loop is again executed. This process continues till the value of the control variable
fails to satisfy the test condition.

8
UNIT-II

Example:
#include<stdio.h>
#include<conio.h>
main()
{
int x,sum=0;
for(x=1;x<=10;x++)
{
sum=sum+x;
}
printf(" The sum is %d ",sum);
getch();
}

Nested Loops:
Nesting of loops, that is, one for statement within another for statement is allowed in C.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int row=1,col=1;
for(row=1;row<=10;row++)
{
for(col=1;col<=10;col++)
{
printf(" %3d",(col*row));
}
printf("\n");
}
getch();
}

Difference b/w while and do-while:

While Do -while
It is an entry-control loop it is an exit-controlled loop
Test condition is tested first Test condition is tested after executing the
body of the loop
It is pre-testing loop It is post-testing loop
It will not give guarantee to execute the body It will give the guarantee to execute the body
of the loop minimum once of the loop minimum once
Syntax: while (condition) Syntax: do
Simple or compound statement; Simple (or) compound statement;
while(condition);

9
UNIT-II

GOTO STATEMENT:
The goto statement is an unconditional statement used to transfer the control to any place in a
program.
Syntax: goto label;
Here the label is a variable used to name the target location to which the control is
transferred. The labels name must be unique with in a program. The label can be placed any
where in the program either before or after. The target statement must be named with label name
followed by a colon as follows:
Label: statement;

Ex: Forward Jump Ex: Backward Jump


main()
{ main()
int num; {
printf(“Enter a value”); int num;
scanf(“%d”,&num); Input:printf(“Enter a value”);
if(num<0) scanf(“%d”,&num);
goto end; if(num<0)
printf(“value=%d”,num); goto input;
end:printf(“end of program”); printf(“value=%d”,num);
}
}

BREAK STATEMENT:
The break statement is used to terminate the loop. When the break statement is encountered
inside a loop, the loop is immediately exited and the program continues with the statement
immediately following the loop. When the loops are nested, the break would only exit from
the loop containing it. That is, the break will exit only a single loop.
Syntax: Break ;
Example :
#include<stdio.h>
#include<conio.h>
main ( )
{ int i,num,n,sum=0;
printf(“how many values?”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&num);
if (num<0)
break;
sum=sum+num;
}
printf(“result=%d”,sum);
getch();
}

10
UNIT-II

CONTINUE STATEMENT:
Like break statement, C supports another similar statement called the continue statement.
However, unlike the break which caused the loop to be terminated, the continue, as the name
implies, causes the loop to be continued with the next iteration after skipping any statements
in between. The continue statement tells the compiler. “SKIP THE FOLLOWING
STATEMENTS AND CONTIUNE WITH THE NEXT ITERATION”. The format of the
continue statement is simply

Syntax: Continue ;
Example:
#include<stdio.h>
#include<conio.h>
main ( )
{
int i, n,sum,num;
printf(“how many values?”);
scanf(“%d”,&n);
for(i=1;i<=n,i++)
{
scanf(“%d”,&num);
if(num<0)
continue;
else
sum=sum+num;
}
printf(“Result=%d”,sum);
getch();
}

11
UNIT-II

FUNCTIONS:
A function is a block of code that performs a particular task. There are times when we need to
write a particular block of code for more than once in our program. This may lead to bugs
and irritation for the programmer. C language provides an approach in which you need to
declare and define a group of statements once and that can be called and used whenever
required. This saves both time and space.
C functions can be classified into two
categories,

 Library functions
 User-defined functions

Built-in or Library functions: Library functions are those functions which are defined
by C library, example printf(), scanf(), strcat() etc. You just need to include appropriate
header files to use these functions. These are already declared and defined in C libraries.

User-defined functions are those functions which are defined by the user at the time of
writing program. Functions are made for code reusability and for saving time and space.

Advantages of User-defined Functions :(or salient features )


 Modular programming
 Testing and debugging (correction of errors) is easy.
 Understanding the program is easy.
 It reduces size of the program due to code reusability
 Functions can be accessed without redevelopment, which in turn prompts reuse code.
 Code duplication can be avoided
 Can be invoked any number of times and from any locations of the application.

Elements of user defined function are

1) Function Declaration/prototype
2) Function definition (or) called function
3) Function call (or) calling function

Function Declaration/ Function prototype:


General syntax of function declaration is:
return-type function-name (parameter-list);
Like variables, all functions in a C program must be declared, before they are invoked. A
function declaration (also known as function prototype) consists of four parts.

12
UNIT-II

1. Function type (return type).


2. Function name.
3. Parameter list.
4. Terminating semicolon.
Example:
int mul (int m, int n);
Points to remember:
1. The parameters list must be separated by commas.
2. The parameter names do not need to be the same in the prototype declaration and the
function definition.
3. The types must match the types of parameters in the function definition, in number
and order.
4. Use of parameter names in the declaration is optional.
5. If the function has no formal parameters, the list is written as (void).
6. The return type must be void if no value is returned.
7. When the declared type does not match with the types in the function definition,
compiler will produce an error.

A prototype declaration may be placed in two places in a program:


 Above all the functions (including main).
 Inside a function definition.

Function Definition (or) called function:


The general syntax of function definition is
return-type function-name(parameter-list)
{
Local variable declarations;
Executable statement1;
Executable statement2; function body
…………..
Return statement;
}
The function definition is an independent program module that is specially written to
implement the requirements of the function. It contains the actual coding of the function.
The function definition also known as function implementation shall include the following
elements:
1. Function name ;
2. Function type;
3. List of parameters;
4. Local variable declarations;
5. Function statements; and
6. A return statement.
All the six elements are grouped into two parts, namely

13
UNIT-II

1. Function header (first three elements) and


2. Function body (second three elements)
return type: return type specifies the type of value(int,float,char,double) that function is
expected to return.
function-name: function name specifies the name of the function.
parameter-list: The parameter list declares the variables that will receive the data sent by
calling program. They often referred to as formal parameters. These parameters are also used
to send values to calling program. A function can also defined without arguments.
Function body: The function body contains the declarations and statements necessary for
performing the required task. The body is enclosed with curly braces { } and consists of three
parts.
 Local variable declaration.
 Executable statements.
 Return statement.
Example:
float mul( float x, float y)
{
float result;
result= x+y;
return (result);
}

Function Call or calling function:


A function can be called by simply using the function name followed by a list of actual
parameters, if any, enclosed in parentheses.
Whenever a function is called, the execution control is transferred to that function. After
completion of function execution, the control returns to the calling point.
The general form of calling a function is as follows:
Syntax:
Function-name(data-type arg1, data-type arg2, ……., data-type argn);
Where, ‘function name’ is name of user-defined functio. Arg1, arg2, ….., arg-
n are the values that are send to the function. These are referred as actual arguments.
While accessing a function, the following points must be remembered.
1. The number and order of actual parameters and formal parameters must be same.
2. When a function returns a value to its calling point then the returned value must be
assigned to a variable or it must be used in the output function.
Example:
sum(a,b);
square(10);

Return Statement:(Return values and their Types)


The return statement is used to return a value from a user-defined function to its calling
point. The statement can be used in the following ways.
Syntax-1: return;

14
UNIT-II

Syntax-2: return (value);


Examples:
1.return;
2. return (25);
3. return (x+y);
4. return x+y;
There are two types of parameters. They are
(i) Actual Parameters and
(ii) Formal parameters.
Actual Parameters: The parameters that are included in function calling point are called
“actual parameters”. These are used to send vales to the called function.
Formal Parameters: The parameters that are included in function definition are called
“formal parameters”. These are used to receive values from the calling point.
While using actual and formal parameters the following rules must be followed:
1. The number of actual parameters must be equal to the number of formal parameters.
2. The data types of actual parameters must be same to their corresponding formal
parameters.
3. The actual and formal parameters may or may not be having the same names.

#include<stdio.h>
#include<conio.h>
int sum(int a,int b); // function prototype
void main()
{
int x,y,z;
clrscr();
printf("\n Enter x,y values:");
scanf("%d%d",&x,&y);
z=sum(x,y); //actual arguments
Function call or calling function

printf("sum:%d",z);
getch();
}
int sum(int a,int b) // formal arguments
{ Function definition or called
return(a+b); function
}

CATEGORY OF FUNCTIONS
A function can be created by using any one of the following 4 forms:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and one return value.
4. Functions with no arguments but return a value.

15
UNIT-II

1. Function with no arguments and no return values:


When a function has no arguments, it does not receive any data from the calling function.
Similarly, when it does not return a value, the calling function does not receive any data
from the called function. In effect, there is no data transfer between the calling function
and the called function.

Syntax: Void function-name(void);

Funnction1() Funnction2()
No input
{ {
---- - - - - - -- -- ---- - - - - - -- --
Function2(); No output - - - -- - - - -
- - - -- - - - - - - - - -- -- -
- - - - -- -- - }
}

No data communication between functions

Example:
#include<stdio.h>
#include<conio.h>
void printline(void);
void main()
{
printline();
printf("\n SBVR DEGREE college");
printline();
getch();
}
void printline(void)
{
int i;
for(i=1;i<=50;i++)
{
printf("-");
}
}

2. Function with arguments and no return values:


This type of function receives data from calling function but it will not return any data
to the calling function.
Syntax:
Void function-name(argument-list);

16
UNIT-II

Funnction1() With arguments Funnction2( f )


{ {
---- - - - - - -- -- ---- - - - - - -- --
Function2( a ); No return values - - - -- - - - -
- - - -- - - - - - - - - -- -- -
- - - - -- -- - }
}

One way data communication

Example:
#include<stdio.h>
#include<conio.h>
void printline(char ch,int n);
void main()
{
printline('*',20);
printf("\n SBVR DEGREE college \n");
printline('=',50);
getch();
}
void printline(char ch,int n)
{
int i;
for(i=1;i<=n;i++)
{
printf("%c",ch);
}
}
3. Function with arguments and return values:
This type of functions receive data from calling function and also return data to the
calling function.
Syntax: datatype function-name(argument-list);
Funnction2( f )
Funnction1()
{
{
---- - - - - - -- --
---- - - - - - -- --
- - - - -- -- -
Function2( a ); return (e);
- - - -- - - - - }
}
Two way data communication between functions

Example:
#include<stdio.h>
#include<conio.h>
int sum(int a,int b);
void main()

17
UNIT-II

{
int x,y,z;
printf(“\n enter a,b values:”);
scanf(“%d%d”,&x,&y);
z=sum(x,y);
printf(“\n sum:%d”,z);
getch();
}
int sum(int a,int b)
{
int c;
c=a+b;
return c;
}
4. Function without arguments and with return values:
This type of functions does not receive any data from the calling function but it
returns a value to the calling function.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int a;
a=sum();
printf("%d",a);
getch();
}
int sum()
{
int a;
printf(" Enter the value ");
scanf("%d",&a);
return (a);
}

NESTED FUNCTIONS
Nested functions can be defined as calling functions from another function.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int a,b;

18
UNIT-II

printf("\n Enter the Numerator:");


scanf("%d",&a);
printf("\n Enter the Denominator:");
scanf("%d",&b);
printf("\n Result:%d",div(a,b));
getch();
}
int div(int x,int y)
{
int result;
if(diff(x,y)==1)
{
printf("invalid value passed");
return 0;
}
else
{
result=x/y;
return result;
}
}
int diff(int x,int y)
{
int z;
if(x>y)
z=0;
else
z=1;
return z;
}
o/p:
Enter the Numerator:10
Enter The Denominator:5
Result:2

RECURSION
Recursion is a special of nesting functions, where a function calls itself inside it. We must
have certain condition to break out of the recursion, otherwise recursion is infinite.
A special example of recursion is presented below:
main()
{
Printf(“\n this is example for recursion…”);
main();
}

19
UNIT-II

Here execution is terminated abruptly; otherwise the execution will continue indefinitely.
Another example is evaluation of a factorial of a given number
Factorial of n=n(n-1)(n-2)…….1

Ex: To find factorial of 5 it can be recursively computed as follows:


Factorial of 5=5*4*3*2*1=120
In the same way the factorial of n is recursively defined as,

N! = N * (N-1)! if N>1
=1 if N<=1
Ex: find the factorial of a given number using recursive funcion
#include<stdio.h>
#include<conio.h>
int fact(int n);
void main()
{
int n,res;
clrscr();
printf("\n Enter a value:");
scanf("%d",&n);
res=fact(n);
printf("\n factorial of %d is %d",n,res);
getch();
}
int fact(int n)
{
if(n==0)
return 1;
else
return (n*fact(n-1));
}

Scope and Lifetime of Variables:


The scope of variable determines in which part of the program a variable is actually available
for use. Life of the variable refers to the period during which a variable holds given value
during execution of a program.

The variables are classified into two types. They are


1. Local (Internal or Private) variables
2. Global (External or Public) variables

Local variables:
The variables that are declared inside a function are called local variables.

20
UNIT-II

Lifetime of local variables starts when control enters the function in which it is declared and
it is destroyed when control exits from the function.

Global variables:
A variable declared outside any function is known as global variable. Global variables can be
used by all functions in the program.
Global variables exist in the memory as long as the program is running. These variables are
destroyed from the memory when the program terminates. These variables occupy memory
longer than local variables.
Ex:
int a; // global or external variables
void main()
{
int b; //local or internal variables
}

STORAGE CLASSES
A storage class defines the scope (visibility) and life-time of variables and/or functions within
a C Program.
We have four different storage classes in a C program –
1. Automatic variables (auto)
2. Extern variables (Extern)
3. Static variables (static)
4. Register variables (register)

Automatic Variables:
Automatic variables are always declared within a function with the keyword
‘auto’. They are local to the function in which they are declared. A variable declared inside a
function without storage class specification is, by default an automatic variable.
Ex: void main()
{
int a; or auto int a;
}
Default initial value of an automatic variable is unpredictable value.
These variables are stored in memory.

Ex:
#include<stdio.h>
#include<conio.h>
void fun1(void);
void fun2(void);
void main()
{
int m=3;

21
UNIT-II

clrscr();
fun2();
printf("\n %d",m);
getch();
}
void fun1(void)
{
int m=1;
printf("\n %d",m);
}
void fun2(void)
{
int m=2;
fun1();
printf("\n %d",m);
}
output:
1
2
3

External Variables:
Variables that are both alive and active throughout the entire program are known as external
variables. They are also known as global variables. Unlike local variables, global variables
can be accessed by any function in a program
External variables are declared outside of any function. These variables are
stored in memory. Default initial value is zero.
#include<stdio.h>
#include<conio.h>
int fun1();
int fun2();
int fun3();
int x;
main()
{
x=10;
extern int z;
clrscr();
printf("\n x=%d",x);
printf("\n x=%d",fun1());
printf("\n x=%d",fun2());
printf("\n x=%d",fun3());
getch();
}

22
UNIT-II

z=25;
int fun1()
{
x=x+10;
return x;
}
int fun2()
{
int x;
x=1;
return x;
}
int fun3()
{
x=z+10;
return x;
}
output:
x=10
x=20
x=1
x=35

Static Variables:
As the name suggests the value of static variables persist until the end of the program. A
variable can be declared as static by using the keyword “static”. These variables are stored in
memory. Default initial value is zero. Local to the block in which it is declared.
Example:
#include<stdio.h>
#include<conio.h>
void stat();
void main()
{
int i;
clrscr();
for(i=1;i<=3;i++)
{
stat();
}
getch();
}
void stat()
{

23
UNIT-II

static int x=0;


x=x+1;
printf("\n x=%d",x);
}
output:
x=1
x=2
x=3

Register Variables:
These variables are stored in CPU registers. Default initial value is unpredictable. These
variables are local to the block in which they are declared. They are local to the block in
which they are declared.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
register int i;
clrscr();
for(i=1;i<=3;i++)
{
printf("\n %d",i);
}
getch();
}

output:
1
2
3

PASSING PARAMETERS TO THE FUNCTION


Information is passed to a function from the calling point by using parameters. In ‘C’
language there are two types of methods used to send parameters to a function. They are (i)
Call-by-value Method and (ii) Call-by-reference Method.
CALL-BY-VALUE:
In this method, actual arguments of function call are passed to the formal parameters of the
called function. Inside the function, the value of formal parameters changes according to the
need. When the control is returned to its calling point, the changed values of formal
parameters are not transferred. This type of passing technique is called call-by-value
mechanism.

24
UNIT-II

CALL-BY-REFERENCE
In this method, the address of actual parameters of function call is passed to the formal
parameters of the called function. Inside the function, when the formal parameters changes,
the actual parameters also changes. This type of technique is called call-by-reference. This
technique is performed using pointers.

Example: call-by-value Example: call-by-reference


#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void swap(int a,int b); void swap(int *x,int *y);
void main() void main()
{ {
int x,y; int x,y;
clrscr(); clrscr();
x=10; x=10;
y=20; y=20;
printf("\n values before swapping"); printf("\n values before swapping");
printf("\n x=%d \n y=%d",x,y); printf("\n x=%d \n y=%d",x,y);
swap(x,y); swap(&x,&y);
printf("\n values after swapping"); printf("\n values after swapping");
printf("\n x=%d \n y=%d",x,y); printf("\n x=%d \n y=%d",x,y);
getch(); getch();
} }
void swap(int a,int b) void swap(int *a,int *b)
{ {
int t; int t;
t=a; t=*a;
a=b; *a=*b;
b=t; *b=t;
} }

TYPES OF RECURSION
1. Direct recursion: A function is said to be directly recursive if it explicitly call itself.
int fact(int n)
{
if(n==0 || n==1)
return 1;
else
return n*fact(n-1);
}
2. Indirect recursion: A function is said to be indirectly recursive if it contains a call to
another function which ultimately call it.

25
UNIT-II

int func1(int n)
{
if(n==0 || n==1)
return 1;
else
return n*func2(n-1);
}
int func2(int x)
{
return func1(x-1);
3. Tail recursion: A recursive function is tail recursive when recursive call is the last thing
executed by the function.

TOWERS OF HANOI
#include<stdio.h>
#include<conio.h>
void towers(int, char, char, char);

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("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
Output:
Enter the number of disks : 3
The sequence of moves involved in the Tower of Hanoi are :

Move disk 1 from peg A to peg C


Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

26

You might also like