|
|
Summary
o Do-While Statement
o Example
o for Statement
o Sample Program 1
o Increment/decrement Operators
o Sample Program 2
o Tips
Do-While Statement
We have seen that there may be certain situations when the body of
while loop does not
execute even a single time. This occurs when the condition in
while is false. In
while
loop, the condition is tested first and the statements in the body are executed
only when
this condition is true. If the condition is false, then the control goes directly
to the
statement after the closed brace of the
while loop. So we can say
that in while structure,
the loop can execute zero or more times. There may be situations where we may need
that some task must be performed at least once.
For example, a computer program has a character stored from a-z. It gives to user
five chances or tries to guess the character. In this case, the task of guessing
the character
Page 56
must be performed at least once. To ensure that a block of statements is executed
at least
once, C provides a do-while
structure. The syntax of
do-while structure is as
under:
do
{
statement(s);
}
while ( condition ) ;
Here we see that the condition is tested after executing the statements of the loop
body.
Thus, the loop body is executed at least once and then the condition in
do while statement
is tested. If it is true, the execution of the loop body is repeated. In case, it
proves
otherwise (i.e. false), then the control goes to the statement next to the
do while
statement. This structure describes ‘execute the statements enclosed
in braces in do
clause' when the condition in
while clause is true.
Broadly speaking, in while
loop, the condition is tested at the beginning of the loop
before the body of the loop is performed. Whereas in
do-while loop, the condition
is
tested after the loop body is performed.
Therefore, in do-while
loop, the body of the loop is executed at least once.
The flow chart of do-while structure is as follow:
Example
Let’s consider the example of guessing a character. We have a character in the program
to be guessed by the user. Let’s call it ‘z’. The program allows five tries (chances)
to the
user to guess the character. We declare a variable tryNum to
store the number of tries.
The program prompts the user to enter a character for guessing. We store this character
in
a variable c.
Page 57
We declare the variable c of type
char. The data type
char is used to
store a single
character. We assign a character to a variable of
char type by putting the
character in
single quotes. Thus the assignment statement to assign a value to a
char variable will be
as c = ‘a’. Note that there should be a single character in
single quotes. The statement like
c = ‘gh’ will be a syntax error.
Here we use the do-while
construct. In the
do clause we prompt the user to enter a
character.
After getting character in variable c from user, we compare
it with our character i.e ‘z’.
We use if\else structure
for this comparison. If the character is the same as ours then we
display a message to congratulate the user else we add 1 to tryNum
variable. And then in
while clause, we test the condition whether tryNum
is less than or equal to 5 (tryNum
<=
5). If this condition is true, then the body of the
do clause is repeated again.
We do this
only when the condition (tryNum
<= 5) remains true. If it is otherwise, the control goes
to the first statement after the
do-while loop.
If guess is matched in first or second try, then we should exit the loop. We know
that the
loop is terminated when the condition
tryNum <= 5 becomes false,
so we assign a value
which is greater than 5 to tryNum after displaying the message.
Now the condition in the
while statement is checked. It proves false (as tryNum is greater than
5). So the control
goes out of the loop. First look here the flow chart for the program.
The code of the program is given below.
//This program allows the user to guess a character from a to z
//do-while construct is used to allow five tries for guessing
# include <iostream.h>
Page 58
main ( )
{
//declare & initialize variables
int tryNum = 0 ;
char c ;
// do-while construct
do
{
cout << “Please enter a character between a-z for guessing : “ ;
cin >> c ;
//check the entered character for equality
if ( c == ‘z’)
{
cout << “Congratulations, Your guess is correct” ;
tryNum = 6;
}
else
{
tryNum = tryNum + 1;
}
}
while ( tryNum <= 5);
}
There is an elegant way to exit the loop when the correct number is guessed. We
change
the condition in while
statement to a compound condition. This condition will check
whether the number of tries is less than or equal to 5 and the variable
c is not equal to ‘z’.
So we will write the while
clause as while
(tryNum <= 5 && c != ‘z’ ); Thus when a
single condition in this compound condition becomes false, then the control will
exit the
loop. Thus we need not to assign a value greater than 5 to variable tryNum.
Thus the
code of the program will be as:
//This program allows the user to guess a character from a to z
//do-while construct is used to allow five tries for guessing
# include <iostream.h>
main ( )
{
//declare & initialize variables
int tryNum = 0 ;
char c ;
Page 59
// do-while construct, prompt the user to guess a number and compares it
do
{
cout << “Please enter a character between a-z for guessing : “ ;
cin >> c ;
//check the entered character for equality
if ( c == ‘z’)
{
cout << “Congratulations, Your guess is correct” ;
}
else
{
tryNum = tryNum + 1;
}
}
while ( tryNum <= 5 && c != ‘z’ );
}
The output of the program is given below.
Please enter a character between a-z for guessing : g
Please enter a character between a-z for guessing : z
Congratulations, Your guess is correct
for Loop
Let’s see what we do in a loop. In a loop, we initialize variable(s) at first. Then
we set a
condition for the continuation/termination of the loop. To meet the condition to
terminate
the loop, we affect the condition in the body of the loop. If there is a variable
in the
condition, the value of that variable is changed within the body of the loop. If
the value of
the variable is not changed, then the condition of termination of the loop will
not meet
and loop will become an infinite one. So there are three things in a loop structure
i.e. (i)
initialization, (ii) a continuation/termination condition and (iii) changing the
value of the
condition variable, usually the increment of the variable value.
To implement these things, C provides a loop structure known as
for loop. This is the
most often used structure to perform repetition tasks for a known number of repetitions.
The syntax of for loop
is given below.
for ( initialization condition ; continuation condition ; incrementing condition
)
{
statement(s) ;
}
Page 60
We see that a 'for statement'
consists of three parts. In initialization condition, we
initialize some variable while in continuation condition, we set a condition for
the
continuation of the loop. In third part, we increment the value of the variable
for which
the termination condition is set.
Let's suppose, we have a variable counter of type
int. We write
for loop in our
program
as
for ( counter = 0 ; counter < 10 ; counter = counter +1 )
{
cout << counter << endl;
}
This 'for loop'
will print on the screen 0, 1, 2 …. 9 on separate lines (as we use
endl in our
cout statement). In
for loop, at first, we
initialize the variable counter
to 0. And in the
termination condition, we write
counter < 10. This means
that the loop will continue till
value of counter is less than 10. In other words, the loop will terminate when the
value of
counter is equal to or greater than 10. In the third part of
for statement, we write
counter
= counter + 1 this means that we add 1 to the existing value of
counter. We call
it
incrementing the variable.
Now let's see how this loop executes. When the control goes to
for statement first time,
it
sets the value of variable counter to 0, tests the condition (i.e.
counter < 10). If it is
true,
then executes the body of the loop. In this case, it displays the value of
counter which is
0
for the first execution. Then it runs the incrementing statement (i.e. counter =
counter + 1
). Thus the value of counter becomes 1. Now, the control goes to
for statement and tests
the condition of continuation. If it is true, then the body of the loop is again
executed
which displays 1 on the screen. The increment statement is again executed and control
goes to for statement.
The same tasks are repeated. When the value of counter becomes
10, the condition counter <
10 becomes false. Then the loop is terminated and control
goes out of for
loop.
The point to be noted is that, the increment statement (third part of
for statement) is
executed after executing the body of the loop. Thus
for structure is equivalent
to a while
structure, in which, we write explicit statement to change (increment/decrement)
the
value of the condition variable after the last statement of the body. The
for loop does this
itself according to the increment statement in the
for structure. There may
be a situation
where the body of for
loop, like while
loop, may not be executed even a single time. This
may happen if the initialization value of the variable makes the condition false.
The
statement in the following for loop will not be executed even a single time as during
first
checking, the condition becomes false. So the loop terminates without executing
the body
of the loop.
for ( counter = 5 ; counter < 5 ; counter ++)
{
cout << “The value of counter is “ << counter ;
}
Page 61
Sample Program 1
Let’s take an example to explain
for loop. We want to write
a program that prints the
table of 2 on the screen.
In this program, we declare a variable counter of type
int. We use this variable to
multiply it by 2 with values 1 to 10. For writing the table of 2, we multiply 2
by 1, 2, 3 ..
upto 10 respectively and each time display the result on screen. So we use
for loop to
perform the repeated multiplication.
Following is the code of the program that prints the table of 2.
//This program display the table of 2 up to multiplier 10
# include <iostream.h>
main ( )
{
int counter;
//the for loop
for ( counter = 1 ; counter <= 10 ; counter = counter + 1)
{
cout << “2 x “ << counter << “ = “ << 2 * counter << “\n” ;
}
}
This is a simple program. In the
for statement, we initialize
the variable counter to 1 as
we want the multiplication of 2 starting from 1. In the condition clause, we set
the
condition counter <= 10
as we want to repeat the loop for 10 times. And in the
incrementing clause, we increment the variable counter by 1.
In the body of the for loop,
we write a single statement with
cout. This single statement
involves different tasks. The portion ‘<<
“2 x “’ displays the string “2 x “ on the screen.
After this, the next part ‘<<
counter’ will print the value of counter. The ‘<<
“ = ”’ will
display ‘ = ‘ and then the next part ‘<<
2 * counter’ will display the result of 2 multiply
by counter and the
last <<”\n” ( the
new line character) will start a new line. Thus in the
first iteration where the value of counter is 1, the
cout statement will display
the
following line
2 x 1 = 2
After the execution of cout
statement, the for
statement will increment the counter
variable by 1. Thus value of counter will be 2. Then condition will be checked which
is
still true. Thus the body of for loop (here the
cout statement) will be
executed again
having the value of counter 2. So the following line will be printed.
2 x 2 = 4
Page 62
The same action will be repeated 10 times with values of counter from 1 to 10. When
the
value of counter is 11, the condition (
counter <= 10 ) will become
false and the loop
will terminate.
The output of the above program is as the following.
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Now what will we do, if some one says us to write a table of 3, or 4 or 8 or any
other
number. Here comes the point of re-usability and that a program should be generic.
We
write a program in which a variable is used instead of a hard code number. We prompt
the user to enter the number for which he wants a table. We store this number in
the
variable and then use it to write a table. So in our previous example, we now use
a
variable say number where we were using 2. We also can allow
the user to enter the
number of multipliers up to which he wants a table. For this, we use a variable
maxMultiplier and execute the loop for maxMultiplier
times by putting the condition
counter <= maxMultiplier. Thus our program becomes generic which can
display a table
for any number and up to any multiplier.
Thus, the code of our program will be as below:
//This program takes an integer input from user and displays its table
//The table is displayed up to the multiplier entered by the user
# include <iostream.h>
main ( )
{
int counter, number, maxMultiplier ;
// Prompt the user for input
cout << “Please enter the number for which you want a table : “ ;
cin >> number ;
cout << “Please enter the multiplier up to which you want a table : “ ;
cin >> maxMultiplier ;
Page 63
//the for loop
for ( counter = 1 ; counter <= maxMultiplier ; counter = counter + 1)
{
cout << number << “ x “ << counter << “ = “ << number * counter << “\n” ;
}
}
The output of the program is shown as follows:
Please enter the number for which you want a table : 7
Please enter the multiplier up to which you want a table : 8
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
Here is a guideline for programming style. We should avoid using constant values
in our
calculations or in long routines. The disadvantage of this is that if we want to
change that
constant value later, then we have to change every occurrence of that value in the
program. Thus we have to do a lot of work and there may be some places in code where
we do not change that value. To avoid such situations, we can use a variable at
the start
and assign that constant value to it and then in the program use that variable.
Thus, if we
need to change the constant value, we can assign the new value to that variable
and the
remaining code will remain the same. So in our program where we wrote the table
of 2,
we can use a variable (say number) and assign it the value 2. And in
cout statement we
use this variable instead of constant 2. If we want that the program should display
a table
of 5, then we just change the value of the variable. So for good programming, use
variables for constant values instead of explicit constant values.
Increment Decrement Operators
We have seen that in while, do-while and for loop we write a statement to increase
the
value of a variable. For example, we used the statements like
counter = counter + 1;
which adds 1 to the variable
counter. This increment statement is so common that it is
used almost in every repetition structure (i.e. in while, do-while and for loop).
The C
Page 64
language provides a unary operator that increases the value of its operator by 1.
This
operator is called increment operator and sign ++ is used for this. The statement
counter
= counter + 1; can be replaced with the statement
counter ++ ;
The statement counter++
adds 1 to the variable counter. Similarly the expressions
i = i +
1 ; and j = j + 1 ; are equivalent to i++ ; and j++;
respectively. There is also an operator
-- called decrement operator. This operator decrements, the value
of its operand by 1. So
the statements counter = counter
- 1; and j = j -
1; are equivalent to counter--; and j--;
respectively.
The increment operator is further categorized as pre-increment and post-increment.
Similarly, the decrement operator, as pre-decrement and post-decrement.
In pre-increment, we write the sign before the operand like ++j
while in post-increment,
the sign ++ is used after the operand like j++. If we are using
only variable increment,
pre or post increment does not matter. In this case, j++ is
equivalent to ++j. The
difference of pre and post increment matters when the variable is used in an expression
where it is evaluated to assign a value to another variable. If we use pre-increment
( ++j ),
the value of j is first increased by 1. This new value is used
in the expression. If we use
post increment ( j++ ),the value of j is used in the expression. After that it is
increased by
1. Same is the case in pre and post decrement.
If j = 5, and we write the expression
x = ++ j ;
After the evaluation of this expression, the value of x will be 6 (as j is incremented
first
and then is assigned to x). The value of j will also be 6 as
++ operator increments it by 1.
If j = 5, and we write the expression
x = j++ ;
Then after the evaluation of the expression, the value of x will be 5 (as the value
of j is
used before increment) and the value of j will be 6.
The same phenomenon is true for the decrement operator with the difference that
it
decreases the value by 1. The increment and decrement operators affect the variable
and
update it to the new incremented or decremented value.
The operators ++ and -- are used to increment or decrement the variable by 1. There
may
be cases when we are incrementing or decrementing the value of a variable by a number
other than 1. For example, we write
counter = counter + 5;
or j = j – 4;. Such
assignments are very common in loops, so C provides operators to perform this task
in
short. These operators do two things they perform an action (addition, subtraction
etc)
and do some assignment.
These operators are +=, -=, *=, /= and %=. These operators are compound assignment
operators. These operators assign a value to the left hand variable after performing
an
action (i.e. +, -, *, / and %). The use of these operators is explained by the following
examples.
Page 65
Let’s say we have an expression,
counter = counter + 5;.
The equivalent of this
expression is counter += 5;.
The statement counter += 5;
does two tasks. At first, it adds
5 to the value of counter and then assigns this result to
counter. Similarly the following
expressions
x = x + 4 ;
x = x - 3 ;
x = x * 2 ;
x = x / 2 ;
x = x % 3;
can be written in equivalent short statements using the operators ( +=, -=, *=,
/=, %= ) as
follows
x += 4 ;
x -= 3 ;
x *= 2;
x /= 2;
x %= 3 ;
Note that there is no space between these operators. These are treated as single
signs. Be
careful about the operator %=. This operator assigns the remainder to the variable.
These
operators are alternate in short hand for an assignment statement. The use of these
operators is not necessary. A programmer may use these or not. It is a matter of
style.
Example Program 2
Let’s write a program using
for loop to find the sum of the squares of the integers from 1
to n. Where n is a positive value entered by the user (i.e. Sum = 12
+ 22 + 32 + ……+ n2)
The code of the program is given below:
//This program displays the sum of squares of integers from 1 to n
# include <iostream.h>
main ( )
{
//declare and initialize variables
int i, n, sum;
sum = 0 ;
//get input from user and construct a for loop
cout << “Please enter a positive number for sum of squares: ” ;
cin >> n;
for ( i = 1 ; i <= n ; i ++)
Page 66
{
sum += i * i ;
}
cout << “The sum of the first ” << n << “ squares is “ << sum << endl ;
}
In the program declared three variables i, n
and sum. We prompted the user to enter a
positive number. We stored this number in the variable n. Then
we wrote a for loop.
In
the initialization part, we initialized variable i with value
1 to start the counting from 1. In
the condition statement we set the condition i less than or
equal to n (number entered by
the user) as we want to execute the loop n times. In the increment
statement, we
incremented the counter variable by 1. In the body of the for
loop we wrote a single
statement sum += i * i
;. This statement takes the square of the counter variable ( i )and
adds it to the variable sum. This statement is equivalent to
the statement sum = sum + (
i
* i ) ; Thus in each iteration the square of the counter variable (which
is increased by 1 in
each iteration ) is added to the sum. Thus loop runs
n times and the squares of numbers
from 1 to n are summed up. After completing the
for loop the
cout statement is executed
which displays the sum of the squares of number from 1 to n.
Following is the output when the number 5 is entered.
Please enter a positive number for sum of squares: 5
The sum of the first 5 squares is 55
Tips
• Comments should be meaningful, explaining the task
• Don’t forget to affect the value of loop variable in
while and
do-while
loops
• Make sure that the loop is not an infinite loop
• Don’t affect the value of loop variable in the body of
for loop, the
for loop
does this by itself in the
for statement
• Use pre and post increment/decrement operators cautiously in expressions
|
|
|
|