Unit
3: Control structure
# control structure :-
The structures those regulates the order in which
program statements are executed are called control structures. There are three
structure in C.
· Sequential Structure:
The sequential structure consists of sequence of
program statements that are executed one after another in order.
This is simplest type, involving no decisions,
branches or loop.
·
Selective structure:
The selective structure consists of a test for a
condition followed by alternative path that the program can follow.
In this type, one or more decisions boxes are
introduced and the action is taken depending on the result of the decision
element.
·
Repetitive structure:
Repetitive structure consists of program statements
that are repeatedly executed while some conditions holds true.
It represents a procedure which may be repeated a
definite or indefinite number of times.
The C
languages has three major statements and a conditional operator for decision
making.
a.
if statement
b.
if-else statement
c.
switch statement
d.
?: (conditional
operator)
3.1 Selective structure:
The decision making
structure is also called selective structure. The flowchart for the selective
structure in C is given below.
In this flow chart a condition is tested, if
it is true a group of statements is executed else the statement skipped or
other group of statements are executed.
entry
Condition?
Statement1 Statement2
Exit
Relational, equality
and logical operators:
For the selective
structure in C different operators such as relational, equality or the logical
operators are used.
a.
Relational operators
Less than <
Greater than >
Less than or equal
to <=
Greater than or equal
to =>
b.
Equality operators
Equal to ==
Not equal to !=
c.
Logical operators
Logical not !
Logical and &&
Logical
or ||
The if statement:
The general form of if statement is
If (test_expression)
statement;
The test expression should
always be enclosed in parentheses. If the test_expression is non zero (true)
then statement is executed; otherwise, statement is skipped and control passes
to the next statement. The statement can be a single or compound statement. The
statement part of the if statement is body of the statement.
Flowchart:
Test expression
statements
exit
The following program
illustrates the use of if statement:
/*marks.c*/
/*program to illustrate
if*/
#include <stdio.h>
Int main (void)
{
Int marks;
Printf(“enter your marks in computer
programming: “);
Scanf(“%d”, &marks);
If (marks>=40)
Printf(“you are passed”);
Return 0;
}
/*program to illustrate
min number among two integer*/
#include <stdio.h>
Int main (void)
{
Int j,k;
Printf(“enter two number”);
Scanf(“%d”,&j,&k);
If(k<j)
Min=j;
If(j<k)
Min =k;
Printf(“%d is smaller”,min);
Return 0;
}
The if - else statement:
If-else construct to perform some action even when the
test expression is not true (zero). We can have situation where we need to
execute one if the condition is true, and another when false. The format of the
if-else construct is as follows.
If (test_expression)
Statement1;
Else
Statement2;
When the test expression test_expression is true
(nonzero), then the body of if executed
and the control passes to the next statement immediately following the
if construct.
but if the test expression test_expression is not true(zero) then the
body of the else is executed.
The follow chart for the if-else construct is as
Test expression
statement
statements
/*program to illustrate
if-else statement*/
#include <stdio.h>
Int main ()
{
Int marks;
Printf(“enter your marks in computer
programming: “);
Scanf(“%d”, &marks);
If (marks>=40)
Printf(“you are passed”);
Else
Printf(“you are failed the exam”);
Return 0;
}
Nested if - else statement:
The actual meaning of nesting is to have the same
construct with in itself. If the if block or else block or both can have
another if of if-else statements, this type of resulting statement is called a
nested conditional statement.
The general format of this statement is
If (expr1)
If(expr2)
Statement1;
Else
Statement2;
Else
If(exp3)
Statement3;
Else
Statement4;
/*program to find largest of three numbers*/
#include <stdio.h>
Int main (void)
{
Int num1, num2, num3;
Printf(“enter three integer numbers:
“);\
Scanf(“%d%d%d”,&num1, &num2, &num 3);
If(num1>num2)
If(num1>num3)
Printf(“first number is largest”);
Else
Printf(“third number is largest”);
else
If(num2>num3)
Printf(“second number is largest”);
Else
Printf(“third number is largest”);
Return 0;
}
Multiway conditional statement:
Sometimes while programming we have to check series of
the condition. So if –else condition is used in another way. To check the
multiple condition a chain of ifs are used in which the statement
associated with each else is another if. This construct is called
multiway conditional or if-else ladder. The general format of this construct is
as follows.
If (expr_1)
Statement_1;
Else(expr_2)
Statement_2;
Else(expr_3)
Statement_3;
.
.
.
Else(expr_n)
Statement_n;
Else
Default_statement;
/*program
to find the division of a student*/
#include <stdio.h>
Int main (void)
{
Int
marks;
Printf(“enter
marks obtained: “);
Scanf (“%d”,
&marks);
If(marks>=80)
Printf(“grade: distinction”);
else(marks>=60)
Printf(“grade: first division”);
else(marks>=50)
Printf(“grade: second division”);
else(marks>=40)
Printf(“grade: third division”);
else
Printf(“grade: fail”);
Return 0;
}
/*program to find fruit according to the code number*/
#include <stdio.h>
Int main (void)
{
Int
fruit;
Printf(“enter the fruit code: “);
Scanf
(“%d”, &fruit);
If(fruit==1)
Printf(“orange”);
else(fruit==2)
Printf(“apple”);
else(fruit==3)
Printf(“grape”);
else(fruit==4)
Printf(“banana”);
else
Printf(“fruit not in the list”);
Return 0;
}
The switch statement:
When each of the test in a multiway conditional if
statement checks for a different value of the same expression then switch
statement is used. The switch statement is also called the constant multiway
conditional statement. The general format of the switch statement as follows:
Switch(fruit)
{
Case
value1:
statement;
Break;
Case
value2:
statement;
Break;
.
.
Case
value_n:
Statement_n;
Break;
default:
Statement_x;
Break;
}
/*program to find fruit according to the code number
using switch statement*/
#include <stdio.h>
Int main (void)
{
Int
fruit;
Printf(“enter the fruit code: “);
Scanf
(“%d”, &fruit);
Printf(“
the fruit is”);
Switch(fruit)
{
Case1:
Printf(“orange”);
Break;
Case2:
Printf(“apple”);
Break;
Case3:
Printf(“grape”);
Break;
Case4:
Printf(“banana”);
Break;
Default:
Printf(“fruit not in the list”);
}
Return 0;
}
Example: write a menu driven program using switch
statement having the following options.
i.
addition
ii.
subtraction
iii.
multiplication
iv.
division
and perform the above mentioned job as per user
choice. [Purbanchal university].
/*program to choose operator for operation*/
#include <stdio.h>
Int main (void)
{
float
opr1, opr2;
char
oper;
Printf(“enter first operand: “);
Scanf
(“%d”, &opr1);
Printf(“\n enter operator”);
Oper=getche();
/*getche() function is used to get a character on screen*/
Printf(“enter second operand: “);
Scanf
(“%d”, &opr2);
Switch(oper)
{
Case’+’:
Printf(“%0.2f %c
%0.2f = %0.2f, opr1, oper, opr2,
(opr1+opr2)”); /*.2 tells you to print only the first to
digits after the point*/
Break;
Case’-‘:
Printf(“%0.2f %c
%0.2f = %0.2f, opr1, oper, opr2,
(opr1- opr2)”);
Break;
Case’*’:
Printf(“%0.2f %c
%0.2f = %0.2f, opr1, oper, opr2,
(opr1*opr2)”);
Break;
Case’/’:
Printf(“%0.2f %c
%0.2f = %0.2f, opr1, oper, opr2,
(opr1/opr2)”);
Break;
Default:
Printf(“operator not defined”);
}
Return 0;
}
The conditional operator(?):
The C conditional operator ?: is ternary operator ie.
It takes three operands. The conditional operator has the following construct.
Expr1 ? expr2 : expr3
The expression expr1 is normally true-false
expression. The first expression expr1 is evaluated first. If it is non zero
(true) then expr2 is evaluated and that is the value of the whole conditional
expression. If expr1 is zero (false) then expr3 is evaluated and that is the
value of whole conditional expression. Thus conditional expression can be used
to do the work of if –else statement. For example in the following assignment
statement.
Small = x<y ? x : y;
Small is assigned the value of x if x is smaller than
y otherwise y is assigned to small.
This expression is equivalent to the following if-else
statement.
If (x<y)
Small = x;
Else
Small = y;
Example 1: write a program to read a person’s age in
year and find out how many person fall under the following categories. [pokhara
university].
Category age
Child 0 to 12
Teenager 13 to 19
Adult life 20 to 30
Mature life 31 to 50
Old age over 50
/*read age and display category*/
#include<stdio.h>
#include<stdlib.h>
Int main (void)
{
Int age;
Printf(“enter age:”);
Scanf(“%d”,&age);
If
(age>0 && age<=12)
Printf(“child”);
Else If
(age>=13 && age<=19)
Printf(“teenager”);
Else If
(age>=20 && age<=30)
Printf(“adult life”);
Else If
(age>30 && age<=50)
Printf(“mature life”);
else
Printf(“old age”);
Return 0;
}
Example 2: write a program to calculate the roots of a
quadratic equation ax^2+bx+c.
[Pokhara university]
The term b^2-4ac is known as the discriminant of a
quadratic equation. It tells the nature of the roots.
a.
If the discriminant is greater than 0, the roots are real and
different.
b. If the
discriminant is equal to 0, the roots are real and equal.
c.
If the discriminant is less than 0, the roots are complex and
different.
#include
<math.h>
#include
<stdio.h>
int main() {
double a, b, c, discriminant, root1, root2,
realPart, imagPart;
printf("Enter coefficients a, b and c:
");
scanf("%lf %lf %lf", &a,
&b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2
* a);
root2 = (-b - sqrt(discriminant)) / (2
* a);
printf("root1 = %.2lf and root2 =
%.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 =
%.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 *
a);
printf("root1 = %.2lf+%.2lfi and
root2 = %.2lf-%.2lfi", realPart, imagPart, realPart, imagPart);
}
return 0;
}
# Looping structure
( Repetitive structure) :-
C provides a repetitive structure which allows
the sequence of program statements to be executed several times even though it
appears only once in the program is called repetitive structure. While dealing
with large amount of data, we use repetitive control structure that
repetitively executes specific statements. The repetitive structure is also
called loop.
A repetitive structure has
entry point, a loop body and exit point. For repetition, there is a loop
continuation condition. The loop continuation condition can be at the beginning
of the loop or at the end of loop. In every repetition of the loop continuation
condition is tested.
Example
when not using repetitive structure is given below:
/* to display programming in
C is fun 10 times using sequential structure*/
#include <stdio.h>
Int main (void)
{
Printf(“programming in C is fun”);
Printf(“programming in C is fun”);
Printf(“programming in C is fun”);
Printf(“programming in C is fun”);
Printf(“programming in C is fun”);
Printf(“programming in C is fun”);
Printf(“programming in C is fun”);
Printf(“programming in C is fun”);
Printf(“programming in C is fun”);
Printf(“programming in C is fun”);
Return 0;
}
Example
when using repetitive structure is given
below:
/* to display programming in
C is fun 10 times using repetitive structure*/
#include <stdio.h>
Int main (void)
{
Int i;
i = 1;
While (i<=10)
{
Printf(“programming in C is fun”);
i++;
})
Return 0;
}
programming in C is fun
programming in C is fun
programming in C is fun
programming in C is fun
programming in C is fun
programming in C is fun
programming in C is fun
programming in C is fun
programming in C is fun
In C programming language
there are three types of loops:
i.
While loop
ii.
Do-while loop
iii.
For loop
While loop:
The while loop is an entry control (pre test) loop. It
repeats a statement or a block of statements while its controlling expression
is found to be true.
The general format is:
While (test_expression)
Statement;
The statement which is repeated is called the body of
the loop. The statement can be single or compound statement.
Generally following construct is used:
Loop initialization;
While(test_expression)
Statement;
Next_statement;
Flow chart of while loop:
The enrty point of the structure is defined by loop
initialization. In the while loop at first test_expression is evaluated. If it
is found nonzero(true), then statement following while is executed and control
is passes back to the beginning of the while loop. The body of while loopis
executed repeatedly until test_expression is zero(false). After the loop
termination the control passes to next statement.
entry
statement Condition?
true
false
exit
figure: flowchart of while loop
example:
/*to display number from 1 to 40 */
#include<stdio.h>
Int main(void)
{
Int i;
i = 1;
while
(i<=40)
{
Printf(“\t
%d”, i);
I++;
}
Return 0;
}
Do-While loop:
The do-while loop is an exit control (post) loop
unlike for and while loop. The loop body is executed at least once even though
the condition is false because the test expression is at the bottom of the
loop.
The general format is:
Do
{
Statement;
}while(test_expression);
Generally following construct is used:
Loop initialization;
Do
{
Statement;
}while (test_expression);
Next_statement;
Flow chart of do-while loop:
First statement is executed before test_expression is
evaluated. If the value of expression is found to be nonzero(true), then
control passes back to the beginning of the do statement and the process is
repeated itself. When expression is zero (false), then control is passed to
next statement ( next_statement).
In each iteration, the loop body is executed and then
only the conditional statement is evaluated. If the condition is found to be
true, the loop will repeat otherwise the loop terminates.
Entry
Condition? statement
false
example:
/*to display number from 1 to 40 */
#include<stdio.h>
Int main(void)
{
Int i;
i = 1;
do
{
Printf(“\t %d”, i);
I++;
}while (1<=40);
Return 0;
}
For loop:
It is a pre-test or entry control loop similar to
while loop. A program can aslo use a while loop instead of for loop. The
statement can be single or compound statement.
The general format is :
For (expression_1; expression_2; expression_3)
Statement;
Generally following construct is used:
For (initialization; test_expression; increament)
Statement;
Next_statement;
Flow chart of for loop:
Firstly expression_1 is evaluated, which is used to
initialize the loop. Normally expression2 is a test condition. If it is nonzero
(true), then loop body is executed. The expression3 is evaluated at the end.
Normally, expression3 is increment/decrement expression. The logical
expression2 controls the repetition of the for loop. This process continues
until expression2 is zero (false) and the control is passed to next_statement.
initialize
increment statements Condition?
exit
example:
/*to display number from 1 to 40 */
#include<stdio.h>
Int main(void)
{
Int i;
i=1;
For(i =1; i<=40;
i++)
Printf(“\t
%d”, i);
Return 0;
}
The comparison of while, do-while and for loops:
The comparison of while, do-while and for loop is done
in the following table
s.n |
while |
Do-while |
for |
1 |
Initialization is not the
integral part. |
Initialization is not the
integral part. |
Initialization is within
loop construct. |
2 |
The loop continuation
condition test is done at the beginning of the loop. |
The loop continuation
condition test is done at the end of the loop. |
The loop continuation
condition test is done at the beginning of the loop. |
3 |
The loop variable is not the
integral part of the loop. It should be done explicitly. |
The loop variable is not the
integral part of the loop. It should be done explicitly, |
The loop variable is the
integral part of the loop. It is done within the loop construct. |
4 |
The loop body is never
executed if the condition is false. That is loop body is executed zero or
more times. |
The loop body is executed at
least once if the condition is false. That is loop body is executed one or
more times. |
The loop body is never
executed if the condition is false. That is loop body is executed zero or
more times. |
5 |
While (test_expression) statement |
Do { Statement; }while (test_expression); |
For (expr1;expr2;expr3) Statement; |
Nested loop:
When the body part of the loop is another loop then
the inner loop is said to be nested within the outer loop. Therefore, there is
no limit of number of loop that can be nested. When nesting one loop inside
another, the inner loop must be entirely contained within the body of the outer
loop and each loop must have its own unique loop continuation expression. The
loop may have the same exit point.
The syntax for nested for loop statement in C :
For (init; condition; increment)
{
For
(init; condition; increment)
{
Statement(s);
}
Statement(s);
}
The syntax for nested while loop statement in C :
While (condition)
{
While
(condition)
{
Statement(s);
}
Statement(s);
}
The syntax for nested do-while loop statement in C :
Do
{
Statement(s);
}while
(condition)
}while (condition);
Loop interruption:
Sometimes, we need to exit from loop other than by
testing loop termination condition. Similarly, sometimes, we need to interrupt
the particular iteration without exiting from the loop. There two statements
for loop interruption are: break and continue.
break statement:
A break statement terminates the execution of the loop
(while or do-while or for) and the control is transferred to the statement
immediately following the loop. When a break is encountered in the program,
remaining part of the block is skipped and the loop is terminated passing
control out of the loop. For example:
for (i =0; i<5; i++)
{
If ( i==2)
Break;
Printf(“%d”,i);
}
In above program-segment 0 and 1 are printed. When
value of i is equal to 2, then break is encountered and control is passed out
of the loop. As a result, the program is terminated.
The break statement can also be used to terminate an
infinite loop when some condition arises.
Flowchart of break statement:
entry
Break; Condition?
end of loop
fig:
flowchart of break statement
continue statement:
Unlike break; continue does not terminate a loop
(while or do-while or for). It only interrupts a particular iteration. Whenever
the continue statement encountered, the remaining loop statement are skipped
and the computation proceeds directly to the next pass of the loop. The
condition which made to encounter with continue, that particular value is not
executed all other are executed. For example:
For ( i = 0; i<5; i++)
{
If( i ==2)
Continue;
Printf(“%d”, i);
}
In the above program block 0, 1,3 and 4 are printed
but not 2.
Flowchart of
continue statement:
entry
continue Condition?
false
Remaining part of the loop
Pattern Program 1
In the below pattern each column contains N number of stars
where N is the number of rows. The number of rows and columns are same so we
can assume it as square matrix.
Sample Input/ Output:-
Enter the number of rows: 5
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
#include<stdio.h>
int main()
{
int n;
printf("Enter the number of rows: ");
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Pattern Program 2
Sample Output:-
* * * * *
* * * *
* * *
* *
*
#include<stdio.h>
int main()
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=i;j>=1;j--)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Pattern Program 3
Sample Output:-
*
* *
* * *
* * * *
* * *
* *
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
if(j<=i)
printf("* ");
else
printf(" ");
}
printf("\n");
}
return 0;
}
2 * *
3 * * *
4 * * * *
5 * * * * * i
I j
1 1
2 1,2
3 1,2,3
4 1,2,3,4
5 1,2,3,4,5
I j
1
j<=1
2
j<=2
3
j<=3
4
j<=4
5
j<=5
j<=i
Pattern program 4
Sample Input/Output:-
Enter number of rows:
5
* * * * *
* * * *
* * *
* *
*
C program for inverted full pyramid of stars
#include<stdio.h>
int main()
{
int n, i, j,
k;
printf("Enter number of rows: ");
scanf("%d",&n);
for(i=n;i>=1;i--)
{
for(k=1;k<=n-i;k++) printf(" ");
for(j=1;j<=i;j++) printf("* ");
printf("\n");
}
return 0;
}
Pattern program 5: Display Full Pyramid
Sample Input/Output:-
Enter number of rows:
5
*
***
*****
*******
*********
C program for the above full pyramid star pattern,
#include<stdio.h>
int main()
{
int n, i, j, k;
printf("Enter number of
rows: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(k=1;k<=n-i;k++)
printf(" ");
for(j=1;j<=(2*i-1);j++)
printf("*");
printf("\n");
}
return 0;
}
No comments:
Post a Comment