C++ Chapter 4

Chapter Four

 

Conditions and loops are inalienable components of structured programming. These form what are called program constructs or structures.

 

Program Structure

 

:

 

DECISION MAKING

 

The if structure

 

: The if condition is followed by a test expression which is evaluated to true or false, and this determines whether the subsequent statement or block is to be executed or skipped. Note that the test expression after if is enclosed in parenthesis and not followed by any semi-colon.

 

You are already familiar with BASIC programming, and the signs <, >, >=, <= have the same meaning. Note, however, two important exceptions - we write if (a == 5) [corresponding to IF A = 5 in BASIC] and also if (a != 5) [corresponding to IF NOT A=5 in BASIC]. In addition, the word THEN is not used in C++.

 

Also when two or more conditions are combined, && is used for logical AND as also || is used for logical OR. Conditions connected by && evaluate to TRUE only if both or all are TRUE, whereas conditions connected by || are TRUE if at least one of them is TRUE.

 

Thus if (a == 6 && b < 5) is equivalent to IF A=6 AND B<5 of BASIC.

Also if (a == 6 || b < 5) is equivalent to IF A=6 OR B<5 of BASIC.

 

If P represents the condition (a==6) and Q represents the condition (b < 5) then the result of joining them by AND or OR will be P AND Q or P OR Q. Representing TRUE by 1 and FALSE by 0, we may show that the result of logical AND is multiplication and of logical OR is addition. The following truth table will clarify the concept.

 

Value_of_P (0 or 1)

Value_of_Q (0 or 1)

P && Q (P.Q)

P || Q (P+Q)

Remarks

P = 0 (false)

Q = 0 (false)

0 (F)

0 (F)

P && Q true

P = 0 (false)

Q = 1 (true)

0 (F)

1 (T)

only if both are true

P = 1 (true)

Q = 0 (false)

0 (F)

1 (T)

P || Q false

P = 1 (true)

Q = 1 (true)

1 (T)

1 (T)*

only if both are false

* 1+1=2; but any value greater than 0 is TRUE and is taken as 1

 

Now observe the difference between the following two programs and their outputs:

 

//program-3.06 To illustrate if (in block)

#include <iostream.h>

void main()

{

int mks; //variable for your marks

int passmrk = 40;

cout << "Enter your marks ";

cin >> mks;

cout << "Your results" << endl;

if (mks >= passmrk) //if condition--no semi-colon

{

cout << "You have Passed" << endl; //a block of

cout << "Well done!"; //two statements

} //end of if block

}

 

 

Output (first run): Output (second run):

Enter your marks 50 Enter your marks

20

Your results Your results

You have passed

Well done!

 

The above gives no output when the if condition is not met. That is, the two statements in a block are regarded as a compound statement, and either both are executed or both are skipped

Now we rewrite the program but without the braces after if condition

//program-3.07 To illustrate if (no block)

#include <iostream.h>

void main()

{

int mks; //variable for your marks

int passmrk = 40;

cout << "Enter your marks ";

cin >> mks;

cout << "Your results" << endl;

if (mks >= passmrk) //if condition--no semi-colon

cout << "You have Passed" << endl; //no block

cout << "Well done!"; //not governed by if condition

} //end of if block

}

 

 

Output (first run): Output (second run):

Enter your marks 50 Enter your marks

20

Your results Your results

You have passed Well done!

Well done!

The display of the statement "Well done!" is unconditional.

 

Thus, the first program executes the entire block (i.e., outputs the statements "You have Passed" and "Well done!") only if the input mark is 40 or above. Thus the statements in the block are subject to the if condition.

 

The second program unconditionally prints "Well done!" irrespective of whether you have secured above or below 40. Only the statement "You have Passed" immediately following the if condition is printed or skipped depending on the input value.

 

So the summary is this:

 

If a single statement is subject to a condition, do not use braces. If two or more statements or actions are condition dependent, enclose them within a pair of braces to form a block.

 

The if - else structure

 

: The if - else in C++ is just like IF - THEN - ELSE of BASIC. As in if, a single statement or an entire block after else is condition dependent according to whether they are without or within braces. The else part is executed when the test expression of the if condition gets evaluated to false.

 

