Professional Documents
Culture Documents
In C++, by default, statements are executed sequentially. In reality, however, not many
programs execute all their statements in strict order from beginning to end. Most programs
(like many humans) decide what to do in response to changing circumstances. They may do
one thing if some condition is met or another if not (decisions). They may also have to do a
certain action repeatedly (looping). Therefore, C++ defines a set of flow-of-control
statements that allow statements to be executed conditionally or repeatedly. (Remember the
discussion on Algorithms and Flowcharts)
How many times a loop is executed, or whether a decision results in the execution of a section
of code, depends on whether certain expressions are true or false. These expressions typically
involve relational and logical operators observed in Chapter 3.
A program may need to make a one-time decision which alters the sequential flow of execution
and causes a jump to another part of the program (branching). C++ provides us with the if
statement and the switch statement for these purposes.
The if Statement
An if statement has two forms: one with an else branch and one without. First let's see the
plain if (without the else branch).
Syntax:
if (condition) statement
The figure above shows two sample interactions with the program. As you can see, when
the user entered the value 12, the expression age<17 evaluated to true. This caused the first
output statement to be executed. When the user entered the value 56, the expression age<17
evaluated to false. This caused the first output statement to be jumped.
Example:
3. int main ()
4. {
5. int Val;
6. cout<<” Enter an integer value:> “;
7. cin>>Val;
8. if (val%2 == 0) //val%2 will be zero if val is divisible by two
9. {
10. int quotient = Val/2;
11. cout<<val<<” is divisible by 2” <<endl;
12. cout<<” The quotient is “<<quotient<<endl;
13. }
14. return 0;
15. }
In the above example, notice the condition val%2 == 0. First the modulus operator is used
to calculate the remainder of a division by two. Then this remainder is compared to 0 with
the equality operator. All the statements from line 10 to 12 will be executed if this condition
evaluates to true.
Note: Don't confuse the equality operator (==) with the assignment operator (=). The
compiler won't signal an error if you do. This will result in a very hard to find bug in your
program.
Exercises:
1. In the above example, add one line between lines 7 and 8, modify them as follows to
observe how the program mis-behaves.
7. cin>>val; new. int rem =
val%2; 8. if (rem = 0)
2. It is also a common mistake to forget the curly braces. See how the program behaves if
you remove the curly braces on lines 9 and 13.
It is usually the case that we want another statement to be executed if the condition evaluates
to false. The if statement allows for this kind of either or condition by providing the else
clause.
Syntax:
if (condition) statement1
else statement2
Here, the output statement on line 9 will be executed if age is less than 17. If not, the if...else
statement on lines 11 to 17 will be executed. Again, if the condition age<30 is fulfilled
(mind you, now we know age is greater than or equal to 17), the statement on line 12 is
executed. If not, the if...else statement on lines 14 to 17 will be executed. And so on. By
rearranging white spaces, we have the following, more convenient, form.
8. if (age < 17) //age is the element of [0, 17)
9. cout<<”You are too young\n”;
10. else if (age<40) //age is the element of [17, 40)
11. cout<<”Don't worry, you are still young\n”;
12. else if (age<70) //age is the element of [40, 70)
13. cout<<”Still young at heart\n”;
14. else //age is greater than or equal to 70
15. cout<<”Are you sure that is your age?\n”;
If age is less than 17, line 9 is executed. After line 9 is executed, lines 10 to 15 are jumped.
But if age is greater than or equal to 17, control jumps to line 10. And so on.
Although this is not a new syntax, let us formalize its usage Convenient
Form:
if (condition1) statement1
else if (condition2) statement2
...
else if (conditionN-1) statementN-1
else statementN
Exercises:
1. Develop a program that tells students their grade based on the following scale.
Mark>90 A 90 ≥ Mark > 85 A-
85 ≥ Mark > 82 B+ 82 ≥ Mark > 76 B
76 ≥ Mark > 70 C+ 70 ≥ Mark > 61 C
61 ≥ Mark > 50 C- 50 ≥ Mark > 43 D
Mark ≤ 43 F
Take Mark as an input from the user.
2. Develop a program that converts temperature from Celsius to Fahrenheit and vice versa
based on the user's preference.
(Hint: Display the following menu to the user)
Temperature Converter
1. for Celcius to Faranheit
2. for Fahrenheit to Celsius choice:>
The keyword switch is followed by the switch variable to test in parenthesis. This variable
should be an integer or character variable. Curly braces then delimit a number of case
statements. Each case keyword is followed by a constant, which is followed by a colon.
The data type of the case constants should match that of the switch variable. When the
value in the switch variable matches a constant in one of the case statements, the statement
immediately following the case will be executed until a break is reached.
The break keyword causes the entire switch statement to exit and control goes to the first
statement following the end of the switch construction. If the value of the switch variable
doesn't match any of the case constants, the statements immediately following the default
keyword will be executed. The default keyword is optional. If it is not present and no match
is found, control passes to the end of the switch without doing anything.
Example:
A program may also need to execute a group of statements more than once. C++ provides us
with the while, do while, and for statements for performing repetitive tasks.
The while loop is known as a pretest loop because it tests the condition before each iteration.
Notice that the variable ans is initialized to 0. If ans had been initialized to 42, the loop
would never have been executed. This is an important property of the while loop: the while
loop will never iterate if the test condition is false to start with.
Conversely, if the test condition never evaluates to false, the loop will never terminate.
This results in an infinite loop which will loop forever. For example, commenting out line
9 in the above example will make the loop an infinite one. Also note that a semicolon right
after the parentheses will be treated as a null statement and might generate an infinite loop.
Adding a semicolon at the end of line 6 will create an infinite loop. In this case, lines 7 to
10 are not treated as the body of the loop.
The do … while Loop Statement
There are cases where we may want to execute the body of the loop at least once before
testing the condition. In other words, there are times where we may need a posttest loop.
This is where the do … while loop comes in. Syntax:
do statement
while (condition);
Counters
Sometimes it is important to keep track of the number of iterations a loop makes. The
following example prints the square of the numbers from 1 to 10 using a while loop.
Example:
6. int num=1; //num initialized
7. cout<<setw(6)<<”Num.”<<setw(10)<<”Square”<<endl;
8. while (num<=10) //notice no semicolon here
9. {
10. cout<<setfill(' ')<<setw(6)<<num<<setw(10)
11. <<setfill('.')<<num*num<<endl;
12. num++; //num updated
13. }
Exercises:
1. Rewrite the above example program using a do … while loop and only one expression
statement inside the body of the loop.
2. Modify the programs you wrote for the exercises in Chapter 3 so that the user can
perform the tasks your programs do as many times as she wishes.
Here we have the for keyword followed by three expressions in parentheses, separated by
semicolons (notice the absence of a semicolon after the update expression). The
initialization expression is used to initialize or assign a starting value to a variable (usually
a counter). This is the first action performed by the loop and it is done only once. The
condition expression controls the loop just like the conditions in the while and do … while
loops – if it evaluates to true, the statement will be executed. Note that the for loop is a
pretest loop and checks the condition before each iteration. The update expression is
executed at the end of each iteration. It is usually used to modify the variable initialized
with the initialization expression (for example, increment a counter). Example:
5. cout<<setw(6)<<”Num.”<<setw(10)<<”Square”<<endl;
6. for (int num=1; num<=10; num++) //the for header
7. {
8. cout<<setfill(' ')<<setw(6)<<num<<setw(10)
9. <<setfill (‘.’) <<num*num<<endl;10. }
Note: The for header can omit any (or all) of the initialization, condition, and update
expressions. The initialization and update expressions can be made up of multiple
expressions separated by commas.
Examples:
int count=0;
for (count<10; count++) //no initialization cout<<” Counting: “<<count<<endl;
for (int i=0; ++i) //no condition: defaults to true – infinite loop
cout<<” i is: “<<i<<endl;
int ans=0;
for (ans! =42;) //no initialization and update
{
cout<<” What is the answer? :> “;
cin>>ans;
}
Exercise:
1. Analyze the following code segment.
int i, sum;
for (i=1, sum=0; i<100; i++, sum+=i);
cout<<sum<<endl;
2. Write a program that accepts a number from the user and calculates its factorial.
3. Write a program that averages numbers. The numbers are to be entered by the user and
their amount is not predetermined.
Nested Loops
Just like we did with if … else statements, it is also possible to put one loop inside another
loop. The first loop is called the outer loop and the one inside it is known as the inner loop.
You can nest your loops as much as you like. Example:
5. for (int i=0; i<10; i++) //outer loop header
6. {//beginning of outer loop
7. for (int j=0; j<5; j++) //inner loop header
8. {//beginning of inner loop
9. cout<<j<<'\t';
11. } //end of inner loop
12. cout<<”: “<<i<<endl;
13. } //end of outer loop
In this example, the outer loop is controlled by the i variable and the inner loop is controlled
by the j variable.
Nested loops are used when, for each iteration of the outer loop, something must be repeated
a number of times. For example, consider summing up the scores for each course for each
student.
Exercises:
1. Write a program (programs) that print the following triangle patterns. You can use only
for loops and use cout to output only one character at a time. Valid characters are '*', ' '
(space), and '\n'.
a) * b) * c) * **
** ***
*** *** *****
**** **** *******
***** ***** *********
2. Modify the above program to print the patterns for any number of rows the user desires.
3. Write a program that averages a set of test scores for a group of students. (Inputs are:
number of students, number of scores for each student, scores for each student)
• The break statement provides a way to bypass the loop condition and interrupt the loop
• In a nested loop, the break statement interrupts only the loop it is placed in.
The continue statement, placed inside a loop, causes the loop to stop its current iteration
and begin the next one. All statements in the body of the loop that come after it are ignored.
Example:
5. int n, count=0;
6. cout<<” Enter a number between 1 and 10 :> “;
7. cin>>n;
8. while (count++ < 10)
9. {
10. if (count==10)
11. continue;
12. cout<<” You did not enter “<<count<<endl;
13. }
Choosing a Loop
The while loop is ideal for situations where a pretest loop is required, i.e., if you don't want
to iterate if the condition is false from the beginning.
The do...while loop is ideal for situations where a posttest loop is required, i.e., if you want
the loop to iterate at least once even if the condition is false from the beginning.
The for loop is ideal for situations where a counter variable is needed.
Note: All loops are quite sufficient on their own for any task.
Example:
1. #include <iostream.h>
2. using namespace std;
4. int main () //the name main is now visible from this point on
5. {//open curly brace marks the beginning of a scope (scope 1). 6. int a = 10; // the name a is
now visible from this point 7. // on upto the end of the scope 1.
8. for (int i=0; i<5; i++)
9. {//open curly brace – beginning of scope 2
10. int a=5, b=10; //visible until the end of scope 2
11. cout<<a; //the new a is preferred(used)
12. } //close curly brace – end of scope 2
13. cout<<a<<endl; //here the new a is not visible
14. cout<<b<<endl; //b is not visible - error
15. return 0;
16. }
When using loops with multiple statements in their bodies, new scopes are introduced.
Scopes nest, i.e. all variables declared in an outer scope are visible in an inner scope.
Hence, in the above example, the variable a defined on line 6 is visible inside the scope
starting on line 9. However, when a new variable with the same name is defined in a new
scope on line 10, it overrides the previous definition. So within scope 2, the name a refers
to the variable defined on line 10.
The initialization expression inside the for loop header causes confusion. Where is the
variable i going to be visible? ANSI Standard C++ states that the variable i defined with the
initialization expression should only be visible within the body of the for loop (scope 2).
By this definition, the variable will only be visible from line 8 up to line 12. Some compilers
choose to ignore this restriction and the compiler that comes with Microsoft Visual Studio
6 is one of them. When developing programs with MS Visual Studio 6, the variable i will
be visible from its point of declaration (line 8) to the end of scope 1.
A function is a collection of statements that performs a specific task. A function performs some
computation and usually yields a result. A program may be broken into a set of manageable
functions, or modules. This is called modular programming. Real world programs can easily
have thousands of lines of code and unless they are modularized, they can be very difficult to
modify and maintain.
When creating a function, we write its definition. A definition has the following parts.
Name: a unique name for the function. Naming rules are the same as those for variables.
Parameter List: a list of variables that hold values being passed to the function.
Body: the set of statements that make up the function.
Return Type: the data type of the value being sent back from the function. Example:
1. int main ()
2. {
3. cout<<” Hello World! \n”;
4. return 0;
5. }
On line 1: int indicates the return type, main is the name of the function, and the parameter
list goes between the parentheses (currently empty). Line 1 is known as the function header.
Every statement within the curly braces is regarded as the function body. The last statement
within the function is usually a special statement that returns the value computed by the
function (line 4).
The main function is a special function because it gets executed automatically when the
program starts. All other functions are executed when they are called. These calls are made
by function call statements. You have written function call statements when using library
functions.
Example:
1. #include <iostream>
2. using namespace std;3.
4. void sayHello ()
5. {
6. cout<<” Hello from function! \n”;
7. }
8.
9. int main ()
10. {
11. cout<<” First Hello from main! \n”;
12. sayHello (); //a function call statement
13. cout<<” Back in main\n”;
14. return 0;
15. }
On line 12, we call the sayHello function. In this case, notice that the function call statement
is simply the function name followed by parentheses followed by a semicolon.
When the program is run, it starts executing from the main function. It goes on with normal
sequential program flow until the function call statement on line 12 is encountered. When
this happens, the program jumps to the called function on line 4 and starts executing it
sequentially. When it reaches the end of the function on line 7, it returns back to the main
function and continues executing from where it stopped, i.e. after the function call statement
(line 13).
Function calls can also be hierarchical. Function 1 calls Function 2 which may call a third
function and so on. Also note that the function name must be defined before it can be used.
In the example code above the name sayHello is visible in main because it is defined before
main.
As an example, let us modify the sayHello function defined in the previous example.
void sayHello (int times) //one parameter – times
{
for (int i=0; i<times; i++)
cout<<”Hello from function!\n”; }
Notice the variable definition inside the parentheses – times is the parameter. Inside the
function body, the parameter controls how many times the message is displayed. The
function can now accept an integer value as an argument which will be copied into times
when the function is called. The function call statement is now modified as:
sayHello (5);
where the argument is placed inside the parentheses. This will cause the sayHello function
to display the message 5 times.
When a function returns a value, the function call evaluates to the returned value. Therefore,
a function call can be placed anywhere an expression is needed. Consider the following
function calls:
double num = sqrt (5.6); cout<<” Sin 30 = “<<sin (3.14159/6);
if (abs(sin(ang)*sin(ang)+cos(ang)*cos(ang)-1)>0.0001) {cout<<” What?”;}
The abs function, defined in the math library, finds the absolute value of a number.
Example:
1. #include <iostream.h>
2. using namespace std;
3.
4. float add (float a, float b) //can accept two float arguments
Function Scope
A function body, enclosed within a pair of curly braces, forms a new scope. Variables
defined within a function body are not visible outside the function. Such variables are
known as local variables. They exist only while the function is executing. Parameters are
also local variables.
Points to Remember
• You should always document what your functions do by writing comments. Common
practice is to write these comments just above the function header.
• You must define a function before all calls to the function. (more on this in Chapter 6)
• Values that are passed into a function are called arguments and the variables that accept
these values are called parameters. The parameters always get a copy of the values (more
on this in Chapter 6)
Exercise:
1. Write a function called power what raises a number n to the power r (inputs are of type
int and the result is of type double). Hint:raising a number to the power r is the same as
multiplying the number by itself r times.
2. Write a function that computes the formula ID=IS ekVD/TK−1 seen previously.
Incorporate this function into your program.
3. Write a function called is_a_digit that returns true if a character argument passed to it is
a digit ('0' - '9') and false otherwise.
4. Write a menu driven program that does addition, subtraction, multiplication, division,
exponentiation, and logarithm of two numbers. Define each operation in its own
function. The program should end only when the user asks it to.
1. It is often required to find out what day of the week (Monday to Sunday) a given date
falls on. For example, May 15, 2009 falls on a Friday. The following algorithm describes
a procedure for calculating the day of the week given the month, day, and year as
integers (M = 1 for January). Algorithm to calculate the day of the week
i. If the month is January or February, add 12 to M and subtract 1 from Y.
ii. Calculate C as D + 2*M + 3*(M+1)/5 + Y + Y/4 - Y/100 + Y/400.
iii. Calculate A as the remainder of dividing C by 7.
a) Write a C++ function that accepts M, D and Y as input and displays the day of the
week.
b) Modify the above function to return true if the inputs are valid and false otherwise.
(M is valid if it is between 1 and 12, D is valid depending on the month, Y is valid
between 1800 and 2100)
c) Draw the flowchart for the algorithm. The conditions joined by an OR in step i. have
to be shown separately.
2. The following code was placed inside the body of main in a test program. What will be
displayed after the program is compiled and executed?
int a=0, b=1, c=2, d=3; cout<<”Testing...\tStart\n”; while (b<10)
{
cout<<--a-b*b+c/d<<endl;
d++;
b+=d;
c*=2; }
cout<<”Finished\n”;
3. Some of the following pieces of code compile but give undesired results. For each code,
identify the problem (if any), state its behavior, and correct it.
//sum the numbers from 13 to 128 int sum=0; //function to cube a number float cube(float
for (int i=13; i<=128; i++); sum+=i; number)
{
return number*number*number; }
a) c)
b)