c_unit_2
c_unit_2
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
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:
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
Looping operations:
1. while Loop
2. do ..while Loop
3. for Loop
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
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();
}
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();
}
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;
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.
1) Function Declaration/prototype
2) Function definition (or) called function
3) Function call (or) calling function
12
UNIT-II
13
UNIT-II
14
UNIT-II
#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
Funnction1() Funnction2()
No input
{ {
---- - - - - - -- -- ---- - - - - - -- --
Function2(); No output - - - -- - - - -
- - - -- - - - - - - - - -- -- -
- - - - -- -- - }
}
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("-");
}
}
16
UNIT-II
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
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
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));
}
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
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
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.
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;
26