//program-3.08 To illustrate if else

#include <iostream.h>

void main()

{

int m1 = 45, m2 = 30, m3 = 20, m4 = 60;

/* four variables (marks of 4 boys) */

int pm = 40; // pass mark

int cnt_pass = 0; //counters for pass / fail

int cnt_fail = 0; // both initialized to 0

 

//condition begins

if(m1 < pm) //if below pass mark

cnt_fail = cnt_fail + 1; // increase fail count

else // otherwise

cnt_pass = cnt_pass + 1; // increase pass count

if(m2 < pm)

cnt_fail = cnt_fail + 1; //same for second boy

else

cnt_pass = cnt_pass + 1;

if(m3 < pm)

cnt_fail = cnt_fail + 1; //same for third boy

else

cnt_pass = cnt_pass + 1;

if(m4 < pm)

cnt_fail = cnt_fail + 1; //same for fourth boy

else

cnt_pass = cnt_pass + 1;

/* output result on screen */

cout << "No. of boys Passed..." << cnt_pass;

cout << endl <<endl; //new linefeed

cout << "No. of boys Failed..." << cnt_fail;

 

}

Output:

No. of boys Passed...2

No. of boys Failed... 2

Increment / Decrement Operator

 

: A very convenient increment / decrement operator is ++ or --. This always increases or decreases the value of the variable by unity.

 

Thus, in the above program cnt_fail = cnt_fail + 1 may be written as cnt_fail++. Similarly, for any variable n, n++ and n += 1 mean the same (namely, n = n+1) Similarly, n-- or n -= 1 means n = n-1.

 

Rewrite the above program using the new notations. Also, do not assign the marks to m1, m2, m3, m4. Instead input marks from keyboard, using

cin >>

 

Pre-increment and Post-increment

 

: A variable (say a) may be incremented as a++ or ++a. In a++, the ++ sign is called post-increment; in ++a, it is called pre-increment.

 

In a standalone statement, a++ and ++a are identical and it is immaterial which one is used. However note the following:

 

int a = 10; int b = 10;

cout << a++;

//it first outputs 10, then increments a to 11

cout << a; //now it prints 11

cout << ++b);

//it first increments and then outputs 11

cout << b; //it prints 11 again

 

Similar is the case with decrement operator: a-- and --a work as post- and pre- decrements.

 

The if - else if - else statement

 

: When there are 3 or more branching depending on the outcome of test expressions, we use

if - else if … else -

//program-3.09 To illustrate else if

#include <iostream.h>

void main()

{

int m = 56; // marks obtained

/* condition begins */

if (m > 80)

cout << "First Class Distinction";

else if (m > 60)

cout << "First Class";

else if (m > 50)

cout << "Second Class";

else if(m > 35)

cout << "Third Class";

else //no condition specified

cout << "Failed";

}

Output:

Second Class

 

Rewrite the above program by replacing int m = 56 with cin >> m. Check for various marks input such as 85, 70, 55, 40, 20.

 

//program-3.10 To illustrate else if-a 4 function calculator

#include <iostream.h>

void main()

{

float a = 4.56f; //note suffix f for float

float b = 6.93f;

cout << "Enter + or - or * or /... ";

char op;

cin >> op;

if (op == '+') //note double equality sign

cout << (a + b);

else if (op == '-')

cout << (a - b);

else if (op == '*')

cout << (a * b);

else if (op == '/')

cout << (a / b);

else

cout << "Error";

}

 

Output:

Enter + or - or * or / ... -

//minus sign is entered by user

-2.37

 

Rewrite the program by using cin >> to read values of a, b from keyboard. Assign a value for op thus: op = ‘+’ (within single quotes since op is a character variable).

 

Truly Speaking

 

: Just what is TRUE and what is FALSE in C++? While philosophy may still debate the matter of truth, absolute or relative, C++ is very clear on this. In C++, a zero value is FALSE, while one (or any non-zero value) is TRUE. The statement if (x) would mean if x is true (i. e., if x = 1 or any non-zero value), and if (!x) would mean if x is false (i. e., if x = 0).

 

