Control Structures

Normally the statements in a program, are executed sequentially one by one. This is known as the normal flow of control. One of the keys to designing intelligent programs is to make them able to make decisions, such as whether you are going to see a movie or not, whether to play a cricket match or not, whether you want to go on a long journey, and if so by the train or by the air.

Like these activities programs also need to decide among alternative actions, such as whether the year is a leap or not, whether the number is even or odd, and so on. Thus there is the possibility of changing the sequence of statements, based on these decisions.

Decisions can be made in C++ in several ways. C++ provides the if statement and the switch statement for implementing these decisions. The former one is generally used to choose between two alternatives, whereas the later one for multiple alternatives. In this article we will discuss these two decision making statements, along with logical and relational operators, and in last we will see the conditional operator which provides another way to make a choice.

The if statement

The if statement is used in a program where you need to perform a particular action on some condition. If the result of this condition is true then perform the action; otherwise either perform some other action or not. The if statement comes in two flavors:

the if statement
the if–else statement

The if statement is the simplest form of the decision statements. The if statement causes a program to execute a statement or a set of statements when a test-condition results in true, and to skip that statement or set of statements when the condition is false.

The C++ uses the keyword if to implement the decision control statement. The general form of the if statement is:

 if (test-condition)
statement;

here if is the keyword, followed by a test-condition. The test-condition must always be enclosed within a pair of parentheses. If this test-condition is true then the statement is executed; otherwise the statement is not executed and skipped by the program. Now we will see how the test-condition is expressed in C++?

Like C, C++ provides six relational operators as shown in Fiigure 1. The relational operators compare two numbers to check whether they are equal, unequal or whether one is greater than other, and so on. Each relational expression results in 1 if the comparison is true and 0 if the comparison is false.

Let we have x = 10 and y = 6 then

x == y      results in    0
x != y       results in    1
x > y        results in    1
x < y        results in    0
x >= y      results in    1
x <= y      results in    0

figg1

Figure 1

Here the first number, which is on the left-hand side of the relational operator, is compared with the number, which is on the right hand side. Note that the relational operators have a lower precedence than the arithmetic operators. Thus the following expression   

x – 6 > y + 2

corresponds to

(x - 6) > (y + 2)

and not the following

x – (6 > y) + 2

Therefore if x = 10 and y = 6 then the result of the relational expressions are as:

Relational expression        Result
x – 6 > y +2                       0
x – 6 < y +2                       1
x – 6 == y +2                     0
x – 6 != y +2                      1
x – 6 >= y +2                     0
x – 6 <= y +2                     1

Here is a simple program which illustrates the use of the if statement and the relational operators.

// Program-con1.cpp
#include
void main()
{
int num;
cout << “\nEnter a number : ”;
cin >> num;

if (num >= 0)
cout << “You have entered a positive number.”;
}

Here is the output of this program

Enter a number : 2
You have entered a positive number.

Let us see another example that makes you comfortable with the simple if statement. While purchasing some shirts, a discount of 20% offered if the number of shirts purchased is more than 5. It is required to calculate the cost of shirts, if quantity and cost per shirt are entered through the keyboard.
// Program-con2.cpp 
#include
void main()
{
int qty;
float tprice, price, discount;
discount = 0.0;
cout << “\nEnter number of shirts : ”;
cin >> qty;
cout << “Enter price per shirt : ”;
cin >> price;
if (qty > 5)
discount = 0.2;
tprice = qty * price * (1-discount);
cout << “Total price : ” << tprice;
}

In this program, the discount is set to 0 initially. After this we read the quantity and the price per shirt. The next statement sets discount to 0.2, only if the quantity is greater than 5. After the if statement, the total price is evaluated.

Here is some sample outputs of this program

Enter number of shirts : 4
Enter price per shirt : 125.50
Total price : 502

Enter number of shirts : 8
Enter price per shirt : 160.0
Total price : 1024

In the first output, the test-condition results in false, since 4 is not greater than 5. Thus the discount remains 0. On the other hand, in the second output, the test condition results in true, since 8 is greater than 5. Therefore the discount is set to 0.2 and the total price is evaluated using this new value of discount.

Multiple Statements in the if Body

You can also have more than one statement in an if body. In such case, it is necessary to enclose them within a pair of braces. The general form of such an if statement is as:
if (test-condition)
{
statement1;
statement2;
statement3;
statement4;
}

Following program illustrates this.
// Program-con3.cpp
#include
void main()
{
int age;
cout << “\nEnter your age : ”;
cin >> age;

if (age >= 20)
{
cout << “You have grown up.”;
cout << “\nNow you can take a pepsi.”;
}
}

The output of this program is

Enter your age : 24
You have grown up.
Now you can take a pepsi.

If you don’t use a pair of braces then the C++ compiler assumes that you have only one statements in the if body and executes this one statement only after the successful evaluation of the test-condition.

Figure 2(a) shows the typical operation of the if statement.

The if–else Statement

In earlier if statement, it decides whether a particular statement or a set of statements should be executed or not depends on the result of test-condition. It does nothing when the test-condition is false. The if–else statement allows you to execute a statement or a set of statements when the test-condition is true and another statement or a set of statements when the test-condition is false.

The general form of an if–else statement is
if (test-condition)
statement1;
else
statement2;

If the result of test-condition is true, the statement1 is executed and statement2 is skipped. If the result of test-condition is false, the statement2 is executed and statement1 is skipped.

Like simple if statement, if you have multiple statements in if body and as well as in else body then it is necessary to enclose them within a pair of braces as:
if (test-condition)
{
statement1;
statement2;
statement3;
statement4;
}
else
{
statement5;
statement6;
statement7;
statement8;
}

