0% found this document useful (0 votes)
22 views19 pages

Chapter 4

Chapter Four of the document discusses the fundamental building blocks of C++ programs, specifically focusing on statements, which are essential for controlling program flow and executing actions. It categorizes statements into simple, compound, selection, iterative, and jump statements, explaining their structures and uses with examples. The chapter emphasizes the importance of flow control and the syntax rules, such as the requirement for statements to end with a semicolon.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views19 pages

Chapter 4

Chapter Four of the document discusses the fundamental building blocks of C++ programs, specifically focusing on statements, which are essential for controlling program flow and executing actions. It categorizes statements into simple, compound, selection, iterative, and jump statements, explaining their structures and uses with examples. The chapter emphasizes the importance of flow control and the syntax rules, such as the requirement for statements to end with a semicolon.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Adama Science & Technology University SEng 1021

Chapter Four
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).

A statement causes an action to be performed. In C++, a statement controls the sequence of


execution, evaluates an expression, or does nothing (the null statement). The basic structure of
any program can be represented like this:

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:
Statements are divided into:
1) Simple statement
2) Compound Statement
3) Selection Statement
4) Iterative / Loop Statement
5) Jump Statement

1. Simple statement
1|Page cc
Adama Science & Technology University SEng 1021

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.

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/Branching Statement
As in most programming languages, C++ handles flow of control with branching and looping
statements. C++ branching and looping statements are similar to branching and looping
statements in other languages. They are the same as in the C language and very similar to what
they are in the Java programming language.
2|Page cc
Adama Science & Technology University SEng 1021

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.

3.1 Two-way selection


It is sometimes desirable to make the execution of a statement dependent upon a condition being
satisfied. The if statement provides a way of expressing this, the
general form of which is:
if (expression)
statement;
First expression is evaluated. If the outcome is nonzero then statement is executed. Otherwise,
nothing happens. For example, when dividing two values, we may want to check that the
denominator is nonzero:
if (count != 0)
average = sum / count;

To make multiple statements dependent on the same condition, we can use a


compound statement:
if (balance > 0)
{
interest = balance * creditRate;
balance += interest;
}

 A variant form of the if statement allows us to specify two alternative statements: one
which is executed if a condition is satisfied and one which is executed if the condition is
not satisfied. This is called the if-else statement and has the general form:
if (expression)
statement1;
else
statement2;
 First expression is evaluated. If the outcome is nonzero then statement1 is executed.
Otherwise, statement2 is executed.
For example:

3|Page cc
Adama Science & Technology University SEng 1021

if (balance > 0)
{interest = balance * creditRate;
balance += interest;
}
else
{interest = balance * debitRate;
balance += interest;
}

E.g. 1 #include <iostream.h>


void main ()
{
int x;
cout << "Please guess a number I have inmind from 1-10:";
cin >> x;
if (x > 10)
cout << "That number is too big!" << endl;
if (x < 1)
cout << "That number is too small!" << endl;
if (x != 5)
cout << "You didn't get the right number!" << endl;
if (x==5)
cout << "You’ve got the right number!" << endl;
cout << "Thank you and goodbye!" << endl;
}

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: Statements may be nested by having an if statement appear inside another if statement. For
example:

4|Page cc
Adama Science & Technology University SEng 1021

if (callHour > 6)
{
if (callDuration <= 5)
charge = callDuration * tarrif1;
else
charge = 5 * tarrif1+(callDuration - 5)*tarrif2;
}
else
charge = flatFee;

 A frequently-used form of nested if statements involves the else part consisting of


another if-else statement like:

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";

5|Page cc
Adama Science & Technology University SEng 1021

else if (ch >= 'a' && ch <= 'z')

cout<<"the character "<<ch<<"Small letter letter";


else

cout<<"the character "<<ch<<"It is a special character";

3.2 Multiple-way Selection


The switch statement provides a way of choosing between a set of alternatives, based on the
value of an expression. The general form of the switch statement is:
switch (expression)
{
case constant 1:
statements;
.....
case constant n:
statements;
default:
statements;
}
 First expression (called the switch tag) is evaluated, and the outcome is compared to each
of the numeric constants (called case labels), in the order they appear, until a match is
found. The statements following the matching case are then executed. Note the plural:
each case may be followed by zero or more statements (not just one statement).
Execution continues until either a break statement is encountered or all intervening
statements until the end of the switch statement are 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;

6|Page cc
Adama Science & Technology University SEng 1021

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

7|Page cc
Adama Science & Technology University SEng 1021

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 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).

4. Iterative / Loops Statements


A loop is a way of repeating a series of instructions several times. The loop is set up either to
repeat a certain number of times or to go round and round until some condition is met. Either way
there should be some condition that makes the loop terminate.
The loop can be arranged in one of three ways:
 for statement
 while statement
 do…while statement

4.1 The for loop


This is the simplest and straight-forward looping construct that has the following general look:
for(expression1;expression2;expression3)

 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.

//calculates the sum of numbers 1 through n


void main()
{
int sum = 0,n;
cout<<"Enter the maximum number"<<endl;
cin>>n;
for (int i = 1; i <= n; ++i)
sum += i;

8|Page cc
Adama Science & Technology University SEng 1021

cout<<"the sum of numbers from 1 to <<n<<"is =:"<<sum;


}