#include <iostream.h>

void main()

{

int a = 1; int b = 0;

cout << (a > b) << endl; //it is true

cout << (a < b) << endl; //it is false

if (a) //a > 0

cout << "T" << endl;

else

cout << "F" << endl;

 

if (b) //b = 0

cout << "T" << endl;

else

cout << "F" << endl;

}

 

Output:

1

// a > b is true, hence output 1

0

// a < b is false, hence output 0

T

// a > 0, hence True

F

// b = 0, hence False

 

 

TERNARY OPERATOR

 

: Study the following code.

 

if (a > b)

c = a;

else

c = b;

 

This may be written in a more condensed and terse style using the ternary operator:

 

c = (a > b) ? a : b;

 

The test expression is followed by a question mark. If true, the first variable / expression and if false, the second one (after colon) is assigned to the variable c.

 

The program earlier written to show that in C++ 0 is false and 1 (or any other value) is true may be written thus:

 

#include <iostream.h>

void main()

{

int a = 1; int b = 0;

cout << (a ? "T" : "F")<< endl;

cout << (b ? "T" : "F") << endl;

}

 

Output:

1

//true because

a = 1//false because

b = 0

 

Ternaries may be nested, but take care as they are prone to error for beginners. The following code finds the highest of 3 numbers:

 

max = a > b ? (a > c ? a : c) : (b > c ? b : c);

 

Now write the code for finding the smallest of 3 numbers.

 

 

SWITCH

 

We will now rewrite the four-function calculator using switch instead of else if as follows:

 

//program-3.11 To illustrate else if-a 4 function calculator

#include <iostream.h>

void main()

{

float a = 4.56f; //note f for float

float b = 8.67f;

char op = '+';

 

switch (op) //switch(var) begins...note parentheses

{

case '+': //if switch variable matches '+'

cout << (a + b);

break; //exit the switch block

case '-': //if switch variable matches '-'

cout << (a - b);

break; //exit the switch block

case '*': //if switch variable matches '*'

cout << (a * b);

break; //exit the switch block

case '/': //if switch variable matches '/'

cout << (a / b);

break; //exit the switch block

default: //if no match is found

cout << "Error";

} //close of switch block

} //end of main()

 

Output:

13.23

 

Rewrite the above using cin >> to read from keyboard the values of a, b, op.

 

The default case is usually but not necessarily the last one. If break is not used it will execute all subsequent cases following a successful match-find.

 

Although use of switch (value) is more convenient and elegant, it cannot be used if the determining variable is a non-integer or if there are more than one determining variables [e.g., if (a > 5 && b < 4)].

 

Now we rewrite the program using integer values instead of characters for addition, subtraction, multiplication, and division operations.

 

#include <iostream.h>

void main()

{

float a = 4.56f; //note f for float

float b = 8.67f;

int op = 2;

 

switch (op) //switch(var) begins...note parentheses

{

case 1: //if switch variable matches '+'

cout << (a + b);

break; //exit the switch block

case 2: //if switch variable matches '-'

cout << (a - b);

break; //exit the switch block

case 3: //if switch variable matches '*'

cout << (a * b);

break; //exit the switch block

case 4: //if switch variable matches '/'

cout << (a / b);

break; //exit the switch block

default: //if no match is found

cout << "Error";

} //close of switch block

} //end of main()

 

Output:

-4.11

 

ITERATIONS

 

When a single instruction or a set of instructions is to be performed repeatedly, subject to some preset condition(s), it is called a loop or iteration.

 

The for loop

 

: The syntax consists of initial value of a variable, its final (exit) value, and how the variable will be incremented or decremented.

 

//program-3.12 To illustrate a for loop

#include <iostream.h>

void main()

{

int num, count;

for(count = 1; count <= 10; count++) //no semi-colon

{ // braces to include block

num = count * 2; //body of loop

cout << num << ", ";

} //end of loop

} //end of main()

 

Output:

2, 4, 6, 8, 10, 12, 14, 16, 18, 20

 

The parenthesis after for consists of 3 elements separated by semi-colons. Here, for example,

 

