Chapter Three: Statements
Chapter Three: Statements
CHAPTER THREE
STATEMENTS
Statements represent the lowest-level building blocks of a program. Each statement
represents a computational step which has a certain side-effect. (A side-effect can be
thought of as a change in the program state, such as the value of a variable changing
because of an assignment.) Statements are useful because of the side-effects they cause,
the combination of which enables the program to serve a specific purpose (e.g., sort a list
of names).
Begin
Statement
Statement
Statement
.....
End
A running program spends all of its time executing statements. The order in which
statements are executed is called flow control (or control flow). This term reflect the fact
that the currently executing statement has the control of the CPU, which when completed
will be handed over (flow) to another statement.
C++ insists that all statements end with a semicolon. The reason is that C++ is tolerant of
different layouts. If you chose to put several statements on one line, then the semicolons
would be the only way in which C++ would be able to separate them.
Like many procedural languages, C++ provides different forms of statements:
Simple Statement
Compound Statement
Statement Selection Statement
Iterative/Loop Statement
Jump Statement
1. Simple statement
A simple statement is a computation terminated by a semicolon. Variable definitions and
semicolon- terminated expressions are representatives of this category.
int i; //declaration statement
x++; // this has a side-effect
m+3; //useless statement b/c it has no side-effect; result is just discarded
The simplest statement is the null statement which consists of just a semicolon:
; // null statement
2. Compound statement
Compound statement is a unit of code consisting of zero or more statements; hence the
name compound. This consists of an opening brace, an optional declaration and definition
section, and an optional statement section, followed by a closing brace.
1
ASTU Department Of Computing
For example:
{ int min, i = 10, j = 20;
min = (i < j ? i : j);
cout << min << '\n';
}
Compound statements are useful in two ways:
(i) They allow us to put multiple statements in places where otherwise only
single statements are allowed, and
(ii) They allow us to introduce a new scope (part of the program text within which
a variable remains defined in the program) in the program. For example, the
scope of min, i, and j in the above example is from where they are defined
till the closing brace of the compound statement. Outside the compound
statement, these variables are not defined.
Notes: Because a compound statement may contain variable definitions and defines a
scope for them, it is also called a block.
A block does not need a semi colon.
3. Selection Statement
Selection statements are used for specifying alternate paths of execution, depending on
the outcome of a logical condition. It is sometimes desirable to make the execution of a
statement dependent upon a condition being satisfied. C++ provides such facilities. The
if statement enables you to test for a condition (such as whether two variables are equal)
and branch to different parts of your code, depending on the result. The modern
languages provide two selection constructs: two-way and multiple-way selections.
if (balance > 0)
{interest = balance * creditRate;
balance += interest;
}
else
{interest = balance * debitRate;
balance += interest;
}
E.g. 2 #include<iostream.h>
Void main()
{
cout << "Please type the number 8 : ";
cin >> x;
if (x == 8)
cout << "Thank you! I appreciate that." << endl;
else
{
cout << "Why can't you follow simple instructions?<< endl;
}
}
Note: If statements may be nested by having an if statement appear inside another if
statement. For example:
if (callHour > 6)
{
if (callDuration <= 5)
charge = callDuration * tarrif1;
else
charge = 5 * tarrif1+(callDuration - 5)*tarrif2;
}
else
charge = flatFee;
Void main()
{
Char ch;
Cout<<"Enter a character"<<endl;
Cin>>ch;
if (ch >= 0 && ch <= 9)
cout<<"the character "<<ch<<"is a number";
else
{
if (ch >= 'A' && ch <= 'Z')
cout<<"the character "<<ch<<"capital letter";
else
{
if (ch >= 'a' && ch <= 'z')
cout<<"the character "<<ch<<"Small letter letter";
else
cout<<"the character "<<ch<<"It is a special character";
}
}
}
For improved readability, it is conventional to format such cases as follows:
if (ch >= '0' && ch <= '9')
cout<<"the character "<<ch<<"is a number";
else if (cha >= 'A' && ch <= 'Z')
cout<<"the character "<<ch<<"capital letter";
else if (ch >= 'a' && ch <= 'z')
cout<<"the character "<<ch<<"Small letter letter";
else
cout<<"the character "<<ch<<"It is a special character";
4
ASTU Department Of Computing
executed. The final default case is optional and is exercised if none of the
earlier cases provide a match.
E.g.1 The following example prompts user to enter an operator and 2 operands and
generate the expression result with the selected operator on the operands.
void main()
{
int operand1, operand2;
char operator;
cout <<"enter two numbers"<<endl;
cin >> operand1>>operand2;
cout <<"enter one of the these operators ‘+’ , ’*’ , ‘/’ , ‘%’ "<<endl;
cin>> operator;
switch (operator)
{
case '+':
cout<<operand1 + operand2;
break;
case '-':
cout<<operand1 - operand2;
break;
case '*':
cout<<operand1 * operand2;
break;
case '/':
cout<<operand1 / operand2;
break;
default:
cout << "unknown operator: " << operator << ‘\n';
break;
}
}
It should be obvious that any switch statement can also be written as multiple else-if
statements. The above statement, for example, may be written as:
void main()
{
int operand1, operand2;
char operator;
double result;
cout <<" Enter two Integers "<<endl;
cin >> operand1>>operand2;
cout <<"Enter one of the arithmetic operators ‘+’ , ’*’ , ‘/’ , ‘%’ "<<endl;
cin>> operator;
if (operator == '+')
cout<<operand1 + operand2;
else if (operator == '-')
cout<< operand1 - operand2;
else if (operator == 'x' || operator == '*')
cout<< operand1 * operand2;
else if (operator == '/')
cout<< operand1 / operand2;
else
cout << "unknown operator: " << operator << '\n';
}
However, the switch version is arguably neater in this case. In general, preference should
be given to the switch version when possible. The if-else approach should be reserved for
5
ASTU Department Of Computing
situation where a switch cannot do the job (e.g., when the conditions involved are not
simple equality expressions, or when the case labels are not numeric constants).
First expression1 is evaluated. Each time round the loop, expression2 is evaluated. If
the outcome is nonzero then statement is executed and expression3 is evaluated.
Otherwise, the loop is terminated.
The most common use of for loops is for situations where a variable is
incremented or decremented with each iteration of the loop.
Test NO exit
exprsn
?
Yes
Loop body
6
ASTU Department Of Computing
int n;
for (n=1; n<=20;n++)
{ cout<<setw(4) <<n;
int sq = n*n;
cout<<setw (6) << sq<<endl;
} //end of loop
} // end of program.
E.g. 1
//a program to display numbers from 100 to 1 x--;
#include<iostream.h> } //end of while loop
#include <iomanip.h> return;
void main ( ) } //end of main prog
{
int x = 100;
while (x>=1)
{ E.g 2
cout<< setw(4)<<x<<endl; // An example of a while loop
7
ASTU Department Of Computing
#include <iostream.h> {
void main () cout << "No, bigger than 10!
{ int number; Try again: ";
cout << "Please type a number cin >> number;
bigger than 10 : "; }
cin >> number; }
while(number <= 10)
4.3 The do...while statement
The do statement (also called do loop) is similar to the while statement, except that its
body is executed first and then the loop condition is examined.
Syntax: do
statement;
while (expression);
First statement is executed and then expression is evaluated. If the outcome of the
latter is nonzero then the whole process is repeated. Otherwise, the loop is
terminated.
The do loop is less frequently used than the while loop. It is useful for situations
where we need the loop body to be executed at least once, regardless of the loop
condition.
//the DO while logic for summing numbers from 1 through n
void main()
{
int sum = 0,i=1,n;
cout<<"Enter the maximum number"<<endl;
cin>>n;
do
{
sum += i++;
}
While(i<=n);
cout<<"the sum of numbers from 1 to <<n<<"is =:"<<sum;
}
Loop body
true
E.g.1 //the following program displays “Hello’’ until one presses ‘N’
#include<iostream.h>
#include<conio.h>
void main ()
{
8
ASTU Department Of Computing
char ch;
do
{
cout<<"Hello!\n";
cout<<"Do you want to display more Hello's (Y/N) ";
cin >>ch;
} while (ch != 'N');
getch();
}
E.g. 2 /* this prog asks the user to type a number from 1 to 10 (inclusive) and
refuses to accept any number outside that range. */
#include <iostream.h>
void main ()
{
int my_number;
int valid; // 1 if the number is valid,
// 0 otherwise
cout << "Please enter a number from 1 to 10 : ";
do
{ cin >> my_number;
valid = 1; // by default
if (my_number < 1)
valid = 0;
if (my_number > 10)
valid = 0;
if (valid == 0)
cout << "I said from 1 to 10! Try again : ";
}
while (valid == 0);
cout << "Thank you." << endl;
}
We can stick/nest one loop statement inside another one. In such cases, the resulting loop
statement is called a nested loop statement. In principle, you can have as many loops
nested inside each other as you like.
#include <iostream.h>
void main ()
{ int x, answer;
for (x = 1; x <= 10; x++)
{ cout << "Question " << x << endl;
cout << "What is the answer to " << 2*x
<< " + " << (30 - x) << " ? : ";
9
ASTU Department Of Computing
do
{ cin >> answer;
if (answer == 2*x + 30 - x)
cout << "Correct!" << endl;
else
cout << "No, try again!" << endl;
}
while (answer != 2*x + 30 - x);
}
}
E.g. /* this program converts characters from small case to upper case if they
are written in small cases. The loop body will be prematurely terminated
by the break statement if ‘N’ is pressed,
*/
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main( )
{
char ch;
for( int i=1; i<=26;i++)
{
cout<<"Enter a character ";
cin>>ch;
char up=toupper(ch); // converts
character from
cout<<"upper case "<<up; // lower case
to upper one
cout<<"\nContinue [Y/N] ";
cin>>ch;
if (ch = = 'N')
break; // exit out of
loop.
}
cout<<"Thanks";
getch();}
10
ASTU Department Of Computing
E.g. //the following program displays even natural numbers below 100
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main ()
{
for (int i=1; i<=100; i++)
{
if (i%2!= 0)
continue;
else
cout<<setw(4)<<i<<endl;
}
getch(); }
goto label;
where label is an identifier which marks the jump destination of goto. The label should be
followed by a colon and appear before a statement within the same function as the goto
statement itself. But most programmers these days avoid using it all together in favor of
clear programming.
int attempts=3;
int password;
for (i = 0; i < attempts; ++i) {
cout << "Please enter your password: ";
cin >> password;
if ((password==123)) // check password for correctness
goto out; // drop out of the loop
cout << "Incorrect!\n";
}
out:
//etc...
return expression;
where expression denotes the value returned by the function. The type of this value
should match the return type of the function. For a function whose return type is void,
expression should be empty:
return;
Note:
11
ASTU Department Of Computing
The only function we have discussed so far is main, whose return type is
always int. The return value of main is what the program returns to the
operating system when it completes its execution.
For a function whose return type is void, expression should be empty:
Exercises
1. Write a program which inputs a person’s height (in centimetres) and weight (in
kilograms) and outputs one of the messages: underweight, normal, or overweight, using
the criteria:
4. Write a program which inputs an integer value, then whether it is positive or not.
If it is positive, then computes the factorial of the number, if not display “non
positive”. outputs its factorial, using the formulas:
factorial(0) = 1
factorial(n) = n × factorial(n-1)
5. Write a program that display numbers from 0 to 10 using three loops.
6. write for loop that will produce each of the following sequence
2, 4, 6, ….44
5, 7, 9,…...45
The sum of numbers between 2 to 44 inclusive
The sum of the first 20 numbers in the series 1, 4, 7, 10…
7. Re write the following code fragment using one switch statement
if (ch = = ‘E’|| ch= = ‘e’)
cout<<" this is either the value of ‘E’ or ‘e’";
else if (ch = = ‘A’|| ch= = ‘a’)
cout<<" this is either the value of ‘A’ or ‘a’";
else if (ch = = ‘r’|| ch= = ‘i’)
cout<<" this is either the value of ‘i’ or ‘r’";
else
cout<<" Enter the correct choice";
12
ASTU Department Of Computing
8. If the originally x=2, y=1 and z=1, what are the value of x, y, z after
executing the following code?
Switch(x)
{
case 0 : x = 2;
y =3;
case 1 : x =4;
Default:
y = 3;
x = 1;
}
9. If the variable divisor is not zero, divide the variable dividend by divisor, and
store the result in quotient. If divisor is zero, assign it to the quotient. Then print
all the variables. Assume the dividend and divisor are integer and quotient is a
double.
10. Write a program that create the following number patern.
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
11. Write a program that accepts student mark out of 100, and return the
corresponding letter grade based on the following condition:
if mark is greater than or equal to 90 A
if mark is greater than or equal to 80 and less than 90 B
if mark is greater than or equal to60 and less than 80 C
if mark is greater than or equal to 40 and less than 60 D
if mark is less than 40 F
for other cases NG
13