Computer programming chapter 3
Control Statements
________________________________________________________________________________
3.1. Introduction
A running program spends all of its time executing statements. The order in which statements are
executed is called flow control (or control flow). Flow control in a program is sequential, from
one statement to the next, but may be diverted to other paths by branch statements.
There are different forms of C++ statements:
Declaration statements are used for defining variables.
Assignment statements are used for simple, algebraic computations. Branching statements are
used for specifying alternate paths of execution, depending on the outcome of a logical condition.
Loop statements are used for specifying computations, which need to be repeated until a certain
logical condition is satisfied.
Flow control statements are used to divert the execution path to another part of the program.
3.2. Conditional Statements
3.2.1. The if Statement
General form:
if (expression)
statement;
First expression is evaluated. If the outcome is true then statement is executed. Otherwise, nothing
happens.
For example, when dividing two values, we may want to check that the denominator is nonzero:
if (y!= 0) if(n<=0)
z = x/y; cout<<”Illegal Square Root!”;
To make multiple statements dependent on the same condition, we can use a compound statement:
if (balance > 0) {
interest = balance * creditRate;
balance += interest;
}
C++ If Example
1. #include <iostream.h>
2. int main () {
3. int num = 10;
4. if (num % 2 == 0)
5. {
6. cout<<"It is even number";
7. }
8. return 0;
9. }
Output:
It is even number
1
Computer programming chapter 3
[Link] if-else statement
General form:
if (expression)
statement1;
else
statement2;
First expression is evaluated. If the outcome is true then statement1 is executed. Otherwise,
statement2 is executed.
C++ If-else Example
1. #include <iostream.h>
2. int main () {
3. int num = 11;
4. if (num % 2 == 0)
5. {
6. cout<<"It is even number";
7. }
8. else
9. {
10. cout<<"It is odd number";
11. }
12. return 0;
13. }
Output:
It is odd number
C++ If-else Example: with input from user
1. #include <iostream.h>
2. int main () {
3. int num;
4. cout<<"Enter a Number: ";
5. cin>>num;
6. if (num % 2 == 0)
7. {
8. cout<<"It is even number"<<endl;
9. }
10. else
11. {
12. cout<<"It is odd number"<<endl;
13. }
2
Computer programming chapter 3
14. return 0;
15. }
Output:
Enter a number:11
It is odd number
Output:
Enter a number:12
It is even number
if(score>=85)
{
cout<<”A Grade”;
}
For example: else if(score>=75){
if (balance > 0) cout<<”B Grade”;
}
{ else if(score>=65){
interest = balance * creditRate; cout<<”C Grade”;
}
balance += interest; else if(score>=50){
} cout<<”D Grade”;
else { }
else
interest = balance * debitRate; {
balance += interest; cout<<”F Grade”;
}
}
For example:
if(n!=0){
z = x/y;
if(score>=50)
}
{
else { cout<<”U Passed!”;
cout<<”Illegal Division by 0!”; }
} else{
Cout<<”U Failed!”;
Cout<<”U Must Take This Course Again!”;
}
C++ If else-if Example
1. #include <iostream.h>
2. int main () {
3. int num;
4. cout<<"Enter a number to check grade:";
5. cin>>num;
6. if (num <0 || num >100)
7. {
8. cout<<"wrong number";
9. }
10. else if(num >= 0 && num < 50){
11. cout<<"Fail";
3
Computer programming chapter 3
12. }
13. else if (num >= 50 && num < 60)
14. {
15. cout<<"D Grade";
16. }
17. else if (num >= 60 && num < 70)
18. {
19. cout<<"C Grade";
20. }
21. else if (num >= 70 && num < 80)
22. {
23. cout<<"B Grade";
24. }
25. else if (num >= 80 && num < 90)
26. {
27. cout<<"A Grade";
28. }
29. else if (num >= 90 && num <= 100)
30. {
31. cout<<"A+ Grade";
32. }
33. }
Output:
Enter a number to check grade:66
C Grade
Output:
Enter a number to check grade:-2
wrong number
3.2.2. The switch Statement
Multiple-choice, provides a way of choosing between a set of alternatives.
General form:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break;
5. case value2:
6. //code to be executed;
7. break;
8. ......
9.
10. default:
11. //code to be executed if all cases are not matched;
4
Computer programming chapter 3
12. break;
13. }
First expression (called the switch tag) is evaluated, and the outcome is compared to each
of the numeric constants (called case labels), in the order they appear, until a match is
found.
The final default case is optional and is exercised if none of the earlier cases provide a
match.
Example: Binary arithmetic operation into its three components and stored these in variables
operator, operand1, and operand2, switch performs the operation and stores the result in result.
switch (operator) {
case '+': result = operand1 + operand2;
break;
case '-': result = operand1 - operand2;
break;
case '*': result = operand1 * operand2;
break;
case '/': result = operand1 / operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
The break terminates the switch statement by jumping to the very end of it.
For example, allowing x to be used as a multiplication operator
switch (operator) {
case 'x':
case '*': result = operand1 * operand2;
break;
default: cout << "unknown operator: " << ch << '\n';
break;
}
The above switch statement can be written as in if-else if statement
if (operator == '+')
result = operand1 + operand2;
else if (operator == '-')
result = operand1 - operand2;
else if (operator == 'x' || operator == '*')
result = operand1 * operand2;
else if (operator == '/')
result = operand1 / operand2;
else
cout << "unknown operator: " << ch << '\n';
C++ Switch Example
1. #include <iostream.h>
2. int main () {
3. int num;
4. cout<<"Enter a number to check grade:";
5
Computer programming chapter 3
5. cin>>num;
6. switch (num)
7. {
8. case 10: cout<<"It is 10"; break;
9. case 20: cout<<"It is 20"; break;
10. case 30: cout<<"It is 30"; break;
11. default: cout<<"Not 10, 20 or 30"; break;
12. }
13. }
Output:
Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
3.3. Looping Statements
3.3.1. The ‘while’ Statement
The while loop provides a way of repeating a statement while a condition holds or is true.
1. while(condition){
2. //code to be executed
3. }
First expression (called the loop condition) is evaluated.
If the outcome is nonzero then statement (called the loop body) is executed and the whole
process is repeated.
Otherwise, the loop is terminated.
Example: To calculate the sum of all numbers from 1 to integer n and 1-10
i = 1; int n, sum=0; while(age<=17 && age>=45)
sum = 0; while(n<=10) {
while (i <= n) sum+=n; cout<<”Invalid Age! Plz Try Again!”;
sum += i; //Or sum=sum + n; }
While loop can have an empty body i.e., null statement).
Example: Setting n to its greatest odd factor.
Let's see a simple example of while loop to print table of 1.
1. #include <iostream>
2. using namespace std;
6
Computer programming chapter 3
3. int main() {
4. int i=1;
5. while(i<=10)
6. {
7. cout<<i <<"\n";
8. i++;
9. }
10. }
Output:
1
2
3
4
5
6
7
8
9
10
3.3.2. The ‘for’ Statement
The for loop is similar to the while statement, but has two additional components:
1. An expression which is evaluated only once before everything else, and
2. an expression which is evaluated once at the end of each iteration.
The general form:
for (expression1; expression2; expression3)
statements;
1. for(initialization; condition; incr/decr){
2. //code to be executed
}
First expression1 is evaluated.
Each time round the loop, expression2 is evaluated.
If the condition is true then statement is executed and
expression3 is evaluated. Otherwise, the loop is terminated.
The general for loop is equivalent to the following while loop:
expression1;
while (expression2) {
statement;
expression3;
}
For loop example to calculates the sum of all integers from 1 to n.
sum = 0;
for (i = 1; i <= n; ++i)
sum += i;
This is preferred to the while-loop version,
7
Computer programming chapter 3
i is usually called the loop variable.
Loop variable i can be defined inside the loop itself:
Eg.
for (int i = 1; i <= n; ++i) Equivalent to: int i;
sum += i; for (i = 1; i <= n; ++i)
sum += i; //sum=sum+i;
1. #include <iostream.h>
2. int main() {
3. for(int i=1;i<=10;i++){
4. cout<<i <<"\n";
5. }
6. }
Output:
1
2
3
4
5
6
7
8
9
10
For loop can be empty, removing the first and the third expression gives identical to while
loop:
for (; i != 0;) // is equivalent to: while (i != 0)
something; //something;
Removing all the expressions gives infinite loop.
This loop's condition is assumed to be always true:
for (;;) // infinite loop
something;
Example:
for(;;)
{
if(n<=0)
break;
else
{
sum+=i;
}
}
1. #include <iostream.h>
2. int main () {
3. for (; ;)
4. {
5. cout<<"Infinitive For Loop";
8
Computer programming chapter 3
6. }
7. }
Output:
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c
For loops with multiple loop variables are not unusual. In such cases, the comma operator is used
to separate their expressions:
for (i = 0, j = 0; i + j < n; ++i, ++j)
something;
Because loops are statements, they can appear inside other loops.
In other words, loops can be nested.
C++ Nested For Loop Example
Let's see a simple example of nested for loop in C++.
1. #include <iostream.h>
2. int main () {
3. for(int i=1;i<=3;i++){
4. for(int j=1;j<=3;j++){
5. cout<<i<<" "<<j<<"\n";
6. }
7. }
8. }
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
The ‘do…while’ Statement
The do loop is similar to the while statement, except that its body is executed first and
then the loop condition is examined.
The general form:
1. do{
2. //code to be executed
9
Computer programming chapter 3
3. }while(condition);
First statement is executed and then expression/condition is evaluated.
If the outcome of the latter is nonzero then the whole process is repeated. Otherwise, the
loop is terminated.
The do loop is less frequently used than the while loop.
It is useful for situations where we need the loop body to be executed at least once,
regardless of the loop condition.
For example to repeatedly read a value and print its square, and stop when the value is
zero.
do {
cin >> n;
cout << n * n << '\n';
} while (n != 0);
Unlike the while loop, the do loop is never used in situations where it would have a null body.
Let's see a simple example of C++ do-while loop to print the table of 1.
1. #include <iostream.h>
2. int main() {
3. int i = 1;
4. do{
5. cout<<i<<"\n";
6. i++;
7. } while (i <= 10) ;
8. }
Output:
1
2
3
4
5
6
7
8
9
10
3.4. Other Statements
3.4.1. The ‘continue’ Statement
The continue statement terminates the current iteration of a loop and instead jumps to
the next iteration.
It applies to the loop immediately enclosing the continue statement. It is an error to use
the continue statement outside a loop.
In a while and do loops, the next iteration commences from the loop condition.
In for loop, the next iteration commences from the loop’s third expression.
10
Computer programming chapter 3
For example, a loop which repeatedly reads in a number, processes it but ignores negative
numbers, and terminates when the number is zero, may be expressed as:
do is equivalent to: do
{ {
cin >> num; cin >> num;
if (num < 0) if (num >= 0) {
continue; // process num here...
// process num here... }
} }
while (num! = 0); while (num != 0);
For loop that reads in a number exactly n times.
for (i = 0; i < n; ++i) {
cin >> num;
if (num < 0)
continue; // causes a jump to: ++i
// process num here...
}
When the continue statement appears inside nested loops, it applies to the loop immediately
enclosing it, and not to the outer loops. For example, in the following set of nested loops,
continues applies to for loop, and not the while loop:
while (more) {
for (i = 0; i < n; ++i) {
cin >>num;
if (num < 0)
continue; // causes a jump to: ++i
}
}
C++ Continue Statement Example
1. #include <iostream.h>
2. int main()
3. {
4. for(int i=1;i<=10;i++){
5. if(i==5){
6. continue;
7. }
8. cout<<i<<"\n";
9. }
10. }
Output:
11
Computer programming chapter 3
2
3
4
6
7
8
9
10
3.4.2. 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.
A statement that only applies to the loop or switch immediately enclosing it, and
terminates them is
For example:
for(n=10; n>0; n--)
{
cout<<n << ", ";
if(n==3)
{
cout<< "Countdown Aborted!";
break; //drop out of the loop
}
}
C++ Break Statement Example
1. #include <iostream.h>
2. int main() {
3. for (int i = 1; i <= 10; i++)
4. {
5. if (i == 5)
6. {
7. break;
8. }
9. cout<<i<<"\n";
10. }
11. }
12
Computer programming chapter 3
Output:
1
2
3
4
3.4.3. The ‘goto’ Statement
The goto statement provides the lowest-level of jumping.
The general form:
goto label;
where label is an identifier which marks the jump destination of goto. The label should be
followed by a colon and appear before a statement within the same function as the goto statement
itself.
For, example:
int n=10;
loop:
cout<<n<<",";
n--;
if(n>0)
goto loop;
cout<<"FIRE!";
3.4.4. The ‘return’ Statement
The return statement enables a function to return a value to its caller.
General form:
return expression;
where expression denotes the value returned by the function.
The type of this value should match the return type of the function.
For a function whose return type is void, expression should be empty:
return;
The main function may have return type int. The return value of main is what the program
returns to the operating system when it completes its execution. Under UNIX, for example, it is
conventional to return 0 from main when the program executes without errors. Otherwise, a
non-zero error code is returned.
For example:
int main (void)
{
cout << "Hello World\n";
return 0;
}
13