Fundamental of Programming I 2023
Chapter three
Conditional Statements
This chapter discusses the conditional statement. In the most general sense, a conditional
statement is a part of your program that can be executed. That is, a statement specifies an action.
Included in the selection statements are if and switch. (The term conditional statement is often
used in place of "selection statement.") The iteration statements are while, for, and do-while.
These are also commonly called loop statements. The jump statements are break, continue,
goto, and return. The label statements include the case and default statements (discussed along
with the switch statement) and the label statement (discussed with goto). Expression statements
are statements composed of a valid expression. Block statements are simply blocks of code.
(Remember, a block begins with a {and ends with a }.) Block statements are also referred to as
compound statements.
Note: C++ adds two additional statement types: the try block (used by exception handling) and
the declaration statement.
Since many statements rely upon the outcome of some conditional test, let's begin by reviewing
the concepts of true and false.
True and False in C++
Many C/C++ statements rely upon a conditional expression that determines what course of
action is to be taken. A conditional expression evaluates to either a true or false value.
In C++ fully supports the zero/nonzero definition of true and false just described. But C++ also
defines a Boolean data type called bool, which can have only the values true and false. As
explained in Chapter 2, in C++, a 0 value is automatically converted into false and a nonzero
value is automatically converted into true. The reverse also applies: true converts to 1 and false
converts to 0. In C++, the expression that controls a conditional statement is technically of type
bool. But since any nonzero value converts to true and any zero value converts to false.
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 1
Fundamental of Programming I 2023
Selection Statements
Selection statements are statements in a program where there are points at which the program
will decide at runtime whether some part of the code should or should not be executed.
There are two types of selection statements in C++, which are the “if statement” and the “switch
statement”
The if Statement
It is sometimes desirable to make the execution of a statement dependent upon a condition being
satisfied.
The different forms of the „If” statement will be used to decide whether to execute part of the
program based on a condition which will be tested either for TRUE or FALSE result.
The different forms of the “If” statements are:
The simple if statement
The If else statement
The if else if statement
The simple if statement
The simple if statement will decide only one part of the program to be executed if the condition
is satisfied or ignored if the condition fails.
Note:- that if is in lowercase. Uppercase letter (If or IF) will generate an error.
The General Syntax is: if (expression)
statements;
In any “if” statement, first the “expression” will be evaluated and if the outcome is non-zero
(which means TRUE), then the “statements” is executed. Otherwise, nothing happens (the
statement will not be executed) and execution resumes to the line immediately after the “if”
block.
To make multiple statements dependent on the same condition we can use a compound
statement, which will be implemented by embracing the group of instructions within the left “{“
and right “}” French bracket.
E.g.:
if(age>18)
cout<<”you are an adult”;
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 2
Fundamental of Programming I 2023
E.g.:
Int x=20, int y=18;
if(x> y)
{
Cout<<”x is greater than y”;
}
Most of the time “expression” will have relational expressions testing whether something is
equal, greater, less, or different from something else.
It should be noted that the output of a relational expression is either True (represented by
anything different from zero) or False (represented by Zero).
Thus any expression, whose final result is either zero or none zero can be used in ”expression”
E.g.:
int x;
cin>>x;
if(x)
cout<<”you are an adult”;
In the above example, the value of variable x will be an input from the user. The “if” statement
will be true if the user gives anything different from zero, which means the message “you are an
adult” will be displayed on the screen. If the user gives zero value for x, which will be
interpreted as False, nothing will be done as the if statement is not satisfied.
Fortunately, programmers can take steps to ensure that division by zero does not occur. Listing
3.1 ([Link]) shows how it might be done.
#include <iostream>
using namespace std;
int main() {
int dividend, divisor;
// Get two integers from the user
cout << "Please enter two integers to divide:";
cin >> dividend >> divisor;
// If possible, divide them and report the result
if (divisor != 0)
cout << dividend << "/" << divisor << " = "
<< dividend/divisor << endl;
}
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 3
Fundamental of Programming I 2023
The second cout statement may not always be executed. In the following run
Please enter two integers to divide: 32 8 32/8 = 4
it is executed, but if the user enters a zero as the second number:
Please enter two integers to divide: 32 0
the program prints nothing after the user enters the values.
The last statement in Listing 3.1 ([Link]) begins with the reserved word if. The if
statement allows code to be optionally executed. In this case, the printing statement is executed
only if the variable divisor‟s value is not zero.
The Boolean expression divisor != 0 determines if the single statement that follows the right
parenthesis is executed. If divisor is not zero, the message is printed; otherwise, the program
prints nothing.
The If else statement
Another form of the “if” is the “if …else” statement. The “if else” statement allows us to specify
two alternative statements: One which will be executed if a condition is satisfied and
Another which will be executed if the condition is not satisfied. Use the else statement to specify
a block of code to be executed if the condition is false.
The General Syntax is: if (expression)
statement1;
else
statment2;
First “expression” is evaluated and if the outcome is none zero (true), then “statements1” will be
executed. Otherwise, which means the “expression” is false “statements2” will be executed.
Eg.1
Int time= 20;
If(time<18)
cout<< ”Good day”;
else
cout<< ”Good evening”;
E.g.2: int x;
Cout<<”Enter a number: “;
Cin>>x;
if(x%2)
cout<<”The Number is Odd”;
else
cout<<”The Number is Even”;
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 4
Fundamental of Programming I 2023
The above three examples illustrate the “if else” statement. The last two examples will do
the same thing except that the expression in the Eg2 is changed from relational to
arithmetic. We know that the result from the modulus operator is either 0 or one if the
divider is 2. Thus the final result of the expression in Eg2 will either be 1 for odd numbers
or be 0 for even numbers. „if‟ statements may be nested by having an if statement appear
inside another if statement. For instance:
Eg.2 #include<iostream.h>
#include<conio.h>
int main()
{
Int testScore;
cout<<”\nEnter your test score:”;
cin>>testScore;
if(testScore <70)
cout<<”\n You did not pass:”;
else
cout<<”\n You did pass:”;
getch();
return 0;
}
The “If else If” statement
The third form of the “if” statement is the “if … else if “statement. The “if else if” statement
allows us to specify more than two alternative statements each will be executed based on
testing one or more conditions.
The General Syntax is:
If(expression1)
Statments1;
Else If(expression2)
Statments2;
Else
statements
First “expression1” is evaluated and if the outcome is none zero (true), then “statements1” will
be executed. Otherwise, which means the “expression1” then “expression2” will be evaluated: if
the output of expression2 is True then “statements2” will be executed otherwise the next
“expression” in the else if statement will be executed and so on.
If all the expressions in the “if…else” statements are false then “statements” under else will be
executed. The “if…else” and “if…else if” statements are said to be exclusive selection as if one
of the condition (expression) is satisfied only instructions in its block will be executed and the
rest will be ignored.
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 5
Fundamental of Programming I 2023
E.g.:
If(score>=90)
cout<< “\n your grade is A“;
else if(score >= 80)
cout<< “\n your grade is B“;
else if(score >= 70)
cout<< “\n your grade is C“;
else if(score >= 60)
cout<< “\n your grade is D“;
else
cout<<“\n your grade is F“;
In the above example, only one of the five cout statement will be executed and the rest will be
ignored. But until one of the conditions is satisfied or the else part is reached, the expressions
will be tested or evaluated.
The Switch Statement
Another C++ statement that implements a selection control flow is the switch statement
(multiple-choice statement). The switch statement provides a way of choosing between a set of
alternatives based on the value of an expression.
The switch statement has four components:
Switch
Case
Default
Break
The General Syntax might be:
Switch(expression)
{
case x:
// code block
Break;
Case y:
// code block
Break;
default:
// code block
}
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 6
Fundamental of Programming I 2023
Expression is called the switch tag and the constants preceding each case are called the case
labels.
The output of “expression” should always be a constant value. First expression is evaluated, and
the outcome, which is a constant value, will compared to each of the numeric constants in the
case labels, in the order they appear, until a match is found. Note, however, that the evaluation of
the switch tag with the case labels is only for equality
The statements following the matching case are then executed. Note the plural: each case may be
followed by zero or more statements (not just one statement).
After one case is satisfied, execution continues until either a break statement is encountered or
all intervening statements are executed, which means until the execution reaches the right French
bracket of the switch statement.
The final default case is optional and is exercised if none of the earlier cases provide a match.
This means that, if the value of the expression is not equal to any of the case labels, then the
statements under default will be executed.
Now let us see the effect of including a break statement in the switch statement.
E.g.:
Int day=4;
switch(day)
{
Case 1:
Cout<<”Monday”;
break;
Case 2:
Cout<<”Tuesday”;
break;
Case 3:
Cout<<”Wednesday”;
break;
Case 4:
Cout<<”Thursday”;
break;
Case 5:
Cout<<”Friday”;
Case 6:
Cout<<”Saturday”;
Case 7:
Cout<<”Sunday”; }
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 7
Fundamental of Programming I 2023
Switch evaluates expression and compares the result to each of the case values.
Relational and Boolean operators can be used in switch tag if and only if the expected output is
either 0 to represent False or 1 to represent True as that is the only possible output from such
operators.
Repetition Statements
Repetition statements control a block of code to be executed repeatedly for a fixed number of
times or until a certain condition fails.
There are three C++ repetition statements:
1) The For Statement or loop
2) The While statement or loop
3) The do…while statement or loop
The for statement / loop
The “for” statement (also called loop) is used to repeatedly execute a block of instructions until a
specific condition fails.
The General Syntax is:
for(expression1 ; expression2 ; expression3)
statements;
The for loop has three expressions:
expression1: is one or more statements that will be executed only once and before the looping
starts.
Expression2: is the part that decides whether to proceed with executing the instructions in the
loop or to stop. Expression2 will be evaluated each time before the loop continues. The output of
expression2 should be either zero (to proceed with the loop) or none zero (to stop the loop) to
represent false and true output respectively.
Expression3: is one or more statements that will be executed after each iteration.
Thus, first expression1 is evaluated and then each time the loop is executed, expression2 is
evaluated. If the outcome of expression2 is non-zero then statements is executed and
expression3 is evaluated. Otherwise, the loop is terminated.
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 8
Fundamental of Programming I 2023
In most programs, the “for loop” will be used for such expressions where expression1 is
initialization, expression2 is condition and expression3 is either increment or decrement. The
general format can be expressed as follows for the sake of clarity:
for(initialization ; condition ; increase/decrease)
statement;
Steps of execution of the for loop:
1. Initialization is executed. (Will be executed only once)
2. Condition is checked, if it is true the loop continues, otherwise the loop finishes and statement
is skipped.
3. Statement is executed.
4. Finally, whatever is specified in the increase or decrease field is executed and the loop gets
back to step 2.
E.g. guess the output of the following code:
int main()
{
for(int i=0;i<5;i++)
{
cout<<n<<“,”;
}
return 0; Output: 01234
}
Even though it is not recommended, expression1, expression2 and expression3 can be optional or
can be ignored. This means that they can take NULL statement. But making expression2 null
means that the loop will not terminate. In such cases one can include an “if” statement inside the
“for” loop which will test a condition and break out from the loop using the break statement.
While making one or more of the three expressions null, the semi colons CAN NOT be ignored.
E.g.:
for (;n<10;) //if we want nether initialization nor increase/decrease
for (;n<10;n++) //if no initialization is needed.
for ( ; ; ) //is an infinite loop unless an otherwise there is if statement inside the loop.
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 9
Fundamental of Programming I 2023
It is declared above that expression1 and expression3 can be one or more statements. The
composite statements should be separated by a comma. This means, optionally, using the comma
operator (,) we can specify more than one instruction in any of the two fields included in a “for”
loop.
E.g.
for(i=10;i!=0; i--)
{
//what ever here
} output: 10 to 1
Eg:1
//the following for statement adds the numbers between 0 and n
for(int i=0; i<=10;i++)
output: 0 to 10
Eg:2
//the following for statement adds the even numbers between 0 and n
int Sum=0;
for(int i=0; i<=n; i+=2)
{ output: 0246810
}
The while statement
The while statement (also called while loop) provides a way of repeating a statement or a block
as long as a condition holds / is true.
The general form of the while loop is:
while(expression) {
statements;
}
First expression (called the loop condition) is evaluated. If the outcome is non zero then
statement (called the loop body) is executed and the whole process is repeated. Otherwise, the
loop is terminated.
Suppose that we wish to calculate the sum of all numbers from 1 to some integer value n. this
can be expressed as:
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 10
Fundamental of Programming I 2023
E.g.1:// adds the numbers between 0 and any given number n
i=0;
while(i < 5)
cout<< I <<”\n”;
i++;
}
return 0; Output: 01234
}
E.g.2://adds the numbers between 0 and 100
number=1;
sum=0;
while(number <= 100)
{
sum += number; Output: 1 to 100
number++;
}
Do…while loop.
The do statement (also called the do loop) is similar to the while statement, except that its body
is executed first and then the loop condition is examined. In do…while loop, we are sure that the
body of the loop will be executed at least once. Then the condition will be tested.
The general form is:
do
{
Statement;
}
while(expression);
First statement is executed and then expression is evaluated. If the outcome of the expression is
nonzero, then the whole process is repeated. Otherwise the loop is terminated.
E.g.:
i=0;
do
{
cout<< i <<”\n”;
i++;
}
while(i > 5);
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 11
Fundamental of Programming I 2023
Types of Loops
Count controlled loops
Repeat a statement or block a specified number of times Count-controlled loops contain
An initialization of the loop control variable
An expression to test if the proper number of repetitions has been completed
An update of the loop control variable to be executed with each iteration of the body
Event-controlled loops
Repeat a statement or block until a condition within the loop body changes that causes
the repetition to stop
Keep processing data until a special value that is not a possible data value is entered to
indicate that processing should stop
Keep processing data as long as there is more data in the file
Keep processing data until the value of a flag changes in the loop body
The continue and break statements
The continue statement
The continue statement terminates the current iteration of a loop and instead jumps to the next
iteration. It is an error to use the continue statement outside a loop. In while and do while loops,
the next iteration commences from the loop condition. In a “for” loop, the next iteration
commences from the loop‟s third expression.
E.g.:
for(int n=10;n>0;n--)
{ if(n==5)
continue; //causes a jump to n—
cout<<n<< “\n”; output: 10 to 1
}
When the continue statement appears inside nested loops, it applies to the loop immediately
enclosing it, and not to the outer loops.
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 12
Fundamental of Programming I 2023
The break statement
A break statement may appear inside a loop (while, do, or for) or a switch statement. It causes a
jump out of these constructs, and hence terminates them.
Like the continue statement, a break statement only applies to the “loop” or “switch”
immediately enclosing it. It is an error to use the break statement outside a loop or a switch
statement.
E.g.:
for(n=10;n>0;n--)
{
cout<<n<< “,”;
if(n = = 3)
{
cout<< i<<“\n”;
break; output:10to4
}
}
Prepared by: Birhane Teklu Department of information Science Mekelle University Page 13