Control Structures-Unit 2

You might also like

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

Control structures

C++ is too must able to perform different sets of actions depending on the situations. Many times,
we want a set of instructions to be executed is one situation, and an entirely different set of
instructions to be executed in one situation, and an entirely different set of instructions to be
executing in another situation. This kind of situation is dealt in c++ programs using a control
instruction can be implemented in C++ using:
1) Sequential statements (if, if else, if else if)
2) Selection statements (switch case, goto)
3) Iteration/Repetition statements (while, do while, for)
1. Decision Making in C / C++ (if , if..else, Nested if, if-else-if ) or Sequential
statements
Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C++ handles decision-
making by supporting the following statements,
Decision making statements in programming languages decides the direction of flow of program
execution. Decision making statements available in C++ are:
1. if statement
2. if - else statements
3. nested if statements
4. if-else-if statements
5. switch statements
6. Jump Statements:
a. break
b. continue
c. goto
1. If
This is a one way conditional statement. It is used to execute a set of statements only when the
condition is TRUE or satisfied.

Syntax:
if (condition)
{
Statements;
}
Flowchart:

Example:

Example of if statement
#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}
Output:

Variable x is less than y

2. If else
It is used to execute a set of statements only when the condition is TRUE. When the
condition is FALSE, it displays statements else part.
Syntax:
if(expression)
{
statement-block1;
}
else
{
statement-block2;
}
If the 'expression' is true or returns true, then the 'statement-block1' will get executed, else
'statement-block1' will be skipped and 'statement-block2' will be executed.
Flow Diagram

Example:
#include< iostream.h>
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
cout << "x is greater than y";
}
else
{
cout << "y is greater than x";
}
}
Nested-if in C++:
The if statement with in another if is called Nested if/Ladder if Here a condition with in
another condition will be checked till it satisfies the condition.
Syntax:

if(expression)
{
if(expression1)
{
statement-block1;
}
else
{
statement-block2;
}
}
else
{
statement-block3;
}
Example:
include<iostream.h>
void main( )
{
int a,b,c;
cout << "enter 3 number";
cin >> a >> b >> c;
if(a > b)
{
if( a > c)
{
cout << "a is greatest";
}
else
{
cout << "c is greatest";
}
}
else
{
if( b> c)
{
cout << "b is greatest";
}
else
{
cout << "c is greatest";
}
}
}
4. if-else-if statements
In this we may have to use more than if else statement is called if else if.
Syntax:
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;
Example:
include<iostream.h>
void main( )
{
int a;
cout << "enter a number";
cin >> a;
if( a%5==0 && a%8==0)
{
cout << "divisible by both 5 and 8";
}
else if( a%8==0 )
{
cout << "divisible by 8";
}
else if(a%5==0)
{
cout << "divisible by 5";
}
else
{
cout << "divisible by none";
}
}
5. Switch Statement in C++

Switch case statements are a substitute for long if statements that compare a variable to several
integral values
• The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
• Switch is a control statement that allows a value to change control of execution.
Syntax:
switch (n)
{
case 1:
Statements;
break;
case 2:
Statements;
break;
case 3:
Statements;
break;

case n: Statements; break;

stamen;
default:

}
Example:
#include <iostream.h>
void main ()
{
char grade = 'D';
switch(grade)
{
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}

cout << "Your grade is " << grade << endl;


}
Loops in C++

In any programming language, loops are used to execute a set of statements repeatedly until
a particular condition is satisfied. Loop is nothing but a group of statements it is used to execute a
set of statements repeatedly or until a particular condition is being satisfied.
There are 3 methods by way of which we can repeat a part of a program
1) While loop
2) Do while loop
3) For loop
1. While loop:
A while loop statement repeatedly executes a target statement as long as a given condition
is true. It is a conditional entry loop. It is used execute a set of statements repeatedly when the
condition is TRUE, when the condition becomes FALSE it comes out of the loop.
Syntax
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true.

Example:

#include <iostream.h>
void main ( )
{
int a = 10;
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}
}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Do while loop

