UNIT - 3 Control Structure

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

UNIT-3 control structure

3. Control Structures
3.1 Introduction
3.2 Decision making with IF – statement
3.3 IF – Else and Nested IF
3.4 While and do-while, for loop
3.5 Break. Continue, goto and switch statements

Introduction

Control structures form the basic entities of a “structured programming language“. We all know
languages like C/C++ or Java are all structured programming languages. Control structures are
used to alter the flow of execution of the program. Why do we need to alter the program flow?
The reason is “decision making“! In life, we may be given with a set of option like doing
“Electronics” or “Computer science”. We do make a decision by analyzing certain conditions (like
our personal interest, scope of job opportunities etc). With the decision we make, we alter the
flow of our life’s direction. This is exactly what happens in a C/C++ program. We use control
structures to make decisions and alter the direction of program flow in one or the other path(s)
available.

Decision making with IF – statement

if statement
The if statement controls conditional branching. The body of an if statement is executed if the
value of the expression is nonzero. Or if statement is used to execute the code if condition is
true. If the expression/condition is evaluated to false (0), statements inside the body of if is
skipped from execution.

Syntax :
if(condition/expression)
{
true statement;
}
statement-x;

If the condition/expression is true, then the true statement will be executed otherwise the
true statement block will be skipped and the execution will jump to the statement-x. The
“true statement‟ may be a single statement or group of statement.

If there is only one statement in the if block, then the braces are optional. But if there is more than
one statement the braces are compulsory
Example:
#include<stdio.h>
#include<conio.h>
void main() Output
{ b is greater
int a=15,b=20;
if(b>a)
{
printf("b is greater");
}
getch();
}

Example :
#include <stdio.h>
#include<conio.h>
void main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number); Output:
// Test expression is true if number is less than 0 Enter an integer: -2
if (number < 0) You entered -2.
{
printf("You entered %d.\n", number);
}
getch();
}

If-else statement : The if-else statement is an extension of the simple if statement. The
general form is. The if...else statement executes some code if the test expression is true (nonzero)
and some other code if the test expression is false (0).

Syntax : if (condition)
{
true statement;
}
else
{
false statement;
}
statement-x;
If the condition is true , then the true statement and statement-x will be executed and
if the condition is false, then the false statement and statement-x is executed.
Or
If test expression is true, codes inside the body of if statement is executed and, codes inside the
body of else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes inside
the body of if statement is skipped.

Example:
// Program to check whether an integer entered by the user is odd or even
#include <stdio.h>
#include<conio.h>
void main()
{
int number;
printf("Enter an integer: "); Output
scanf("%d",&number); Enter an integer: 7
// True if remainder is 0 7 is an odd integer.
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
getch();
}

Nested if-else statement


When a series of decisions are involved, we may have to use more than on if-else statement in
nested form. If –else statements can also be nested inside another if block or else block or both.

Syntax :
if(condition-1)
{
if (condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;

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

Example
#include<stdio.h>
#include<conio.h>
void main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2); Output :
if (var1 !=var2)
Var1 =10
{
printf("var1 is not equal to var2"); Var2 = 20
//Below – if-else is nested inside another if block
if (var1 >var2) var1 is not equal to var2
{ var2 is greater than var1
printf("var1 is greater than var2");
}
else
{
printf("var2 is greater than var1");
}
}
else
{
printf("var1 is equal to var2");
}
getch();
}
Switch statement : when there are several options and we have to choose only one option from
the available ones, we can use switch statement. Depending on the selected option, a
particular task can be performed. A task represents one or more statements.

Syntax:
switch(expression)
{
case value-1:
{
statement/block-1;
break;
}
case value-2:
{
statement/block t-2;
break;
}
case value-3:
{
statement/block -3;
break;
}
case value-4:
{
statement/block -4;
break;
}
default:
{
default- statement/block t;
break;
}

The expression following the keyword switch in any „C‟ expression that must yield an integer
value. It must be an integer constants like 1,2,3 .
The keyword case is followed by an integer or a character constant, each constant in each must be
different from all the other.
First the integer expression following the keyword switch is evaluated. The value it gives is
searched against the constant values that follow the case statements. When a match is found, the
program executes the statements following the case. If no match is found with any of the case
statements, then the statements following the default are executed.
Rules for writing switch () statement.
1 : The expression in switch statement must be an integer value or a character constant.
2 : No real numbers are used in an expression.
3 : The default is optional and can be placed anywhere, but usually placed at end.
4 : The case keyword must terminate with colon ( : ).
5 : No two case constants are identical.
6 : The case labels must be constants.

Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("enter choice : ");
scanf("%d",&a);
switch(a)
{
case 1:
{
printf("You chose One");
break;
}
case 2:
{
printf("You chose Two");
break;
}
case 3:
{
printf("You chose Three");
break;
}
case 4:
{
printf("You chose Four");
break; Output :
} enter choice : 3
case 5: You chose Three
{
printf("You chose Five.");
break;
}
default :
printf("Invalid Choice. Enter a no between 1 and 5"); break;
}
getch();
}

Loop Control Statements

A sequence of statements are executed until a specified condition is true. This sequence of
statements to be executed is kept inside the curly braces { } known as the Loop body. After
every execution of loop body, condition is verified, and if it is found to be true the loop body is
executed again. When the condition check returns false, the loop body is not executed.

