Chapter 4
Chapter 4
Chapter 4
Control Statements
• Introduction
• Algorithms and Pseudo code
• Selection Statement
• Multiple-Selection Statement
• Repetition Statement
• Breaking Control Statements
• What is algorithm?
• Algorithm is the effective method to obtain step by
step solution of problems.
• Knowledge of algorithm forms the foundation of
study programming languages.
• Before starting with programming let us understand
algorithm.
• i.e how to write algorithm, characteristic of
algorithm, algorithm designing tool and conversion of
algorithm to programs.
Definition:
• An algorithm is defined as the finite steps followed in
order to solve the given problem. 2
For example:
To find the average score of a student for the
three test marks.
Step1 :Start
Step2: Accept the three test marks s1,s2,s3
Step3: sum=s1+s2+s3
Step4:Average =sum/3
Step5: Display average
Step6: Stop
3
• Characteristic of algorithm:
– Input: An algorithm must provide with any number of
input/data values.
– Output: An algorithm must produce at least one
output.
– Definiteness: Each step of the algorithm must be clear
and distinct which ensures that the statement must
be unambiguous.
For example:
To divide two numbers
Algorithm
Step1: Accept the numbers a,b.
Step2: c=a/b
Step3:Display c.
Step 4: Stop.
4
• Step 2 of this algorithm is not clear, as there
will be no output . If b=0. Since the system
doesn’t such an answer, care must be taken
while writing an algorithm.
• The above algorithm can be rectified as follows
Step1: Read the two numbers a, b.
Step2:If (b=0);
• Print “denominator value is 0;
• And go to step 5
Step3:c=a/b
Step4: print c
Step5: Stop
5
• Finiteness: The algorithm must be terminated after a
finite number of steps.
• Let us illustrate this point with the help of an example:
Algorithm:
Step1: Start
Step2: Let a=9
Step3: x=y*z
Step4: Print x and go to step 2
Step5: Stop
Here we noticed that in an algorithm, nowhere the value
of a is changed, which control the flow of algorithm nerve
terminates. Such statements must be avoided.
The finiteness property assures the unambiguity in the
flow.
6
• Effectiveness: It must be possible in practice, to
carry out each step manually.
• The statements must be feasible.
• Thus the algorithm even through is definite, should
also be practical.
• If one take care of the above mentioned
characteristics while writing the algorithm, then
we can be sure of the results, for any kind of
inputs.
7
• Algorithm Designing tools:
• Algorithm must be designed in such a way that it
is followed by the pure top-down approach.
• This will ensure the straight line execution of the
algorithm.
• An algorithm can be expressed or designed in
many ways.
• One can make a use of any language to specify
the steps involved in solving a particular problem
but simple and precise language could be
adopted.
• Two famous ways of writing the algorithm are
making use of flowcharts and pseudo codes. 8
• Flowchart: Flowchart is the diagrammatic way
of representing, the steps to be followed for
solving the given problem.
• Flowcharts proves the visualization of the
steps involved, since it is in the form of a
diagram one can understand the flow very
easily.
• Here are some diagrammatic symbols to
design a flow chart.
9
START AND STOP
COMPUATIONAL
DECESION MAKING
CONNECTOR
FLOW INDICATOR
10
• Pseudocode:
• Pseudocode is an artificial and informal language that helps
the programmers to develop algorithm in the text format.
• It allows the programmer to focus on the logic of the
algorithm without being distracted by details of the language
syntax.
• It narrates steps of the algorithm more precisely.
• Following are the keywords used to indicate input, output
and other operations.
• Input – READ, GET
• Output – PRINT, DISPLAY
• Compute – CALCULATE, DETERMINE
• Initialize SET, INT
• Add one – INCREMENTER 11
• Conditions and loops
– IF-THEN ELSE
– Repetitive execution
– WHILE
– CASE
– REPEAT UNTIL
– FOR
• Pseudocode to obtain sum of two numbers.
BEGIN
INPUT X,Y
DETERMINE SUM = X+Y
PRINT SUM
END
• Pseudocode to obtain average of three numbers.
BEGIN
DISPLAY “INPUT 3 NOS”
INPUT X,Y,Z
DETERMINE SUM = X+Y+Z
DETERMINE AVG=SUM/3
PRINT AVG
END 13
Control Statements:
• Often in programming we come across situation
where we need to decide which part of the
code should be executed or coded should is
executed only if a particular condition is
satisfied.
• In some programs it may be needed to repeat
apart of code, jump from a particular
instruction or execute code if the particular
condition is fulfilled or take decesion. In all such
cases we can make use of control structures
provided by c++.
• While working with control structures we will
be coming across compound statements also
called as blocks. Let us understand what
compound statements are.
• A statement can be either be a simple
statement(a simple instruction ending with a
semicolon) or a compound statement (several
instruction grouped in a block) like the one
just describe.
• In the case that we want the statement to be a
simple statement, we do not need to enclose
it in the braces({})
• But in the case that we want the statement to
be a compound statement it must be enclosed
between braces({}), forming a block.
• Conditional statements
– If statement
– If …. Else statement
– Switch case statement
IF statement:
• If statement is the decision making statement.
• This statement controls flow of execution of
statements.
• This statement informs compiler of performing
certain instructions only if the specified condition
is met.
Syntax
if (Condition)
Single statement;
or
if (condition)
{
Multiple Statement
}
• For example: Sorting two numbers.
int Value1;
int Value2;
cout << "Enter two integers: ";
cin >> Value1 >> Value2;
if (Value1 > Value2)
{
int RememberValue1 = Value1;
Value1 = Value2;
Value2 = RememberValue1;
}
cout << "The input in sorted order: "
<< Value1 << " " << Value2 << endl ;
Output:
65
50
Else if statement:
• If … else statement is also a decision making
statement.
• This statement controls the flow of execution of
statements.
• This statement informs the compiler of
performing certain instructions if a specified
condition is true or false.
• Thus we need to provide statements which
should be executed when condition is true as
well as condition is false.
Syntax
If(condition)
Statement1;
Else
Statement2;
Braces are used to include multiple Statement
If(condition)
{ multiple statement; }
else
{ multiple statement; }
• The if .. Else statement is a two way branching statement.
• On execution the condition is evaluated and if the condition
is true the set of statement before the else is executed and
if the condition is false then the set of statements after the
else part is executed.
• For example:
cout << "Enter two integers: ";
int Value1;
int Value2;
cin >> Value1 >> Value2;
int Max;
if (Value1 < Value2)
{
Max = Value2;
}
else
{
Max = Value1;
}
cout << "Maximum of inputs is: " << Max << endl;
• Nested of if …. Else statement :
• It is possible to insert an if…else statement inside
another if….else statement this is called nested and
is used in programs where we need to check
multiple conditions.
For example:
#include<iostream.h>
#include<conio.h>
Void main()
{
int result;
Cout << “Enter your marks”;
Cin >>result;
If (result<35)
{
cout << “your result is fail”;
}
Else
{
if (result<50)
{
cout <<“You have passed”;
}
else
{
cout <<“you got NG grade”;
}
}
Switch statement:
• This statement is used to take a multi way decisions.
• Switch statement allows several conditions to be
evaluated within one statement rather than using
series of if…else statement.
• Only one variable is tested & branches depend on
the value of that variable.
• The variable must be an integral type(int long,
short or char)
• Default case is used to specify instructions to be
carried out if variable doesn’t match with any
branch.
Syntax:
Switch(expression)
{
case lable1:
block of statements;
Break;
case lable2:
block of statements;
Break;
case lable3:
block of statements;
Break;
default:
default statement
Break;
}
Break statement is used to make an exit out of the block in which it is included.
• The case labels within switch statement must
not be floating point numbers.
• The case labels within switch statement must
not be a string expression.
• For example case “mumbai” is not allowed.
• The case labels within switch statement must
not be an expression. E.g case ‘x+y’ is not
allowed.
Repetition Statements
• Often in programming, it is necessary to repeat
certain instructions number of times or until certain
condition is met.
• It is tedious to simply type a certain statement or
group of statement a large number of times.
• The structures that enable computers to perform
certain repetitive task are call loops.
• C++ gives you a choice of three types of loops,
– While,
– Do--while and
– For.
– The while loop keeps repeating an action until an
associated test return false.
– This is used where the programmer does not
know in advanced how many times the loop will
be traversed.
– The do while loop is similar, but test occur after
the loop body is executed. This ensures that the
loop body will run at least once.
– The for loop is frequently used, usually where the
loop will be traversed a fixed number of times.
– It is very flexible and novice programmers should
take care not to abuse the power it offers.
For loop
Syntax:
for(initialization; test; increment)
{
/* statement*/
}
• The initialization statement is executed exactly once before the
first evaluation of the test condition.
• It is used to assign an initial value to some variable.
• The initialization statement can also be used to declare an
initialize variables used in the loop.
• The test expression is evaluated each time before the
statements in the for loop execution.
• If the test expression is not true the loop is not executed and
execution continues normally from the statements following the
for loop.
• If the expression is not true then the statements within
the braces of the loop is executed.
• After each iteration of the loop, the increment
statement is executed.
• The increment action can do other things, such as
decrement.
for(i=1;i<=4;i++)
true
{
Statement(s)
for(k=1;k<=i;k++) (loop-body)
{
cout << “*”; Next
} Statement
a=a+1;
}
Output : false
a is 1
a is 2
a is 3
a is 4
Do…while loop :
• Do while loop checks the condition after each run.
• As a result, even if the condition is zero(false), it will run at least once.
• We can use the loop structure when we are certain about the test
condition.
• Its functionality is exactly the same as the while loop, except that
condition in the do-while loop is evaluated after the execution of
statement instead before, granting at least one execution of statement
even if condition is never fulfilled.
• Syntax:
statement
do
{
statement/s; true
Change in the initial condition; condition
} false
while(condition);
• Do… while and while loop are functionally almost
identical, with one important difference: do…
while loop is always guaranteed to execute at
least once, but while loop will not execute at all if
their condition is false on the first execution.
Comparison of for, while and do…..while