Professional Documents
Culture Documents
Unit Four Control Structure: Omputer Kill
Unit Four Control Structure: Omputer Kill
Edition 2 2014
Unit Four
Control Structure
A simple C++ statement is each of the individual instructions of a program, like the variable
declarations and expressions seen in previous sections. They always end with a semicolon (;),
and are executed in the same order in which they appear in a program.
But programs are not limited to a linear sequence of statements. During its process, a program
may repeat segments of code, or take decisions. For that purpose, C++ provides flow control
statements that serve to specify what has to be done by our program, when, and under which
circumstances.
Many of the flow control statements explained in this section require a generic (sub)
statement as part of its syntax. This statement may either be a simple C++ statement, -such as a
single instruction, terminated with a semicolon (;) - or a compound statement. A compound
statement is a group of statements (each of them terminated by its own semicolon), but all
grouped together in a block, enclosed in curly braces: {}:
{statement1; statement2; statement3 ;}
The entire block is considered a single statement (composed itself of multiple sub statements).
Whenever a generic statement is part of the syntax of a flow control statement, this can either be
a simple statement or a compound statement.
C++ programming language provides following types of decision making statements. Click the
following links to check their detail.
Statement Description
if statement An if statement consists of a Boolean expression followed
by one or more statements.
if...else statement An if statement can be followed by an optional else
statement, which executes when the Boolean expression is
false.
switch statement A switch statement allows a variable to be tested for equality
against a list of values.
nested if statements You can use one if or else if statement inside another if or
else if statement(s).
An if statement consists of a Boolean expression followed by one or more statements. The if
keyword is used to execute a statement or block, if, and only if, a condition is fulfilled. Its syntax
is:
Syntax:
The syntax of an if statement in C++ is:
if(boolean_expression)
{
// statement(s) will execute if the boolean
expression is true
}
If the Boolean expression evaluates to true, then the block of code inside the if statement will be
executed. If Boolean expression evaluates to false, If it is false, statement(s) (block of code) is
not executed (it is simply ignored), then the first set of code after the end of the if statement
(after the closing curly brace) will be executed.
Following is the general from of a typical decision making structure found in most of the
programming languages:
Example 1:
#include <iostream>
using namespace std;
int main()
{
int number;
cout<< "Enter an integer: ";
cin>> number;
if ( number > 0)
{
// Checking whether an integer is positive or not.
cout << "You entered a positive integer: "<<number<<endl;
}
cout<<"This statement is always executed because it's outside if statement.";
return 0;
}
Example 2:
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 10;
return 0;
}
Output
a is less than 20;
value of a is : 10
For example, the following code fragment prints the message (x is 100), only if the value
stored in the x variable is indeed 100:
1 if (x == 100)
2 cout << "x is 100";
If x is not exactly 100, this statement is ignored, and nothing is printed. If you want to include
more than a single statement to be executed when the condition is fulfilled, these statements shall
be enclosed in braces ({}), forming a block:
1 if (x == 100)
2 {
3 cout << "x is ";
4 cout << x;
5 }
As usual, indentation and line breaks in the code have no effect, so the above code is
equivalent to:
Syntax:
The syntax of an if...else statement in C++ is:
If (boolean_expression)
{
// statement(s) will execute if the boolean
expression is true
}
else
{
// statement(s) will execute if the boolean
expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram:
Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
return 0;
}
Output:
a is not less than 20;
value of a is : 100
#include <iostream>
using namespace std;
int main()
{
int number; cout<< "Enter an integer: ";
cin>> number;
if ( number >= 0)
{
cout << "You entered a positive integer: "<<number<<endl;
}
else
{
cout<<"You entered a negative integer: "<<number<<endl;
}
cout<<"This statement is always executed because it's outside if...else statement.";
return 0;
}
Example:
1 if (x == 100)
2 cout << "x is 100";
3 else
4 cout << "x is not 100";
This prints x is 100, if indeed x has a value of 100, but if it does not, and only if it does not, it
prints x is not 100 instead.
Syntax:
The syntax of an if...else if...else statement in C++ is:
if(boolean_expression 1)
{
// Executes when the boolean expression 1 is true
}
else if( boolean_expression 2)
{
// Executes when the boolean expression 2 is true
}
else if( boolean_expression 3)
{
// Executes when the boolean expression 3 is true
}
else
{
// executes when the none of the above condition is true.
}
One example where the use of else if provides a convenient solution is checking multiple ranges
for a value. For example, if we want to convert a final grade in a scale of 0 to 100 to a letter
grade (for example, 90 to 100 corresponds to an A, 80 to 89 is B, 70 to 79 is C, 60 to 69 is D, and
less than 60 is F), we could use the following fragment of code:
Example
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int a = 100;
return 0;
}
Output:
Value of a is not matching
Exact value of a is : 100
Example:
#include <iostream>
using namespace std;
int main()
{
int number;
cout<< "Enter an integer: ";
cin>> number;
if ( number > 0)
{
cout << "You entered a positive integer: "<<number<<endl;
} else if (number < 0){
cout<<"You entered a negative integer: "<<number<<endl;
} else {
cout<<"You entered 0."<<endl;
}
cout<<"This statement is always executed because it's outside nested if..else statement.";
return 0;
}
This prints whether x is positive, negative, or zero by concatenating two if-else structures.
Again, it would have also been possible to execute more than a single statement per case by
grouping them into blocks enclosed in braces: {}.
Switch Statement
Consider a situation in which, only one block of code needs to be executed among
many blocks. This type of situation can be handled using nested if...else statement
but, the better way of handling this type of problem is using switch...case
statement.
The syntax of the switch statement is a bit peculiar. Its purpose is to check for a
value among a number of possible constant expressions. It is something similar to
concatenating if-else statements, but limited to constant expressions. Its most
typical syntax is:
syntax is:
switch (expression)
{
case constant1:
group-of-statements-1;
break;
case constant2:
group-of-statements-2;
break;
.
.
.
default:
default-group-of-statements
Exercise:
#include <iostream>
using namespace std;
int main() {
char o;
float num1,num2;
cout<<"Select an operator either + or - or * or / \n";
cin>>o;
cout<<"Enter two operands: ";
cin>>num1>>num2;
switch(o) {
case '+':
cout<<num1<<" + "<<num2<<" = "<<num1+num2;
case '-':
cout<<num1<<" - "<<num2<<" = "<<num1-num2;
break;
case '*':
cout<<num1<<" * "<<num2<<" = "<<num1*num2;
break;
case '/': cout<<num1<<" / "<<num2<<" = "<<num1/num2;
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
cout<<"Error! operator is not correct";
break;
}
cin.get();
return 0;
}
What is the output for:
Select an operator either + or - or * or /
+
Enter two operands: 2.3
4.5
Loop Types
There may be a situation, when you need to execute a block of code several numbers of times.
In general statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general from of a loop statement in most of the programming languages:
C++ programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.
Syntax:
The syntax of a for loop in C++ is:
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 allows you to update any loop control variables.
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.
Flow Diagram:
Example:
#include <iostream>
using namespace std;
int main ()
{
// for loop execution
for( int a = 10; a < 20; a = a + 1 )
{
cout << "value of a: " << a << endl;
}
return 0;
}
Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!
The three fields in a for-loop are optional. They can be left empty, but in all cases the
semicolon signs between them are required. For example, for (;n<10;) is a loop without
initialization or increase (equivalent to a while-loop); and for (;n<10;++n) is a loop with
increase, but no initialization (maybe because the variable was already initialized before the
loop). A loop with no condition is equivalent to a loop with true as condition (i.e., an infinite
loop).
Because each of the fields is executed in a particular time in the life cycle of a loop, it may be
useful to execute more than a single expression as any of initialization, condition, or statement.
Unfortunately, these are not statements, but rather, simple expressions, and thus cannot be
replaced by a block. As expressions, they can, however, make use of the comma operator (,):
This operator is an expression separator, and can separate multiple expressions where only one is
generally expected. For example, using it, it would be possible for a for loop to handle two
counter variables, initializing and increasing both:
n starts with a value of 0, and i with 100, the condition is n!=i (i.e., that n is not equal to i).
Because n is increased by one, and i decreased by one on each iteration, the loop's condition will
become false after the 50th iteration, when both n and i are equal to 50.
1 #include <iostream>
2 using namespace std;
3 int main()
4 {
5 int i;
6 int sum = 0;
7 // sum the numbers from 1 through 10
8 for(i=1; i <= 10; sum += i++) ;
9
10 cout << "Sum is " << sum;
11 return 0;
12 }
13
while loop
A while loop statement repeatedly executes a target statement as long as a given condition is
true.
Syntax:
The syntax of a while loop in C++ is:
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.
When the condition becomes false, program control passes to the line immediately following the
loop.
Flow Diagram:
Here, key point of the while loop is that the loop might not ever run. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.
Example:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}
return 0;
}
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
1
2 // custom countdown using while
3 #include <iostream>
4 using namespace std;
5 int main ()
6 {
7 int n = 10;
8 while (n>0) {
9 cout << n << ", ";
1 --n;
0 }
1 cout << "liftoff!\n";
1 }
1
2
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!
The first statement in main sets n to a value of 10. This is the first number in the countdown.
Then the while-loop begins: if this value fulfills the condition n>0 (that n is greater than zero),
then the block that follows the condition is executed, and repeated for as long as the condition
(n>0) remains being true.
The whole process of the previous program can be interpreted according to the following
script (beginning in main):
1. n is assigned a value
2. The while condition is checked (n>0). At this point there are two possibilities:
o condition is true: the statement is executed (to step 3)
o condition is false: ignore statement and continue after it (to step 5)
3. Execute statement:
cout << n << ", ";
--n;
(prints the value of n and decreases n by 1)
4. End of block. Return automatically to step 2.
5. Continue the program right after the block:
print liftoff! and end the program.
A thing to consider with while-loops is that the loop should end at some point, and thus the
statement shall alter values checked in the condition in some way, so as to force it to become
false at some point. Otherwise, the loop will continue looping forever. In this case, the loop
includes --n, that decreases the value of the variable that is being evaluated in the condition (n)
by one - this will eventually make the condition (n>0) false after a certain number of loop
iterations. To be more specific, after 10 iterations, n becomes 0, making the condition no longer
true, and ending the while-loop.
Syntax:
The syntax of a do...while loop in C++ is:
do
{
statement(s);
}while( condition )
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the
loop execute again. This process repeats until the given condition becomes false.
Flow Diagram:
Example
#include <iostream> Output:
using namespace std;
int main () value of a: 10
{ value of a: 11
value of a: 12
// Local variable declaration:
value of a: 13
int a = 10; value of a: 14
// do loop execution value of a: 15
do value of a: 16
{ value of a: 17
cout << "value of a: " << a << endl; value of a: 18
a = a + 1; value of a: 19
}while( a < 20 );
return 0;
}
For example, the following example program echoes any text the user introduces until the user
enters goodbye:
Nested loops
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
Syntax:
The syntax for a nested for loop statement in C++ is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s); // you can put more statements.
}
do
{
The syntax forstatement(s);
a nested do...while
// youloop
can statement
put more instatements.
C++ is as follows:
do
{
statement(s);
}while( condition );
}while( condition );
Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100:
terminated and program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop
the execution of the innermost loop and start executing the next line of code after the block.
Syntax:
The syntax of a break statement in C++ is:
break;
Flow Diagram:
Example:
return 0;
}
Syntax:
The syntax of a continue statement in C++ is:
continue;
Flow Diagram:
Example:
return 0;
}
The Infinite Loop:
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally
used for this purpose. Since none of the three expressions that form the for loop are required, you
can make an endless loop by leaving the conditional expression empty.
Exercise 2:
1 #include <iostream>
2 using namespace std;
3 int main()
4 {
int counter = 1;
5
6
while ( counter <= 10 )
7
{
8
cout << counter << " ";
9
counter++;
10
}
11
12
cout << endl;
13
return 0;
14
}
15
Exercise 3:
1
2
3 #include <iostream>
4 using namespace std;
5 int main()
6 {
7 int len;
8
9 cout << "Enter length (1 to 79): ";
1
0 cin >> len;
1
1 while(len>0 && len<80) {
1 cout << '.';
2 len--;
1 }
3 return 0;
1 }
4
1
5
Exercise 4:
1
2
3 #include <iostream>
4 using namespace std;
5 int main()
6 {
7 int len;
8
9 cout << "Enter length (1 to 79): ";
1
0 cin >> len;
1
1 while(len>0 && len<80) {
1 cout << '.';
2 len--;
1 }
3 return 0;
1 }
4
1
5
Exercise 5: Demonstrates WHILE loops using fibonacci
series
Exercise 6:
1
2 #include <iostream>
3 using namespace std;
4 int main()
5 {
6 int counter;
7
cout << "How many hellos? ";
8
9 cin >> counter;
1 do
0 {
1 cout << "Hello\n";
1 counter--;
1 } while (counter >0 );
2
1 cout << "counter is: " << counter <<endl
3 ;
1 return 0;
4 }
1
5
Exercise 7:
1
#include <iostream>
2
3 using namespace std;
4
5 int main()
6 {
7 int num;
8
9
do {
1
0 cout << "Enter a number (100 to stop): ";
1
1 cin >> num;
1 } while(num != 100);
2
1
return 0;
3
1 }
4
Exercise: The body of a for loop can be empty
1
2
3
4
5
6
7
8
9 #include <iostream>
1
0 using namespace std;
1
1 int main() {
1 int table = 11;
2
const int table_min = 2;
1
3 const int table_max = 12;
1
4 // Create the top line of the table
1 cout << " |";
5 for(int i = 1 ; i <= table ; i++)
1 cout << " " << setw(3) << i << " |";
6
cout << endl;
1
7
1 // Create the separator row
8 for(int i = 0 ; i <= table ; i++)
1 cout << "------";
9 cout << endl;
2
0
2 for(int i = 1 ; i <= table ; i++) {
1 cout << " " << setw(3) << i << " |";
2
2 // Output the values in a row
2 for(int j = 1 ; j <= table ; j++)
3 cout << " " << setw(3) << i*j << " |";
2
cout << endl;
4
2 }
5
2
6 return 0;
2 }
7
2
8
2
9
3
0
3
1