Control Structures in C++

category: 

In the given example, if the tested expression is true, the statement 1 is executed. Otherwise, is not  executed and control will transfer the statement following the condition. The if statement in the following illustration causes the computer to evaluate the expression X and 20. If the value of X is greater than 20, execute the statement y = z / x. otherwise don’t execute this statement but in either case, execute a = b * x.

if (x>20)

y = z/x;

a = b * x;

To illustrate a single-alternative decision, we present a sample program. Read any two integer values, compare them and prompt the user for the largest value.

if (x > y)

            cout

if (y > x)

            cout

Two-way Decision

In two-way decision, the execution of an if statement allows us to choose between two alternatives. This depends on the evaluation of the condition. If the expression is true, the if part is executed, otherwise the else part. In other words, one of the alternatives is executed.

The general format of a two-way selection:

If(expression)

            Statement1;

else

            Statement2;

In one-way decision, two if’s have been used to find the largest value. One if can easily be avoided by using the concept of two-way decision.

if(x > y)

            cout

else

            cout

In both cases, after the execution of the appropriate statement sequence, control passes to the statement following the if statement. Statement1 and statement2 could either be a single statement or a compound statement. The parentheses around the expression is required and one must be careful about the placement of semicolon before the else clause. The two curly braces are must for a compound statement.

if(x > 20)

            Y = z / x;

else

            y = z * x;

The if-else statement execute either statement in the if clause or statement in the else clause. Since a semicolon terminates every simple statement, the semicolon is required. The rule not the indentation for terminating semicolon for the if portion is not going to be affected by the presence of an else statement.

Multi-way decision

Multi-way decision statements perform different jobs depending on the value of expression. In multi-way decision, instructions are different. First check the condition, if true, then execute the if part. The first statement is optional. The programmer can put another condition after the first condition and so on. The same is true for the else clause. After if clause, the else part is written. An if within and if …. Is allowed. This means that the body of if statement could be another if statement. This situation is called a nested if and is often used to choose between ranged of values. It allows you to make decision given the results of a previous decision. Too many if’s in a program make it cumbersome, to avoid this inconvenience or problem, Switch statement is used.

To illustrate a nested if, we next present a sample program. The problem is to get input in read in temperature and print out the appropriate message for football play. The constant values must be compared with the read in temperature using the following guidelines.

Temperature Message
>=90 Too hot for football
>=30 Suitable for football
Too cold for football

The c++ program with the three different sample of the above problem is shown in program multi.cpp with the run output.

  1. //Program name: multi.cpp
  2. //This program reads an integer value in variable temperature and prints out
  3. //an appropriate weather conditions for a football play
  4. #include
  5. int main (void)
  6. {
  7.             int temperature;
  8.             cin>>temperature;
  9.             cout
  10. if(temperature >= 90)
  11.             cout
  12. else
  13.             if(temperature >= 30)
  14.             cout
  15. else
  16.             cout
  17. }

Output of Program

90

Too hot  for football

50

Suitable for football

10

Too cold for football

The else statement is associated with the nearest unmatched if statement. In case there is doubt, enclose portions of that code within block. Braces can be used to specify the if statement to which an else clause belongs.

if(condition1)

{

            if(condition2)

            Statement1;

}

else

            Statement2;

In this case, we have avoided confusion, the else part is performed if condition1 evaluates to false. As we k now, multi-way decision statements involve using nested if’s. Another example of this type is shown in a program called multi1.cpp.

  1. //Program name: multi1.cpp
  2. //Program to find whether the input value is greater or equal
  3. //or less than zero
  4. #include
  5. int main(void)
  6. {
  7.             int x;
  8.             cout
  9.             cin>>x;
  10. if(x>0)
  11.             cout
  12. else
  13.             if(x == 0)
  14.             cout
  15. else
  16.             cout
  17. return 0;
  18. }

Output of Program

Enter a value

1

X value 1 is greater than zero

Enter a value

0

X value 0 is equal to zero

Enter a value

-1

X value -1 is less than zero

Iterative Execution

This is another important capability of C++ programming language. It causes the computer to execute some set of instructions again and again. Iterative execution means to execute a group of instructions repeatedly until as it satisfies the condition.

Suppose you want to calculate sales tax on a large number of different items. Each new calculation requires the program to be rerun and this will cause problem through the printing of the same instructions over and over again. To avoid this inconvenience, one solution is to redesign the program so as to print the instructions once. After the printing the instructions, accept a price, calculate the tax and then print it out. Doing this process repeatedly until it is needed. This process is accomplished with iteration statements or loops. C++ language has added a capability of looping which has been discussed in the subsequent chapter in detail, but here is a small beginning, to clear the concept of the novice programmer in a look alike English language.

Suppose you want to print the message, “Hello World”, more than once, it would be written like

10 print “Hello world”

20 goto 10

The result of this would be

Hello world

Hello world

Hello world

.

.

Forver!

Rules not the indentation

A statement in if or else clause may either be a single statement or compound statement.It depends on the programmer that how he make his logic. The difference between the two interpretations is explained in a significant way In alternative 1, v1 is incremented only if v1 is negative and v2 is non-negative. In alternative 2, v1 is incremented only if v1 Is non=negative. This ambiguity is called the Dangling else problem. C++ resolves this ambiguity with the use of the first interpretation. An outer else is always associated with the innermost if. Sometimes the use of a redundant ({) and (}) is useful to clarify the statements. It is just like when we use parentheses to make the meaning of an arithmetic expression clear and obvious. In some cases, it is helpful to use ({) and (}) for a single statement but technically it is not good.

Alternative 1

if(v1

{

            if(v2

            v2 = v2 +1;

else

            v1= v1 + 1;

}

Alternative 2

if(v1

{

            if(v2

            v2 = v2 + 1;

}

else

            v1= v1 + 1;

Note that computer follow the language rules not the indentation of a program. In the previous interpretation 1, if we remove ({) and (}), it would look like this;

If(v1

            If(v2

            V2= v2+1;

Else

            V1= v1 + 1;

If we go by the indentation, the else part is associated with the outer if which is absolutely wrong in C++ language. Things are not what they appear to be. The else is associated with the nearest if, regardless of how we layout the source program on the printed page.