The control of the loop statement is depicted below:

Test NO

exprs exit
n

Yes

Loop body

E.g. 1 #include<iostream.h>//displays the squares of the numbers [1,20]


#include <iomanip.h> // for setw( ),
void main ( )
{
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. 2 #include <iostream.h>


void main ()
{
int x, limit, sum;
cout << "Please enter a number bigger than 1 : ";
cin >> limit;
sum = 0;
for (x = 1; x <= limit; x++)
{
cout << "I am adding " << x << endl;
sum = sum + x;
}
cout << endl;
cout << "The sum of all the numbers from 1 to ";
9|Page cc
Adama Science & Technology University SEng 1021

cout << limit << " is " << sum;


return;
}

4.2 The while statement


The while statement (also called the while loop) provides a way of repeating a statement while a
condition holds.
Syntax: while (expression)
Statements;

 First expression (called the loop condition) is evaluated. If the


outcome is nonzero then statement (called the loop body) is executed
and the whole process is repeated. Otherwise, the loop is terminated.
//the 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;
while (i <= n)
sum += i++;
cout<<"the sum of numbers from 1 to <<n<<"is =:"<<sum;
}

E.g. 1
//a program to display numbers from 100 to 1 return;
#include<iostream.h> } //end of main prog
#include <iomanip.h>
void main ( )
{
int x = 100;
E.g 2
while (x>=1)
// An example of a while loop
{
#include <iostream.h>
cout<< setw(4)<<x<<endl;
void main ()
x--;
{ int number;
} //end of while loop

10 | P a g e c c
Adama Science & Technology University SEng 1021

cout << "Please type a number cout << "No, bigger than 10!
bigger than 10 : "; Try again: ";
cin >> number; 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++;
cout<<"the sum of numbers from 1 to <<n<<"is =:"<<sum;
}

The control of the do…while loop statement is shown below:

Loop body

11 | P a g e c c
Condition
? exit
Adama Science & Technology University SEng 1021

false

true

E.g.1 //the following program displays “Hello’’ until one presses ‘N’
#include<iostream.h>
#include<conio.h>
void main ()
{
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,
12 | P a g e c c
Adama Science & Technology University SEng 1021

// 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;
}

4.4 Nested loop statements

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.

//this prog demonstrates the nesting of loop statements

#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) << " ? : ";
do
{ cin >> answer;
13 | P a g e c c
Adama Science & Technology University SEng 1021

if (answer == 2*x + 30 - x)
cout << "Correct!" << endl;
else
cout << "No, try again!" <<
endl;
}
while (answer != 2*x + 30 - x);
}
}

4. 5 Jump statements

4.5.1 Break statement


This statement causes an exit from a loop or decision block. It takes the control from the inner
block to the outer (out of the following closing brace). In switch statement it is used to exit from
the switch statement. A break statement only applies to the loop or switch immediately enclosing
it. It is an error to use the break statement outside a loop or a switch.

E.g. /* this prog 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

14 | P a g e c c
Adama Science & Technology University SEng 1021

cout<<"\nContinue [Y/N] ";


cin>>ch;
if (ch = = 'N')
break; // exit out of loop.
}
cout<<"Thanks";
getch();
}

4.5.2 The continue statement


The continue statement terminates the current iteration of a loop and instead jumps to the next
iteration. It applies, just like the break statement, to the loop immediately enclosing the continue
statement. In while and do loops, the next iteration commences from the loop condition. In a for
loop, the next iteration commences from the loop’s third expression.

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(); }

4.5.3 The goto statement


The goto statement provides the lowest-level of jumping. It has the general
form:

goto label;

15 | P a g e c c
Adama Science & Technology University SEng 1021

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 altogether in favor of clear programming.

for (i = 0; i < attempts; ++i) {


cout << "Please enter your password: ";
cin >> password;
if (Verify(password)) // check password for correctness
goto out; // drop out of the loop
cout << "Incorrect!\n";
}
out:
//etc...

4.5.4 The return statement


The return statement enables a function to return a value to its caller. It has
the general form:

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:
 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:

16 | P a g e c c
Adama Science & Technology University SEng 1021

int main (void)


{ cout << "Hello World\n";
return 0;
}

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:

Underweight: weight < height/2.5


Normal: height/2.5 <= weight <= height/2.3
Overweight: height/2.3 < weight
2. Write a program which inputs a date in the format dd/mm/yy and
outputs it in the format month dd, year.
For example, 25/12/61 becomes: December 25, 1961

3. Write a program which produces a simple multiplication table of the


following format for integers in the range 1 to 9:

1x1=1
1x2=2
...
9 x 9 = 81

4. Write a program which inputs an integer value, checks that it is


positive, and 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.

17 | P a g e c c
Adama Science & Technology University SEng 1021

[Link] 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";

[Link] a C++ program for the following flowchart. N.B Let the user enter the initial value
of X and Y, finaly your program should return the value of X, Y and Z.

[Link] 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;
18 | P a g e c c
Adama Science & Technology University SEng 1021

x = 1;
}

10. 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.
11. 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

12. 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
N.B write the program using both switch and else-if.

19 | P a g e c c

You might also like