the first element is initialization of the variable count (count = 0;)

the second is the condition for the loop to continue (so long as count <= 10;)

the third is how the count changes (count++;)

 

Thus the minimum for a loop to be technically correct is for(… ;… ;)

 

When there are more than one variables they are comma separated thus:

 

for(i=0, j=5; i<6 || j>10; i++, j--)

 

As in case of if, braces are not needed if there is only a single statement under a loop.

 

What is the difference between the following code segments?

 

(i) for(a=0; a<4; a++)

cout << "Hello!"; // no braces or block

cout << "Thank you"; //not under loop

 

(ii) for(a=0; a<4;a++)

{

cout << "Hello! "; // block within braces

cout << "Thank you"; //all under loop

}

 

The first one prints "Hello!" many times, but "Thank you" only once. Only the first statement is under loop.

 

The second one prints both "Hello!" and "Thank you" repeatedly, as both form a block under the loop.

 

We print the odd and even numbers thus:

 

#include <iostream.h>

void main()

{

int i;

for (i = 1; i <= 10; i += 2) //i += 2 means i = i + 2

cout << i << '\t'; //a tab for a space

cout << endl; //new line

for (i = 2; i <= 10; i += 2)

cout << i << '\t';

cout << endl;

}

 

Output:

 

1 3 5 7 9

2 4 6 8 10

 

The following program prints the factorial of any positive integer (not zero).

 

//program-3.13 To illustrate a for loop--factorial

#include <iostream.h>

void main()

{

int prod = 1; //initialize

int num = 5; //(1)

int cnt; //declare variables

for(cnt = 1; cnt <= num; cnt++)

prod *= cnt; //only one statement under loop

cout <<"Factorial is " << prod;

}

 

Output:

Factorial is 120

 

Rewrite the above code replacing line (1) above with cin >> num;

 

The while loop

 

: The loop continues while (or so long as) the condition stated in parentheses after while is true. We shall rewrite the above program using a while loop.

 

//program-3.14 To illustrate a while loop--factorial

#include <iostream.h>

void main()

{

int prod = 1, cnt = 1, num = 5; //initializations

while (cnt <= num) //no semi-colon

{ //braces for multiple statements

prod *= cnt;

cnt++; //increment of cnt inside body

} // end of while loop

cout << "Factorial is " << prod;

}

 

Output:

Factorial is 120

 

The increment could have been done along with the statement prod *= cnt; and the program would stand thus:

 

#include <iostream.h>

void main()

{

int prod = 1, cnt = 1, num = 5; //initializations

while (cnt <= num) //no semi-colon
prod *= cnt++; //post increment

cout << "Factorial is " << prod;

}

 

The do while loop

 

: The loop is introduced by the key word do, followed by opening brace which contains the block of statements; after the closing brace the while condition is specified. Thus the first iteration is unconditional, the stipulations are checked at the end of the block for continuation or exit.

 

 

We shall rewrite the factorial program using do while loop.

 

//program-3.15 Factorial using do - while loop

#include <iostream.h>

void main()

{

int prod = 1, cnt = 1, num = 5;

do //no condition for first iteration

{

prod *= cnt;

cnt++; //increment of cnt inside body

} while (cnt <= num); //condition at end of loop

//for 2nd and all

//subsequent iteration

cout <<"Factorial is " << prod;

}

 

 

Output:

Factorial is 120

 

Here also we could have incremented cnt along with the statement prod *= cnt; and written the code thus:

 

#include <iostream.h>

void main()

{

int prod = 1, cnt = 1, num = 5;

do //no condition for first iteration

prod *= cnt++;

while (cnt <= num);

/*condition at end of loop for 2nd and all subsequent iteration*/

cout <<"Factorial is " << prod;

}

 

We have shown that the same program may be written using a for loop, a while loop or a do while loop. However, the following principle will broadly guide us in the choice of the most convenient form of loop in a program:

 