The loops in C language are used to execute a block of code or a part of the program several times.
In other words, it iterates/repeat a code or group of code many times. Or Looping means a group
of statements are executed repeatedly, until some logical condition is satisfied.

C language provides three iterative/repetitive loops.


1 : while loop
2 : do-while loop
3 : for loop

For Loop:
 This is an entry controlled looping statement.
 In this loop structure, more than one variable can be initialized.
 One of the most important features of this loop is that the three actions can be taken at a
time like variable initialization, condition checking and increment/decrement.
 The for loop can be more concise and flexible than that of while and do-while loops.

Syntax :

for(initialization; condition; increment/decrement)


{
Statements;
}
Example:
#include<stdio.h>
#include<conio.h>
void main( )
{
Output
int x;
1 2 3 4 5 6 7 8 9 10
for(x=1; x<=10; x++)
{
printf("%d\t",x);
}
getch();
}

While loop
while loop can be addressed as an entry control loop. It is completed in 3 steps.
 Variable initialization.( e.g int x=0; )
 condition( e.g while( x<=10) )
 Variable increment or decrement ( x++ or x-- or x=x+2 )

The while loop is an entry controlled loop statement, i.e means the condition is evaluated first and
it is true, then the body of the loop is executed. After executing the body of the loop, the
condition is once again evaluated and if it is true, the body is executed once again, the process of
repeated execution of the loop continues until the condition finally becomes false and the control
is transferred out of the loop.

While Loop: Syntax :


variable initialization ;
while (condition)
{
statements ;
variable increment or decrement ;
}
Example : Program to print first 10 natural numbers
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
x=1;
while(x<=10) Output
{ 1 2 3 4 5 6 7 8 9 10
printf("%d\t", x);
x++;
}
getch();
}

C Program to reverse number


#include<stdio.h>
#include<conio.h>
main()
{
int n, reverse=0, rem;
clrscr();
printf("Enter a number: ");
scanf("%d", &n);
while(n!=0)
{ Output
rem=n%10; n=123
reverse=reverse*10+rem; Reversed Number: 321
n/=10;
}
printf("Reversed Number: %d",reverse);
getch();
}

do-while loop
The do-while loop is an exit controlled loop statement The body of the loop are executed first
and then the condition is evaluated. If it is true, then the body of the loop is executed once again.
The process of execution of body of the loop is continued until the condition finally becomes false
and the control is transferred to the statement immediately after the loop. The statements are
always executed at least once.
Syntax :
variable initialization ;
do{
statements ;
variable increment or decrement ;
}while (condition);

Example : Program to print first ten multiple of 5


#include<stdio.h>
#include<conio.h>
void main()
{
int a,i;
a=5;
i=1;
do
{
printf("%d\t",a*i);
Output
i++;
5 10 15 20 25 30 35 40 45 50
}while(i <= 10);
getch();
}

Example
void main()
{
int i=0
do
{ Output:
printf("while vs do-while\n"); while vs do-while
}while(i= =1); Out of loop
printf("Out of loop");
getch();
}
Factorial Program using for loop
#include<stdio.h>
#include<conio.h>
void main(){
int i,fact=1,number;
clrscr(); Output:
printf("Enter a number: "); Enter a number: 5
scanf("%d",&number); Factorial of 5 is: 120
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
getch();
}

Jump Statements
Jumping statements are used to transfer the program’s control from one location to another,
these are set of keywords which are responsible to transfer program’s control within the same
block or from one function to another.

There are four jumping statements in C language:


 goto statement
 return statement
 break statement
 continue statement

goto statement : goto statement doesnot require any condition. This statement passes
control anywhere in the program i.e, control is transferred to another part of the program without
testing any condition.

Syntax : goto label;


.....
.....
label:
statements;

In this syntax, label is an identifier.


When, the control of program reaches to goto statement, the control of the program will jump to
the label: and executes the code below it.
Or
The goto statement requires a label to identify the place to move the execution. A label is a valid
variable/identifier name and must be ended with colon ( : ).
Example
void main()
{
int age;

Vote:
printf("you are eligible for voting");
Output
NoVote:
printf("you are not eligible to vote"); Enter you age:19

printf("Enter you age:"); you are eligible for voting


scanf("%d", &age);
Enter you age:15
if(age>=18)
goto Vote; you are not eligible to vote
else
goto NoVote;
getch();
}

Break Statement
Break is a keyword. The break statement terminates the loop (for, while and do...while loop)
immediately when it is encountered. The break statement is used/ associated with decision
making statement such as if ,if-else.

Syntax of break statement


break;
Example
#include <stdio.h>
#include <conio.h>
void main()
{
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++)
{
printf("%d \n",i);
if(i==5){//if value of i is equal to 5, it will break the loop
break;
}
Output
}//end of for loop
12345
getch();
}
Continue Statement
Continue is keyword exactly opposite to break. The continue statement is used for continuing next
iteration of loop statements. When it occurs in the loop it does not terminate, but it skips some
statements inside the loop / the statements after this statement. . The continue statement is
used/ associated with decision making statement such as if ,if-else.

Syntax of continue Statement


continue;

Example

#include <stdio.h>

#include <conio.h>

void main(){

int i=1;//initializing a local variable

//starting a loop from 1 to 10

for(i=1;i<=10;i++)

{
if(i==5)

{ //if value of i is equal to 5, it will continue the loop

continue;

printf("%d \n",i);

}//end of for loop

getch();

Output
1234678910

You might also like