figg2

Figure 2


Here if test-condition is true, the program executes statement1, statement2, statement3, and statement4 and skips over else body statements. If the test-condition is false, the program executes statement5, statement6, statement7, and statement8 and skips if body statements. Figure 2(b) shows the behavior of the if–else statement.

Now let us see a simple program that finds out the largest number among two numbers.

// Program-con4.cpp
#include
void main()
{
int a, b;
cout << “\nEnter first number : ”;
cin >> a;
cout << “Enter second number : ”;
cin >> b;

if (a>b)
cout << “First number is greater than second number.”;
else
cout << “Second number is greater than or equal to first number.”;
}

Here is some sample output

Enter first number : 10
Enter second number : 8
First number is greater than second number.

Enter first number : 8
Enter second number : 10   
Second number is greater than or equal to first number.

Note that C++ is a free-form language. You can write if and else anywhere. For the sake of clarity we write the else exactly below the if and the statements in the if body and else body have been shifted to right just for indentation.

Nested if–else Statement

The C++ provides the facility of using an entire if–else statement within either the body of the if statement or the body of an else statement. This is called as nested if–else statement.

Program con5.cpp illustrates this concept.
// Program con5.cpp
#include
void main()
{
int a,b;
cout << “\nEnter first number : ”;
cin >> a;
cout << “Enter second number : ”;
cin >> b;

if (a>b)
cout << “First number is greater than second number.”;
else
{
if (a cout << “Second number is greater than first number.”;
else
cout << “Both numbers are equal.”;
}
}

Here are some sample output

First Run
Enter first number : 10
Enter second number : 12
Second number is greater than first number.

Second Run
Enter first number : 12
Enter second number : 2
First number is greater than second number.

Third Run
Enter first number : 7
Enter second number : 7
Both numbers are equal.

In this program, the second if–else statement is nested in the first else statement. If the first test-condition, that is a>b, is true then it displays the message

First number is greater than second number.

If the first test-condition is false, then the second test-condition, that is a
Second number is greater than first number.

Otherwise it displays the message

Both numbers are equal.

Here an if–statement is placed within the else body of the if–else statement. You can also place an if–else in the if block as well. Note that there is no limit on how deeply the ifs and the elses can be nested. If you are nested more deeply then you should make proper indentation; otherwise it may misguide you and others. In such case you may inadvertently match the wrong if. Following program shows this.
// Program con6.cpp
#include
void main()
{
int age;
cout << “\n Enter your age : ”;
cin >> age;

if (age <=5)
cout << “\n You are a lovely kid.”;
else
if (age <= 10)
cout << “\n You are grwoing up.”;
else
if (age <= 20)
cout << “\n You have not yet grown up.”;
else
if (age <= 30)
cout << “\n Now you have grown up.”;
else
cout << “\n You are a nice gentleman.”;
}

No doubt, this program would work. But when you will look at this program after some time, you may get confused because the else is matched with the wrong if. Here is the proper indentation of this program.
// Program con7.cpp
#include
void main()
{
int age;
cout << “\n Enter your age : ”;
cin >> age;

if (age <=5)
cout << “\n You are a lovely kid.”;
else
if (age <= 10)
cout << “\n You are growing up.”;
else
if (age <= 20)
cout << “\n You have not yet grown up.”;
else
if (age <= 30)
cout << “\n Now you have grown up.”;
else
cout << “\n You are a nice gentleman.”;
}

Here are some sample outputs of this program

First Run
Enter your age : 20
You have not yet grown up.

Second Run
Enter your age : 40
You are a nice gentleman.

Third Run
Enter your age : 10
You are growing up.

Fourth Run
Enter your age : 4
You are a lovely kid.

Since we know that C++ is a free-form language, therefore you can also rearrange the earlier program into an easy–to–read format as shown in program con8.cpp.
// Program con8.cpp 
#include
void main()
{
int age;
cout << “\n Enter your age : ”;
cin >> age;

if (age <=5)
cout << “You are a lovely kid.”;
else if (age <= 10)
cout << “You are grwoing up.”;
else if (age <= 20)
cout << “You have not yet grown up.”;
else if (age <= 30)
cout << “Now you have grown up.”;
else
cout << “You are a nice gentleman.”;
}

This revised format is much clearer than earlier one. You may think that the else–if is a new keyword, but unfortunately it is not true. It is still one if–else statement contained within another one. This entire structure still counts as one statement and lets you choose one among several alternatives.

Logical Operators

Logical operators allow you logically combine two or more than two conditions into one condition. For example, let you want to find out a number whose value is greater than 100 but less than 1000. Or if you want to check whether you have entered a character whose value must be greater than or equal to ‘0’ and less than or equal to ‘9’.


C++ provides three logical operators as shown in Figure 3

figg3

Figure 3

The first two operators, && and ||, are used to combine two conditions in one condition. The third operator,!, negates, or reverse the truth-value of the expression following it. The precedence of logical operators is lower than the relational operators.

Logical  AND Operator: &&

The logical AND operator (&&) is used to combine two expressions into one. If the result of both expressions are true then the result of complete resulting expression is true. If either or both are false then resulting expression would be false.

In program con7.cpp, we have used nested if–elses you have to very careful to match the corresponding ifs and elses. This limitation is overcome by the logical AND operator as:

// Program con9.cpp
#include
void main()
{
int age;
cout << “\n Enter your age : ”;
cin >> age;

if (age <=5)
cout << “\n You are a lovely kid.”;
if (age >5 && age <= 10)
cout << “\n You are growing up.”;
if (age > 10 && age <= 20)
cout << “\n You have not yet grown up.”;
if (age > 20 && age <= 30)
cout << “\n Now you have grown up.”;
if (age > 30)
cout << “\n You are a nice gentleman.”;
}

We have used the && operator as can be seen from the second if statement. The && operator lets you combine the two test expressions into one.

Here are a couple of sample runs.

First Run
Enter your age : 12
You have not yet grown up.

Second Run
Enter your age : 53
You are a nice gentleman.

Third Run
Enter your age : 27
Now you have grown up.

Fourth Run
Enter your age : 3
You are a lovely kid.

The logical OR Operator: ||

The OR operator also combines two expressions into one. The behavior of this OR operator is similar to the english word or. The resulting expression is true if either or both of the original expressions are true. The resulting expression is false if both of the logical expressions are false.

Let us summarize the behavior of OR operator using two expressions Expression1 and Expression2.

Expression1        Expression2        Result

True        ||           True            True      
True        ||           False            True
False       ||           True            True
False       ||           False            False

Let us use the || operator in a program to check for both a lowercase letter and an uppercase first three letters.
// Program con10.cpp
#include
void main()
{
char ch;
cout << “\n Enter a character (a/b/c) : ”;
cin >> ch;   
if (ch == ‘a’ || ch == ‘A’)
cout << “You have entered either a or A”;
else  if (ch == ‘b’ || ch == ‘B’)
cout << “You have entered either b or B”;
else  if (ch == ‘c’ || ch == ‘C’)
cout << “You have entered either c or C”;
else
cout << “Read your question again.”;
}

Here are the sample outputs of this program

First Run
Enter a character (a/b/c): b
You have entered either b or B

Second Run
Enter a character (a/b/c)  : c
You have entered either c or C

Third Run
Enter a character (a/b/c): s
Read your question again.

Fourth Run
Enter a character (a\b\c): a
You have entered either a or A

The Logical NOT Operator: !

The logical NOT operator is a unary operator that takes only one expression. The NOT operator reverses the logical value of its expression. If the value of its operand is true then the ! operator makes it false; if it is false the ! operator makes it true.

Following expressions summarize the behavior of NOT operator

Expression        Result

!True            False 
!False            True

For example, in an expression (num == 10) the result is true if num is equal to 10; but in an expression ! (num == 10) the result is true if num is not equal to 10. Obviously you can achieve the same effect by using the relational operator – “not equal to” as: (num != 10).

But it does not mean that you can use a relational operator in place of a NOT operator. The NOT operator is very helpful with functions that return true-false values. The concept of this NOT operator will be clear later on.

You can also use && and || operators together in order to combine two or more expressions. Now let us write a program to determine whether the year is a leap or not.
// Program con11.cpp
#include
void main()
{
int year;
cout << “\nEnter a year : ”;
cin >> year;

if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
cout << “Leap year.”;
else
cout << “Not a leap year.”;
}

Here are the sample outputs of this program

First Run
Enter a year : 1988
Leap year.

Second Run
Enter a year : 1900
Not a leap year.

We know that a year is a leap year if it is either divisible by 4 or not divisible by 100 or divisible by 400. Note that the logical AND operator has a higher precedence than the logical OR operator and both these logical operators have a lower precedence than relational operators. But the NOT (!) operator has a higher precedence than any of the relational or arithmetic operators.

Thus the expression
! num == 0 is interpreted as (!num) == 0 instead of ! (num == 0).

If you want the later interpretation then it is necessary to use parentheses as:
 ! (num == 0)

The Conditional Operator ? :

The conditional operator ? and : can often be used in place of a simple if–else statement. It is the only C++ operator that requires three operands, that’s why it is also called as ternary operator. The general form of this operator is

expression1 ? expression2 : expression3

Here if the expression1 is true then the value returned by the conditional expression will be expression2; otherwise the value returned will be expression3.

Let us write a simple program that finds the largest number among two numbers.

// Program con12.cpp
#include
void main()
{
int a, b, big;
cout << “\n Enter two numbers : ”;
cin >> a >> b;

big = (a > b) ? a : b;
cout << “Largest number : ” << big;
}

The output of this program is

Enter two numbers : 20  24
Largest number : 24

In this program, you have used the conditional operator in the following statement
big = (a > b) ? a : b;

The expression to the right side of the equal sign is called the conditional expression. The part of conditional expression, before the question mark ? is itself a test-expression. If this test-expression is true then the entire condition expression returns the value of the operand following the question mark; a in this program. If this test-expression is false then the entire condition expression returns the value of the operand following the colon; b in this program.

It produces the same result as the following if–else statement
if (a>b)
big = a;
else
big = b;

Naturally the former one is more concise than the later one.

While using conditional operators, one should remember that it is not necessary that the conditional operators should be used in arithmetical statements. You can also use conditional operators in simple statements.

Following program illustrates this fact.
// Program con13.cpp
#include
void main()
{
int num;
cout << “\nEnter a number : ”;
cin >> num;

(num >= 0 ? cout << “Positive number” : cout << “Negative number.”);
}

Here is the output of this program
Enter a number : 4
Positive number

Another main point to note is that the conditional operator can be nested, as illustrated in the following program.
// Program con14.cpp
#include
void main()
{
int a, b, c, big;
cout << “\nEnter three numbers : ”;
cin >> a >> b >> c;

big = (a>b ? (a>c ? a : c) : (b>c ? b : c));
cout << “Largest number : ” << big;
}

The output of this program is

Enter three numbers : 10 14 21
Largest number : 21

The only limitation of using a conditional operator is that you can use only one statement after the ? or after the colon(:).

The Mistake You Will Probably Not Like

You should always keep in mind the difference between the logical is-equal-to operator (==) and the arithmetic assignment (=) operator. The former operator is used to compare two numbers for its equality whereas the later operator is used to assign the value of the left-hand side.
X == 10    // Comparison
X = 10        // Assignment

Following program shows the difference between these two operators.
// Program con15.cpp
#include
void main()
{
int num;
cout << “\n Enter a number : ”;
cin >> num;

if (num == 10)
cout << “You have entered 10”;
else
cout << “You have not entered 10”;

if (num = 10)
cout << “\nYou have entered 10”;
else
cout << “\nYou have not entered 10”;

}

Here are the sample outputs of two runs.

First Run
Enter a number : 8
You have not entered 10       
You have entered 10

Second Run
Enter a number : 10
You have entered 10
You have entered 10

The first if statement correctly displays the output whereas the second if statement displays

You have entered 10

irrespective of what you enter as the value of num. It is because, in second if statement you have used assignment operator whereas in first if statement you have used relational operator. That’s why in second if statement is reduced to
if(10)

each time you run the program. And a non-zero value is always a true value. Hence if (10) always evaluates to true and you would get the output - You have entered 10.

Another common mistake you probably make while using the if statement is to place a semicolon (;) after the test-condition. For instance
if (num == 10) ;
cout << “You have entered 10”;

Here if the test-condition is true, the null statement (;) gets executed followed by the statement that displays the message - You have entered 10. If the test-condition is false then it skips the null statement and executes the statement that displays the message - You have entered 10. Thus irrespective of the result of test-condition, the statement
cout << “You have entered 10”;

is bound to get executed every time.

The switch Statement

We know that the nested if–elses provides the facility of making a choice among several alternatives. The limitation of using nested if–elses is that you have to carefully match the corresponding ifs and elses and match the corresponding pair of braces. C++ provides another decision control statement, a switch statement, that allows you to handle such cases more effectively than a series of if–else statements.

The syntax of the switch statement is as:
switch (integer-expression)
{
case label1 :
statement(s);
case label2 :
statement(s);
case label3 :
statement(s);
….

case labeln :
statement(s);
default :
statement(s);
}

Here the integer expression must be any expression that yields an integer value. It could be any integer constant or an expression that reduces to an integer value. The values followed by the keyword case are labels. Each label must be an integer or a character constant. Also each label must be different from all the others.

When a program encounters a switch statement, the integer- expression is evaluated first and then the control is transferred to the line labeled with the value corresponding to the value of integer expression. After this, the statements following that case labels gets executed and all subsequent cases and default statements as well unless you explicitly direct it otherwise. If it does not find any match it executes the statements of default case.

Here is a simple program of a switch statement.
// Program con16.cpp
#include
void main()
{
int n;
cout << “\nEnter a number : ”;
cin >> n;

switch (n)
{
case 1:
cout << “\nYou entered 1.”;
case 2:
cout << “\nYou entered 2.”;
case 3:
cout << “\nYou entered 3.”;
case 4:
cout << “\nYou entered 4.”;
default :
cout << “\nYou have not entered 1, 2, 3 or 4.”;
}
}

The output of this program is

Enter a number : 3
You entered 3.
You entered 4.
You have not entered 1, 2, 3 or 4.

From this output it is clear that whenever it finds a match, it then sequentially executes all the statements following that line, including the default as well. If you do not want to execute all the subsequent cases and the default then use a break statement. The break statement skips the remaining statements of the switch statement and transfers the control to the statement following the switch statement.

Program switch17.cpp shows how to use switch and break statement together.
// Program con17.cpp
#include
void main()
{
int n;
cout << “\nEnter a number : ”;
cin >> n;

switch (n)
{
case 1:
cout << “You entered 1.”;
break;
case 2:
cout << “You entered 2.”;
break;
case 3:
cout << “You entered 3.”;
break;
case 4:
cout << “You entered 4.”;
break;
default :
cout << “You have not entered 1, 2, 3 or 4.”;
}
}

Now when you run this program, you get the following output

Enter a number : 3
You entered 3.

In this program, you have used a break statement at the end of each case section. The break statement terminates the entire switch statement and transfers the control to the first statement following the end of the switch statement.

In program con16.cpp and con17.cpp you have used case labels arranged in ascending order, that is 1, 2, 3, and so on. However it is not mandatory. You can also use case labels in any order you like. Following program illustrates this view.
// Program con18.cpp
#include
void main()
{
int n;
cout << “\n Enter a number : ”;
cin >> n;

switch (n)
{
case 4:
cout << “You entered 4.”;
break;
case 1:
cout << “You entered 1.”;
break;
case 27:
cout << “You entered 27.”;
break;
case 6:
cout << “You entered 6.”;
break;
default :
cout << “Pardon me.”;
}
}

Here are the sample outputs this program

First Run
Enter a number : 1
You have entered 1.

Second Run
Enter a number : 2
Pardon me.

The switch Statement with Character Variables

You can also use characters instead of integers as case labels, as shown in program switch4.cpp.
// Program con19.cpp
#include
void main()
{
char ch;
cout << “\nEnter any vowel : ”;
cin >> ch;

switch (ch)
{
case ‘a’:
cout << “You entered a.”;
break;
case ‘e’:
cout << “You entered e.”;
break;
case ‘i’:
cout << “You entered i.”;
break;
case ‘o’:
cout << “You entered o.”;
break;
case ‘u’:
cout << “You entered u.”;
break;
default :
cout << “You have not entered any vowel.”;
}
}

Here is the sample output of four runs.

First Run
Enter any vowel :e
You entered e.

Second Run
Enter any vowel :i
You entered i.

Third Run
Enter any vowel :s
You have not entered any vowel.

Fourth Run
Enter any vowel :a
You entered a.

In this program, you have used a character variable ch as the switch variable, and character constants as the case labels. You can also mix integer and character constants in different cases of a single switch statement.
// Program con20.cpp
#include
void main()
{
char ch;
cout << “\n Enter any vowel : ”;
cin >> ch;

switch (ch)
{
case ‘a’:
cout << “You entered a.”;
break;
case 101:
cout << “You entered e.”;
break;
case ‘i’:
cout << “You entered i.”;
break;
case 111:
cout << “You entered o.”;
break;
case ‘u’:
cout << “You entered u.”;
break;
default :
cout << “You have not entered any vowel.”;
}
}

The output of this program is similar to con19.cpp.

The switch statement also provides the facility of executing a set of statements for more than one case label. Following program illustrates this concept:
// Program con21.cpp 
#include
void main ()
{
char ch;
cout  <<  “\nEnter any of first four alphabet:”;
cin  >> ch;
switch (ch)
{
case ‘a’:
case ‘A’:
cout << “You entered a and A”;
break;           
case ‘b’:
case ‘B’:
cout << “You entered b and B”;
break;
case ‘c’:
case ‘C’:
cout << “You entered c and C”;
break;
case ‘d’:
case ‘D’:
cout << “You entered d and D”;
break;
default:
cout << “You have not entered any of the first four alphabet.”;
}
}

Since we know that whenever a switch statement finds a match. If then executes all the subsequent line in the switch unless it encounters a break statement. So if an alphabet ‘a’ is read through the keyboard. The case ‘a’ is satisfied and since there is no statement in this case label so the control is transferred to the next case ‘A’ and executes all the statements in this case.

Here is the output of this program

First Run
Enter any of first four alphabet: a
You entered a and A

Second Run
Enter any of first four alphabet: g
You have not entered any of the first four alphabet.

From this program of the switch statement, you might think that it is necessary to use the keyword default. But it is not true. If you don’t use a default case and the switch statement does not find a match then nothing gets executes within the switch statement and the control is transferred to the next statement, if any, following the control structure.

Switch versus if-else

One may asks you – Is switch a better replacement for if-else? We know that both the switch and the if-else statements allow us to select from several alternatives. Each of these two decision control statements has its own advantages. The if-else statement can handle ranges for instance, you can use the if-else statement as
if (num >100 && num <=200)
// statements
else if (num >200 && num <=500)
// statements
else
// statements

The switch can not handle these ranges, each switch case label must be a single value and that value must be an integer or a character. You can not use even a floating case label. So as far as the ranges or float point number are countered, you must use if-else statement, on the other hand, if the case label are integer constants (or character constant) then the switch statement is more efficient, easy to write and understand. Like if-else statement, you can also use a switch within another switch but in practice it is rarely used, such statement is called nested switch statement.

The goto statement

The goto statement is an unconditional control statement. It takes the control where you want. Although it is necessary to understand the goto statement but it is not a good idea to use this statement because such programs are unreliable, unreadable and hard to debug.

Consider the following program
// Program con22.cpp 
#include
void main()
{
int number;
start :
cout << “\nEnter a number :”;
cin >> number;
if (number >=0)
{
cout << “Positive number”;
goto start;
}
else
cout << “You have entered a negative number”;
}

The output of this program is:

Enter a number =10
Positive number
Enter a number =20
Positive number
Enter a number = -5
You have entered a negative number.

In this program, the control is transferred to the label ‘start’ till the condition is satisfied. The label is terminated by a colon. The keyword goto, followed by this label name, then takes you to the label. However a good programmer should never use a goto statement in his/her program because there is almost never any need to use goto. You can achieve the same using some other more elegant decision Control and loop control statement.

Loops

The statements in programs, which we have seen so far, include either a sequential or decision control structure in which statements are executed exactly once. But in a general programming environment we need to perform an activity over and over, after with a little variation.

C++ provides loops that cause a part of your program to be repeated either a certain number of times or until a specific event occurs. This repetition process continues till a condition is true. When the condition becomes false, the loop terminates and controls transfers to the statement following the loop.

C++ provides three types of loop control structures: the while loop, the do-while loop and the for loop.

The while loop

Before the discussion of a while loop, let us see a program that finds the sum of a five-digit number.

// Program con23.cpp
#include
#include     // header file for abs()–function
void main()
{
int a, b, c, d, e, sum, number, n;
cout << “\nEnter a number – “;
cin >> number;
n = abs(number);
a = n%10;
n = n/10;
b = n%10;
n = n/10;
c = n%10;
n = n/10;
d = n%10;
n = n/10;
e = n%10;
sum = a+b+c+d+e;
cout << “\nSum of digits = ” << sum;
}

In this program, the statements
n % 10 and
n / 10

are repeated over and over. The first statement finds the least significant digits of ‘n’ and assigns it to any other integer variables. The second statement discards the least significant digit and reduces the length of ‘n’ by 1. These statements are repeated about five times till all digits in ‘n’ get exhausted. Thus for a five digit number, we repeat these two statements until n becomes 0 and add the digit at each step.

If you have a 4 digit number then these two steps are repeated for four times, three digit number three times and so on. Whatever may the number of digits of a number, the condition is that repeat these two statements until ‘n’ become 0. Thus it depends upon the number of digits of a number. It may be of any reasonable length using the while loop, we reformulate it so that it can becomes – generalized solution for any number.

The syntax of a while loop is:

 while (test-condition)
{
statement(s);
}

The while loop may have a single statement or a set of statements in its body. If the test-condition is true then the statement(s) in the body gets executed. After executing the loop body, the program returns to the test-condition and reevaluates it. This process continues and till the test-condition is true. Like for loop, if the test-condition is false in first attempt, the loop body would never get executed. The while loop is preferred in the circumstances where you do not know how many times you want to repeat the loop body before you start the loop.

figg4

Figure 4illustrates the operation of the while loop.


From this figure it is clear that you must do something within the loop body in order to terminate the loop eventually.

Now let us rewrite the program con23.cpp to make it a generalize solution for any number of any digits.

// Program con24.cpp
#include
#include
void main ()
{
int a, sum=0, n , num ;
cout << “\nEnter any number:”;
n = abs(num);
cin >>num;
while (num != 0)
{
a= num  % 10;
num = num /10;
sum = sum + a;
}
cout << “ \n Sum of digit =” <}

Here is the output of this program

Enter any number: 1234
Sum of digit =10

Now let us see another program that shows the working of a while loop.
// Program con25.cpp
#include
void main()
{
int num;
cout<< “\nEnter a positive number: “;
cin>>num;
while (num>=0)
{
cout<< “Square of  “< cout<< “\nEnter the another positive”;
cin>>num;
}
cout<< “\n you have entered a negative number”;
}

Here are the sample outputs of this program

First Run
Enter a positive number: 6
Square of 6 is 36

Second Run
Enter another position: -7
You have entered a negative number   

In this program we ask the user to enter a positive number. When the user enters a negative number the loop ends, since the condition (num>=0) fails.  Here there is no idea for the program to know in advance how many times the statements in the loop are to be executed.  As long as the test condition is true, the loop continues to be executed. The while loop does not contain any initialization expression and updation expression. It contains only a test-expression. That’s why the loop body must also contain some statement that changes the value of the loop variable; otherwise the loop variable cause the loop to continue indefinitely, such a loop is also known as infinite loop, as illustrated in program con26.cpp.
// Program con26.cpp
#include
void main()
{
int num;
num=1;
while (num>=0)
{
cout<< “\n Square of ”< cout<< “\n Enter the another positive”;
}
cout<< “\n you have entered a negative number”;
}

Here we have not updated the value of num. Therefore the loop will never get terminated.

Another important point to note that do not place a semicolon after the closing parentheses of the test-condition as:
while (num>=0);

Since a semicolon is treated as null statement and the loop body does not contain any such statement that could change the value of the loop.  Therefore the loop body would be executed continuously. It works like this
while (num>=0)                                     
{                            
}
  
If the while loop’s body contains the single statement then it is optional to enclose the loop body in braces. Therefore the following loop statement is absolutely right:
while (x==0)
cin>>x;

You can also use a while loop even when you know about the number of repetition of the loop. In this case, the loop counter variable is initialized before the while loop and its value is updated within the loop body. Following program calculated the average of three numbers for five different sets. 
// Program con27.cpp
#include
void main()
{
int count;
float a, b, c, average;
count=1;
while (count<=5)
{
cout<< “\n Enter three numbers :”;
cin >> a>>b>>c;
average = (a + b + c)/3.0;
cout<< “Average = ”<< average;
count++;
}   
}

Here is the sample output of this program:

Enter three numbers :11 12 13
Average = 12
Enter three numbers :12 13.5 24.7
Average = 16.733334
Enter three numbers :10 15.5 17.5
Average = 14.333333
Enter three numbers :45 23.7 56.7
Average = 41.799999
Enter three numbers :5 4 2.4
Average = 3.8

In this program, the loop body is executed five times. Initially the loop counter variable “count” is set to 1 and every time the average is evaluated, the value of count is incremented by when the value of count become 6, the test-condition false and the loop terminates.

Note that the loop counter may be a float variable. It means you can also initialize a loop counter variable, as
num = 0.2;

and update its value as
num = num +0.5;

The do-while loop 

The do-while loop is preferred when you want to execute loop body at least once. The syntax of do-while loop is as:
do
{
statement(s);

} while(test-condition);


Unlike while loop where the test-condition is tested before executing any of the statements within the loop body, do-while loop tests the test-condition after executing the statements within the loop. Thus the do-while executes the loop body’s statements at least once, even if the test-condition is false for the first time. 

Following program defines the subtle difference between while loop and do-while loop.
(i)   
// Program con28.cpp 
#include
void main()
{
int x=0;
while (x==1)
{
cout<< “ \n You have done a big mistake “;
cout<< “\n Never try this again “;
}
cout<< “\n  I was a big stupid “;
}

(ii)   
// Program con29.cpp 
#include
void main()
{
int x=0;
do
{
cout<< “\n Thanks god”;
cout<< “\n I have not done a big mistakes”;
} while (x==1);
cout<< “\n I am a big stupid”;
}

In earlier program con28.cpp the test-condition fails for the first time, thus its loop body would never get executed. On the other hand in later program con29.cpp, the loop body would be executed once and then the loop is terminated. Due to their speciality, the do-while loops are rarely used.

The for loop

The for is the simplest and the most popular loop to use and understand. The for loop is used to execute a part of program a fixed number of times. That’s why before entering into the loop, you must know, how many times you want to execute the loop body.

The general form of the for loop is as:
for (initialize_counter; test-condition; update_counter)
{
statement(s);
}
      
One of the main reasons behind its popularity is that all its loop control elements are gathered in one place. The for loop specifies three things in a single line as:

(a)    Initializing a loop counter value
(b)    Testing  the loop counter to determine if the loop should continue
(c)    Update the loop counter each time the program segment within the loop has been executed

All these three activities are enclosed in parenthesis and separated by semicolon from each other. The for loop evaluation initialization just once. Then the test condition determines whether the loop body gets executed. If the test condition is true, then the loop body executes, otherwise if it is false the loop terminates. Here the test-condition is evaluated before each loop cycle. It never executes the loop body when the test condition is false, If the test-condition fails the very first time; the loop body would never get executed. If the test-condition is true, the loop counter is updated after the loop body has been executed. You can either increment or decrement the value of loop counter in order to keep track of the number of loop cycles.

Following program con30.cpp demonstrates this for loop
// Program con30.cpp
#include
void main()
{
int n;
for (n=1; n<=5; n++)
cout<< “\n N=”<}

Here is the output:

N=1
N=2
N=3
N=4
N=5

Now let us see – how does this work?

Initially, the value of the loop counter ‘n’ is set to 1. When the loop is executed first time, the test-condition  n<=5 is evaluated. Since initially n is 1, the condition is true, therefore the body of the loop is executed for the first time. After executing the loop body, the control is transferred to the update section of the loop counter. The update section is always executed at the end of the loop. Here the value of n is incremented by 1 each time through the loop. Again the test-condition is checked. If it is true the loop body gets executed, otherwise the loop ends. Thus process continues till the value of the n does not exceeds

When the value of n becomes 6, the test condition becomes false and the control is transferred to the first statement, if any, followed the body of the loop.

Here you have just one statement in the loop body. But you may have more than one statement in the loop body. If you have multiple statements in the loop body then it is necessary to enclose them with in a pair of curly brackets ({ }). If you have just one statement in the loop body then it is optional to enclose it in braces. Each individual statement in the loop body is terminated by semicolon after the final braces of the loop body.

In the earlier program, you have incremented the value of the loop counter in the update section, you can also decrement the loop counter as shown in this program
// Program con31.cpp
#include
void main()
{
int n;
for (n=10; n>=1; n--)
cout<< “\nN=”<}

The output of this program is

N=10              N*N=100
N=9                N*N=81
N=8                N*N=64
N=7                N*N=49
N=6                N*N=36
N=5                N*N=25
N=4                N*N=16
N=3                N*N=9
N=2                N*N=4
N=1                N*N=1

Since we know that C++ is a free- form programming language, just for the good programming style the loop body is indented to the right so that one can easily determine at first look which statements of the program are inside the loop. If you have one statement in the loop then just one statement is indented. If you have a set of statements inside the loop then thew entire set is indented.

Following program should shows this view
// Program con32.cpp
#include
void main()
{
int n;
for (n=1; n<=5; n++)
{
cout<< “\n N=”< cout << “\tN*N=”< cout<< “\tN*N*N=”< }
}

The output of this program is

N=1     N*N=1      N*N*N=1
N=2     N*N=4      N*N*N=8
N=3     N*N=9      N*N*N=27
N=4     N*N=16    N*N*N=64
N=5     N*N=25    N*N*N=125

Unlike C, C++ allows to define a variable near the location it is first used. Thus the following for statement is complete valid statement
for (int n=1;n<=5; n++)
{
//
}

Note that you cannot declare the variables after its usage. 

You can also have multiple initialization in the initialization part of the for loop and the multiple increment/decrement expressions in the update section of the for loop. But remember that you can have only test-condition. This test-condition may contain itself several conditions logically combined using logical operators. For example
for (i=1, j=5; i<=5; i++, j--)
cout<< i <<  “ ” << j << “\n”;

In this program we have initialized a normal loop variable i, and one more variable j. Similarly in update section, we have two expressions: i++ and j--. Note that multiple initialization expressions and multiple expressions are separated by comma.

Let us some different forms of a for loop
(i)   
for(n=1;n<=5;)
{
statement(s);
n++; }

(ii)   
n=1;
for( ; n<=5;n++)
{   
statement(s);
}

(iii)   
n=1;
for(;n<=5;)
{
statement(s);
n++;
}

In first case, you have update the value of a loop counter in body of the for loop, but still the semicolon after the test condition is mandatory.  In second case you have initially the loop counter before the for loop, but still the semicolon before the test-condition is necessary as far as the third case is concerned, neither the initialization, nor the updation is done in the for statement but still the two semicolons (or before test-condition and or after the test-condition) are necessary.

In programs, which we have seen so far, increase the value of the loop counter by 1 in each iteration. We can also changes that value by changing the update expression. See the behavior of the following program in which we have increase the loop counter by 3. 
// Program con33.cpp
#include
void main( )
{
int n;
for( n=1; n<=20; n=n+3)
cout<< “\nN =”<}

The output of this program is

N=1
N=4
N=7
N=10
N=13
N=16
N=19

Once n reaches the value 22, the loop terminates. From this it is clear that update expression can be any valid expression.

Now we will see another typical program of a loop. Let we want to sum the following series:
Sum = x – x3/3! + x5/5! – x7/7! + ……… (-1)n-1 x2n-1/(2n-1)!

// Program con34.cpp
# include
void main ()
{
int i , n ;
float x, sum , num , den , sn = -1; 
cout << “\nEnter x and n: ”;
cin >> x >> n;
sum = x;
num = x;
den = 1;
for (i=1 ;i <=n-1 ; i ++) 
{
num = num * x * x;
den = den * (2*i) * (2*i+1);
sum = sum + (num /den ) *sn;
sn =-sn;
}
cout << “\nX=” <}

The output of this program is as

Enter x and n: 6 5
X = 6
N = 5
Sum = 7.028572

Whenever someone says you to write a program for a series, firstly calculate the relation, which gives the technique of finding a term in the series from the previous terms. From this series
ith item = (-1)i-1x2i-1 /(2i-1)!(i +1) 
item = (-1)I x(2i+1)/(2i+1)!

Thus (i +1)th item = (-1)  x2/(2i+1)(2i)* ith item

Nested loops

Like nested if ,while and for , C++ provides the facility of nested while loops, that is defining a while loop with in another while loop. You can also define a while loop in a for loop or vice versa.  Following example illustrates the concept of nested loops.
// Program con35.cpp
#include
void main ( )
{
int  i, j, temp;
for (i=1;i<=3;i++ )
{
for ( j=1 ;j<=3 ; j++)
{
temp = i * j;   
cout << “\nI=”<< i << “\tJ=”< }
}
}

The output of this program is as

I=1     J=1     I*J=1
I=1     J=2     I*J=2
I=1     J=3     I*J=3
I=2     J=1     I*J=2
I=2     J=2     I*J=4
I=2     J=3     I*J=6
I=3     J=1     I*J=3
I=3     J=2     I*J=6
I=3     J=3     I*J=9

The break statement

The break statement is used in a switch statement and in any of the three loops. The break statement transfers the control to the first statement following: the switch or the loop. A break is usually associated with an if statement. When it is encountered in a loop, the control is immediately transferred to the first statement after the loop, without waiting to get back to conditional test.

The break statement is used as:

 break; 

The operation of the break statement is shown as shown below:
statement; 
while (test-condition1)
{
statement(s);
if(test-condition 2)
break;
statement(s);
}
statement;


Program shows how the break statement works?

// Program con36.cpp
#include
void main( )
{
int num , i , flag;
cout<< “\nEnter a number :”;
cin>>num;
i=2;
flag=0;
while (i<=num/2)
{
if(num%i==0)
{
flag = 1;
break;
}
i++;
}
if (flag==0)
cout<< “Prime number: ”<< num;
else
cout<< “Not a prime number: ” << num;
}

Here are the sample outputs of this program

First Run
Enter a number: 14
Not a prime number

Second Run
Enter a number: 17
Prime number

In this the program the moment the condition (num%i==0) results in true, the flag variable is set to1 and the control is transferred out of the while loop. The while loop can also be terminated when the value of i becomes less than or equal to num. After the while, the value of flag is tested. If the flag is 0, then it display a message “Prime number”; otherwise it display the message “Not a prime number”.

Note  that if the break statement is encountered in nested  loop , the control is transferred  outside the loop in which it is placed.

Following program illustrates this point.
// Program con37.cpp
# include
void main()
{
int i ,j , k;
for (i=1;i<=3;i++)
{
for(j=1;j<=3; j++)   
{
for(  k=1; k<=3;k++)
{
if ((i ==j)||(j==k)||(k==i))
break;
else
cout< }
}
}
}

Here whenever i equals to j, and j equals to k and k equals to i, then the innermost for loop is terminated by the break statement and the control is transferred outside by the inner most for loop.

Here is the output of this program

2    3    1
3    2    1

The continue statement


Unlike the break statement, the continue statement takes the control to the beginning of the loop and skip the rest of the loop body. The continue statement is used in loop only, not in a switch statement, like a switch statement. The continue statement is used as
continue;
        
Like the break statement, the continue statement is usually associated with an if statement, the operation of the continue statement is shown in figure:
statement; 
while (test-condition1)
{
statement (s);       
if( test-condition 2)
continue ;
statement (s);       
}   
statement (s);

Following program clears the concept of continue statement:
// Program con38.cpp
#include
void main()
{
int i , j , k ;
for ( i=1; i<=3; i++)
{
for ( j=1 ;j<=3;j++)
{
for (k=1 ;k<=3;k++)
{
if ((i==j)||(j==k)||(k==i))
continue ;
else
cout << "\n" << i << "\t" << j << "\t" << k ;
}
}
}
}

The output of the program is

1     2     3
1     3     2
2     1     3
2     3     1
3     1     2
3      2    1

In this program when the value i equals to j, and j equals to k and k equals to i, the continue statement transfers the control to the inner most for loop by skipping the remaining statement of the inner most for loop.

 

C++ provides two types of decision making statements: if-else statement and switch-case statement. The conditional operator ? and : can often be used in place of a simple if – else statement. Relational operators compare two numbers and its result is either true or false. A true is indicated by a non-zero value and false by 0.

The logical AND and OR operators combine two or more boolean expressions into one. The logical NOT operator changes  the boolean value from true or false, or from false to true. The break statement terminates the switch statement and than the control to the statement, if any following the switch statement. The goto statement transfers the control to the label.

A loop executes the same statement or a set of statements over and over as long as the loop test-condition is true and the loop terminates when the test-condition becomes false.  C++ provides three types of the loop – the while loop, the do-while loop and the for loop. The while loop and for loop are entry-controlled loops, that is they examine the test-condition prior to the execution of the loop body. The do-while loop is an exit-condition loop, that is it examines the test-condition after executing the loop body. A loop body may consist of a single statement, or a block of multiple statements enclosed within pair of braces.

The break statement terminates the loop in which it is placed and transfers the control to the first statement following that loop. The continue statement skips the remaining statements of the loop and transfers the control to the top of the loop in which it is placed.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~END~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

 


Like it on Facebook, Tweet it or share this article on other bookmarking websites.

No comments