(a) Use for loop when the number of iteration is known (e.g., find the sum of first ten even numbers or print a statement five times.

 

(b) Use while or do while loop when only the final exit condition is known, the condition may be numerical (e.g., print Fibonocci Series up to 100) or non-numeric (e.g., repeatedly ask a user whether he wants to continue, exit when he says ‘n’).

 

(c) A while loop checks the condition before entering the loop, it may not enter the loop at all if the condition is false at the outset. A do while loop checks the condition at the end of the first iteration, so it will execute it at least once.

 

 

For example to print the first ten terms of Fibonocci Series we would prefer for loop, but to print Fibonocci Series up to and not exceeding 100 a do while loop (or a while loop) would be used.

 

Fibonocci series consists of numbers starting with 1, 1 such that each subsequent term is the sum of the preceding two terms.

 

//program-3.16 - Fibonocci Series first 10 terms

//1 1 2 3 5 8 13 21 34 55

#include <iostream.h>

void main()

{

int num1 = 1; int num2 = 1; int num3;

cout << num1 << " " << num2 << " ";

for (int term = 3; term <=10; term++)

{

num3 = num1 + num2;

cout << num3 << " ";

num1 = num2; num2 = num3;

} //end of loop

}

Note the use of " " (space) between numbers.

Output: 1 1 2 3 5 8 13 21 34 55

//program-3.17 - Fibonocci Series below 100

#include <iostream.h>

void main()

{

int num1 = 1; int num2 = 1; int num3 = 2;

cout << num1 << " " << num2 << " ";

do

{

cout << num3 << " ";

num1 = num2; num2 = num3;

num3 = num1 + num2;

} while (num3 <= 100);

}

 

Output: 1 1 2 3 5 8 13 21 34 55 89

 

Nested loops

 

: A loop inside a loop is called a nested loop. The following program prints the pattern:

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

 

//program-3.18 To illustrate nested loop

#include <iostream.h>

void main()

{

for (int i=1; i<=5; i++) //for 5 rows

{

for (int j=1; j<=i; j++) //for numbers

cout << j << " "; //each row

cout << endl; //new line

} //end of outer for loop

}

 

Now write similar programs to print the reverse pattern and a pattern of stars.

 

Break

: Break in a loop causes the flow to exit the smallest block enclosing while or for statements, thus skipping the rest of the statements in the block as well as any more iterations of the loop.

 

Break

is used in switch cases, otherwise once the matching option is found, it falls through and executes all the subsequent options as well. For example, the following switch code fragment does not contain break; notice the output:

 

switch (n)

{

case 1: System.out.println ("A");

case 2: System.out.println ("B");

case 3: System.out.println ("C");

case 4: System.out.println ("D");

case 5: System.out.println ("E");

default: System.out.println ("Wrong");

}

 

If n is 3, the output will be C D E Wrong. To rectify, use break; this will ensure that the control exits the switch block after executing the matching case.

 

Continue

causes the control to skip over the rest of the statements in the block, but (instead of exiting the block) it resumes a fresh iteration at the start of the loop.

 

//program-3.19 To illustrate break / continue

#include <iostream.h>

void main()

{

for (int i=0; i <= 5; i++)

{

if (i == 3)

break; //go out of loop

cout << i << endl;

}

}

 

Output: 0 1 2 (in separate lines). When the value of i becomes 3, it not only skips the execution of the subsequent statement [print (i)] but also terminates further iterations of the loop.

 

Now replace the word break; with continue; the output becomes 0 1 2 4 5 (in separate lines). When the value of i is 3, it skips the subsequent statement [print (i)], thus 3 is not printed. However the control is sent back to the start of the loop for the next iterations with the values of i = 4 and i = 5 - so 4 and 5 are printed.

 

In addition exit() causes the program to abort (terminate) and return to the system.

 

The modulus (%) operator

 

: The modulus operator may be used to extract the remainder of an integer division. For example, 20 % 6 gives 2. It corresponds to 20 MOD 6 of BASIC. In Java the number or / and the divisor may be either integers or decimal fractions.

 

The condition if (n%2 == 0) may be used to determine whether the integer n is even. Similarly n % 10 extracts the rightmost digit of a number.

 

//program-3.21 To reverse a number

#include <iostream.h>

void main()

{

int num = 4281, rev = 0, rem;

while (num > 0)

{

rem = num % 10;

rev = rev*10 + rem;

num = (num - rem)/10;

} //end of while loop

cout << "Reversed number is " << rev;

}

Output:

1824

 

To check for a pallindromic number, store the original number in another variable (numcopy = num) before starting the while loop. At the end of the loop, if the reversed number matches with the original number (numcopy) then it is a pallindromic number.

 

The following program prints all 3-digited Armstrong numbers, where the sum of the cubes of the digits is equal to the number itself.

 

//program-3.22 To print all Armstrong Numbers

#include <iostream.h>

void main()

{

int n, r;

for (int c = 100; c < 1000; c++)

{

int d = c;

n = 0;

do{

r = d % 10;

n = n + r * r * r;

d = (d - r) / 10;

} while (d > 0);

if (n == c)

cout << c << ", ";

} //end of for loop

}

Output:

153, 370, 371, 407

 

 

Use of flag as a variable

 

: The following program to ascertain if a number is prime illustrates its use. The variable is initialized to 0; it changes only once if the division has been complete by any divisor in the entire loop. The change of value of a flag is done by using an if condition, but never, never does it include an else clause.

//program-3.23 To illustrate flag to check for prime

#include <iostream.h>

void main()

{

int num; int dvr; int flag = 0;

cout << "Enter a number ";

cin >> num;

for (dvr = 2; dvr < num; dvr++)

if (num % dvr == 0)

flag = 1;

/* flag changes if number is divisible by any divisor */

if (flag == 1) //if divisible by any dvr

cout << "Not a prime number";

else

cout << "A prime number";

 

}

Output:

Enter a number 24

Not a prime number

Enter a number 17

A prime number

 

Thus flag is just an ordinary variable and could be called by any name, except that calling it flag is convenient and it improves the readability of the program because its purpose becomes self-explanatory.

 

We may now rewrite the program to convert the case of a letter.

 

//program-3.22 Case convert - using if - else if - else

#include <iostream.h>

void main()

{

char ch1, ch2;

cout << "Enter a single alphabet ";

cin >> ch1;

if (ch1 >= 'A' && ch1 <= 'Z') //if Capital

ch2 = (char) (ch1 + 32);

else if (ch1 >= 'a' && ch1 <= 'z') //if lowercase

ch2 = (char) (ch1 - 32);

else // if neither

ch2 = ch1; //no change

cout << ch2;

}

We could also use the ternary operator to replace the conditions thus:

//program-3.22 Case convert - using if - else if - else

#include <iostream.h>

void main()

{

char ch1, ch2;

cout << "Enter a single alphabet ";

cin >> ch1;

ch2 = ch1 >= 'A' && ch1 <= 'Z'? (ch1 + 32) :

(ch1 >= 'a' && ch1 <= 'z' ? (ch1 - 32) : ch1);

cout << ch2;

}

 

Output:

Enter a single character A //entered by user

a

Enter a single character f

//entered by user

F

Enter a single character #

//entered by user

#

 

 

The same program may be written using a library function called toupper(), tolower(), isupper(), islower(), isalpha() and they require inclusion of the header file ctype.h as shown below.

 

#include <iostream.h>

#include <ctype.h>

void main()

{

char ch;

cout << "Enter any letter ";

cin >> ch;

if (! isalpha(ch) ) //check if alphaber

cout << "It is not an alphabet";

else

{

if (isupper (ch) ) //check if capital

cout << (char) tolower(ch); //convert to lowercase, typecast

if (islower (ch) ) //check if lowercase

cout << (char) toupper (ch); //change case, typecast

} //end of if block

} //end of main()

 

 

Output:

Enter a single character A //entered by user

a

Enter a single character f

//entered by user

F

Enter a single character #

//entered by user

It is not an alphabet

 

 

cout << (a * b);

break; //exit the switch block

case 4: //if switch variable matches '/'

cout << (a / b);

break; //exit the switch block

default: //if no match is found

cout << "Error";

} //close of switch block

} //end of main()

 