In do while loops also the loop execution is terminated on the basis of test condition. The
main difference between do while loop and while loop is in do while loop the condition is tested at
the end of loop body, i.e do while loop is exit controlled whereas the other two loops are entry
controlled loops.
Note: In do while loop the loop body will execute at least once irrespective of test condition.
Syntax:
do
{
Statements;
Increments / decrement;
} while (Condition);
Difference between while & do while loop

While Do while
1. In this loop the condition is checked 1. In this loop the condition is checked
before the statements after the statements
2. The minimum no of execution of 2. The minimum no. of execution of
statements in while loop is zero statements in do while loop is one.

Example
#include <iostream.h>
void main ()
{
int a = 10;
do
{
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );
}
OUTPUT:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

For loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
for ( initialization; condition; increment / Decrement )
{
statement(s);
}
• The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long
as a semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false,
the body of the loop does not execute and flow of control jumps to the next statement just
after the for loop.
• After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement can be left blank, as long as a semicolon appears after the
condition.
• The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the for loop terminates.

Example:
// C++ program to illustrate for loop
#include <iostream.h>
void main()
{
for (int i = 1; i <= 10; i++)
{
cout << "Hello World\n";
}
}
OUTPUT:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Nested loops: A loop with in another loop is called nested loop. Java supports all looping
statements have nested loops when the outer loop condition becomes true. It enters to the inner
loop. When inner loop executed for every termination of inner loop the condition will be checked.
Labeled loops: in java user can give the labels to a block of statements. A label is a any valid java
variable name. to give a labeled to the loop place it before the loop with a colon. The labeled loops
are used to identify the range of loop.
Syntax;
Loop name : for ( ) block name :
{ {
………….. ……………
………….. ……………
} }
Ex;
loop1: for (int i=0; i<=10; i++)
{

loop2: while(x<100)
{
y=i* x i f (y> 500)
break

l o o p 1;

}
}
6. Jump Statements:
a. Break statements

b. continue statements

c. goto statements

The break; continue; and goto;statements are used to alter the normal flow of a program.
Loops perform a set of repetitive task until text expression becomes false but it is sometimes
desirable to skip some statement/s inside loop or terminate the loop immediately without
checking the test expression. In such cases, break and continue statements are used.

A. break statement
In C programming, break statement is used with conditional if statement.
The break is used in terminating the loop immediately after it is encountered.

it is also used in switch...case statement. which is explained in next topic.

Syntax:
break;

The break statement can be used in terminating loops like for, while and do...while
Example:
//Write a C Program Which use of break statement.
#include<stdio.h>
#include<conio.h>
void main(){
int num, sum=0;
int i,n;
printf("Note: Enter Zero for break loop!\n");
printf("Enter Number of inputs\n");

scanf("%d",&n);
for(i=1;i<=n;++i){up
printf("Enter num%d: ",i);
scanf("%d",&num);
if(num==0) {
break; /*this breaks loop if num == 0 */
printf("Loop Breaked\n");
}

sum=sum+num;
}
printf("Total is %d",sum);
getch();
}

Download

Output:
Command Prompt
Note: Enter Zero for break loop!
Enter Number of inputs
5
Enter num1: 5
Enter num2: 10
Enter num3: 0
Loop Breaked
Total is 15
B.Continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue
statement is used.

Syntax:
continue;

Just like break, continue is also used with conditional if statement.

Example:
//Write a C Program Which use of continue statment.
#include<stdio.h>
#include<conio.h>
void main(){
int i, n=20;
clrscr();
for(i=1;i<=n;++i){
if(i % 5 == 0) {
printf("pass\n");
continue; /*this continue the execution of loop if i
% 5 == 0 */
}
printf("%d\n",i);
}
getch();
}

Download

Output:
Command Prompt
1
2
3
4
pass
6
7
8
9
pass
11
12
13
14
pass
16
17
18
19
pass
C . goto statement
In C programming, goto statement is used for altering the normal sequence of program execution
by transferring control to some other part of the program.

Syntax:
goto label;
.............
.............
.............
label:
statement;

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.

Example:
//Write a C Program Which Print 1 To 10 Number Using goto statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
count: //This is Label
printf("%d\n",i);
i++;
if(i<=10) {
goto count; //This jumps to label "count:"
}
getch();
}

Download

Output:
Command Prompt
1
2
3
4
5
6
7
8
9
10

Note:

You might also like