Output:

-4.11

 

ITERATIONS

When a single instruction or a set of instructions is to be performed repeatedly, subject to some preset condition(s), it is called a loop or iteration.

 

The for loop

: The syntax consists of initial value of a variable, its final (exit) value, and how the variable will be incremented or decremented.

 

 

 

 

 

 

//program-3.12 To illustrate a for loop

#include <iostream.h>

void main()

{

int num, count;

for(count = 1; count <= 10; count++) //no semi-colon

{ // braces to include block

num = count * 2; //body of loop

cout << num << ", ";

} //end of loop

 

} //end of main()

 

Output:

2, 4, 6, 8, 10, 12, 14, 16, 18, 20

The parenthesis after for consists of 3 elements separated by semi-colons. Here, for example,

 

the first element is initialization of the variable

count (count = 0;)

the second is the condition for the loop to continue (so long

as count <= 10;

)

the third is how the count changes

(count++;)

 

Thus the minimum for a loop to be technically correct is

for(… ;… ;)

When there are more than one variables they are comma separated thus:

 

for(i=0, j=5; i<6 || j>10; i++, j--)

As in case of if, braces are not needed if there is only a single statement under a loop.

 

What is the difference between the following code segments?

 

(i) for(a=0; a<4; a++)

cout << "Hello!"; // no braces or block

cout << "Thank you"; //not under loop

 

(ii) for(a=0; a<4;a++)

{

cout << "Hello! "; // block within braces

cout << "Thank you"; //all under loop

}

 

The first one prints "Hello!" many times, but "Thank you" only once. Only the first statement is under loop.

 

The second one prints both "Hello!" and "Thank you" repeatedly, as both form a block under the loop.

 

We print the odd and even numbers thus:

 

#include <iostream.h>

void main()

{

int i;

for (i = 1; i <= 10; i += 2) //i += 2 means i = i + 2

cout << i << '\t'; //a tab for a space

cout << endl; //new line

for (i = 2; i <= 10; i += 2)

cout << i << '\t';

cout << endl;

}

 

Output:

 

1 3 5 7 9

2 4 6 8 10

The following program prints the factorial of any positive integer (not zero).

 

//program-3.13 To illustrate a for loop--factorial

#include <iostream.h>

void main()

{

int prod = 1; //initialize

int num = 5; //(1)

int cnt; //declare variables

for(cnt = 1; cnt <= num; cnt++)

prod *= cnt; //only one statement under loop

cout <<"Factorial is " << prod;

}

 

Output:

Factorial is 120

Rewrite the above code replacing line (1) above with

cin >> num

;

 

The while loop

 

: The loop continues while (or so long as) the condition stated in parentheses after while is true. We shall rewrite the above program using a while loop.

 

//program-3.14 To illustrate a while loop--factorial

#include <iostream.h>

void main()

{

int prod = 1, cnt = 1, num = 5; //initializations

while (cnt <= num) //no semi-colon

{ //braces for multiple statements

prod *= cnt;

cnt++; //increment of cnt inside body

} // end of while loop

cout << "Factorial is " << prod;

}

 

Output:

Factorial is 120

The increment could have been done along with the statement

prod *= cnt;

and the program would stand thus:

 

#include <iostream.h>

void main()

{

int prod = 1, cnt = 1, num = 5; //initializations

while (cnt <= num) //no semi-colon
prod *= cnt++; //post increment

cout << "Factorial is " << prod;

}

 

The do while loop

:

The loop is introduced by the key word do, followed by opening brace which contains the block of statements; after the closing brace the while condition is specified. Thus the first iteration is unconditional, the stipulations are checked at the end of the block for continuation or exit.

 

 

We shall rewrite the factorial program using do while loop.

 

//program-3.15 Factorial using do - while loop

#include <iostream.h>

void main()

{

int prod = 1, cnt = 1, num = 5;

do //no condition for first iteration

{

prod *= cnt;

cnt++; //increment of cnt inside body

} while (cnt <= num); //condition at end of loop

//for 2nd and all

//subsequent iteration

cout <<"Factorial is " << prod;

}

 

 

Output:

Factorial is 120

 

Here also we could have incremented

cnt along with the statement prod *= cnt;

and written the code