You are on page 1of 19

CHAPTER 4: PROGRAM FLOW CONTROL

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.

4.1. Decisions and Branching

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 if keyword is followed by a condition in parenthesis. The condition is a test expression


that evaluates to a boolean value. The statement can be a single statement or a compound
statement. If the condition is true, the statement is executed. Otherwise, the statement is
skipped, and execution continues with the next statement (not shown above). Example:
5. unsigned short age;
6. cout<<” Enter your age:> “;
7. cin>>age;
8. if (age < 17)
9. cout<<” You are too young\n”;
10. cout<<” Thank you” <<endl;

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.

Introduction to Computing Handout. Compiled by: Mohammed A. 23


Similarly, we can execute a block of statements if the condition is satisfied.

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

Introduction to Computing Handout. Compiled by: Mohammed A. 24


Here, if condition evaluates to true, statement1 will be executed. If it evaluates to false,
statement2 will be executed. Both statement1 and statement2 can be compound
statements. Example:
5. unsigned short age;
6. cout<<”Enter your age:> “;
7. cin>>age;
8. if (age < 17)
9. cout<<”You are too young\n”;
10. else
11. cout<<”You are old enough\n”;
12. cout<<”Thank you”<<endl;

Note: the whole of the if...else construct is considered as a statement.


These two forms of the if statement can be represented using flowcharts as follows

Nested if...else statements


Notice that statement2 can be any statement, including an if...else statement. This allows us
to take more complex decisions.
Example:
5. unsigned short age;
6. cout<<” Enter your age:> “;
7. cin>>age;
8. if (age < 17)
9. cout<<” You are too young\n”;
10. else
11. if (age<40)
12. cout<<” Don’t worry, you are still young\n”;
13. else
14. if (age<70)

Introduction to Computing Handout. Compiled by: Mohammed A. 25


15. cout<<” Still young at heart\n”;
16. else
17. cout<<” Are you sure that is your age? \n”;

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

Introduction to Computing Handout. Compiled by: Mohammed A. 26


3. Develop a four function calculator that can
perform addition, subtraction, multiplication and
division of two numbers. The program should
ask the user for a number, an operator, and
another number.

The switch Statement


Situations usually arise where deeply nested if...else statements (a lot of levels of if...else
statements within other if...else statements) have to be used to realize a certain logic. It is
usually very difficult to express our intended logic using such deeply nested if...else
statements. Modifying such code is also much harder to get right.

As an alternative method of choosing among a set of mutually exclusive choices, C++


provides the switch statement. Syntax:
switch (variable)
{
case constant1:
statements
break;
case constant2:
statements
break;

case constantN:
statements break;
default:
statements
}

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:

Introduction to Computing Handout. Compiled by: Mohammed A. 27


5. unsigned short key, ans;
6. float balance = 23.0F;
7. long PIN;
8. cout<<”**** The 904 Program ****\n”;
9. cout<<”Press 1 for recharge”<<endl
10. <<”Press 2 for balance”<<endl
11. <<”Press 3 to change password”<<endl
12. <<”Press 4 for missing claim”<<endl
13. <<”Press 0 to exit”<<endl;
14. cin>>key;
15. switch (key)
16. {
17. case 1:
18. cout<<”Your pre­paid account is being recharged”<<endl;
19. break;
20. case 2:
21. cout<<”Your account balance is currently “
22. <<balance<<” birr.”<<endl;
23. break; 24.
24. case 3:
25. cout<<”Please enter your 8 digit PIN number:”<<endl;
26. cin>>PIN;
27. break;
28. case 4:
29. cout<<”Press 1 to claim missing:”<<endl;
30. cin>>ans;
31. break;
32. case 0:
33. cout<<”Please wait while your call is transferred.”<<endl;
34. break;
35. default:
36. cout<<”Are you sure?”<<endl;
37. }
38. cout<<”Thank you for using ETC's 904. Please come
again!”;
Note: Don't forget the break statement after each case. Without it, control passes down (or
“falls through”) to the statements for the next case, which is usually not what you want. No
break statement is necessary after default, since we're at the end of the switch anyway.
4.2. Looping

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 Statement


A while statement repeatedly executes a statement if a certain condition is true. Syntax:
while (condition) statement

Introduction to Computing Handout. Compiled by: Mohammed A. 28


The while keyword is followed by the condition in
parentheses. The expression inside the parentheses is tested
and if it has a true value, the statement (the body of the loop)
is executed. Again, the statement can be a single statement or
a compound statement. This cycle of testing the condition and
executing the statement in the body of the loop is repeated
until the expression in parentheses is false. Each repetition is
known as an iteration.

In the following example, the program keeps on asking the


user for an answer until the user enters 42. Example:
5. short ans=0; //notice the initialization
6. while (ans! =42)
7. {
8. cout<<”\nWhat is the ultimate answer?: > “;
9. cin>>ans;
10. }
11. cout<<”Well done! You have found the answer.”;

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

Introduction to Computing Handout. Compiled by: Mohammed A. 29


Here we have the do keyword followed by a statement which is
followed by the while keyword and the test condition in
parentheses. (Again, we can have a block of statements.) The do …
while loop is identical to a while loop except that it performs at least
one iteration even if the condition is false from the start. Also notice
that there is a semicolon at the end after the parentheses.

The following program shows a typical usage of the do … while


loop – a program with a menu system. Notice that the test condition
would evaluate to false if this had been a pretest loop. Example:
5. int ans=0; //ans initialized to 0
6. do {
7. cout<<”What would you like to do?\n”
8. <<”1. Display \”Hello World\”\n”
9. <<”2. Do something trivial\n”
10. <<”3. Display a random number\n”
11. <<”Enter your choice (0 to exit):> “;
12. cin>>ans;
13. cout<<”OK then!\n”;
14. /*Normally, you would use a switch statement to
15. do what the user asked */
16. } while (ans!=0); //don't forget this semicolon

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

In this example, num is being treated as a counter. It is initialized to 1 on line 6 and it is


updated (incremented) with every iteration of the loop on line 12. With this arrangement,
in each iteration, the value of num indicates the number of iterations done so far. Although
we can work with counters using both while and do … while loops, C++ has one that is
ideal for working with counters – the for loop.

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.

Introduction to Computing Handout. Compiled by: Mohammed A. 30


The for Loop Statement
The for loop is ideal for working with counters because it provides built in expressions
that initialize and update variables. Syntax:
for (initialization; condition; update) statement

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

The order of execution for the for loop is as follows


1. The initialization statement is executed once at the start of the loop. num is declared and
initialized to 1.
2. Then the condition is evaluated. If num is less than or equal to 10, go to step 3, otherwise
terminate the loop.
3. Execute the statement. Display num and the square of num.
4. Finally evaluate the update expression (increment num) and go back to step 2.

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

for (; ;) //no initialization, condition or update – infinite loop


cout<<” Oh yes! \n”;

Introduction to Computing Handout. Compiled by: Mohammed A. 31


for (int i=0, j=1; j<40 && i! =j; i++, j*=2) //multiple update and init. cout<<” i is: “<<i<<” \tj is:
“<<j<<endl;

(More examples discussed in class).

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)

Introduction to Computing Handout. Compiled by: Mohammed A. 32


The continue and break Statements
The break statement can also be placed inside a loop. When it is encountered, the loop
stops and program jumps to the statement following the loop. Example:
5. int n;
6. int count = 0;
7. cout<<” Enter any number between 1 and 10 :> “;
8. cin>>n;
9. while (count++ < 10)
10. {
11. cout<<count<<endl;
12. if (count==n)
13. break;
14. }
15.
16. cout<<” You entered “<<count;

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

Introduction to Computing Handout. Compiled by: Mohammed A. 33


Variable Scope
Normally, we expect a variable name to be a unique entity. However, C++ allows us to
reuse a name as long as it is used in different contexts. This context is known as a scope. A
scope is a region of the program and a name can refer to different entities in different scopes.
Most scopes in C++ are delimited by curly braces. Names are visible from their point of
declaration until the end of the scope in which the declaration appears.

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.

4.3. Introduction to Functions

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.

Introduction to Computing Handout. Compiled by: Mohammed A. 34


So far, you have created a function called main in every program. You have also made use of
library functions such as sin and setw. Now we will study the basics of functions so that we can
create our own that can be used like the library functions.

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

Introduction to Computing Handout. Compiled by: Mohammed A. 35


In this example, a simple function is defined. The function header on line 4 tells us that the
function has a return type of void, its name is sayHello and it has no parameter list. From
this, we conclude that it takes no arguments and does not return anything. Inside the
function body, we have a single statement that prints a message to the screen (line 6).

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

In general, whenever a function call statement is encountered inside a function, execution


is interrupted and control jumps to the called function. When the function finishes
executing, control jumps back to the calling function. The figure below illustrates this
process. The solid arrows represent execution flow and the dashed arrows represent jumps.

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.

Passing Data to a Function

Introduction to Computing Handout. Compiled by: Mohammed A. 36


Earlier we have said that a function performs some computation and yields a result. When
a function is called, the caller can send values into the function. The function then performs
its computation based on its inputs. The values that are sent into the function are called
arguments. You have already seen how to send arguments to a function when you were
using library functions. A parameter is a special variable that holds a value being passed as
an argument into a function. By using parameters, you can define your own functions that
accept data from the caller.

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.

A function can accept multiple arguments separated by commas (seen previously). To


create a function that is able to do that, we define a number of parameters separated by
commas in the function header. Consider the following headers
void sayHello (int times, int num) float aOverB (float a,
float b)
int bigFunction(int N, float val1, double val2, float val3)
Obtaining the Result from a Function
A function returns the result of its computation to its caller using the return statement. It
takes the form return expr; where expr is an expression which when evaluated will have
the type indicated by the return type of the function. A return type of void indicates that
the function will not return a value. In such cases, the return statement is not necessary.

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

Introduction to Computing Handout. Compiled by: Mohammed A. 37


5. {
6. return a+b;
7. }
8.
9. float input () //can't accept arguments
10. {
11. float a;
12. cout<<” Enter Value:> “;
13. cin>>a;
14. return a;
15. }
16.
17. void show (float num) //can accept one float argument
18. {
19. cout<<” \mResult = “<<num<<endl;
20. }
21.
22. int main ()
23. {
24. float num1, num2, result;
25. num1 = input (); //num1 will be assigned the returned value
26. num2 = input ();
27. result = add (num1, num2);
28. show(result);
29. return 0;
30. }
(Analysis to be done in class)
Since the function call can be used as an expression, lines 27 and 28 may be replaced by a
single line as follows.
27. show (add (num1, num2));

In fact, lines 24 to 28 may be replaced by a single line as follows.


24. show (add (input (), input ()));

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)

Introduction to Computing Handout. Compiled by: Mohammed A. 38


• When writing a parameter list, each variable must have a data type associated with it.
You can't leave out the data type of a variable even if it has the same type as the variable
declared before it.
• A function call, when used as an expression, evaluates to the value returned by the
function.

Example: The following function computes the formula y = mx+ b.


float y (float m, float x, float b)
{ return m*x+b; }

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.

Introduction to Computing Handout. Compiled by: Mohammed A. 39


Sample Exam Questions

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.

iv. If A is 0, then print Monday; if A is 1, then print Tuesday and so on.

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)

Introduction to Computing: Handout


//check if a year is a leap year int year; d)
cout<<”Enter the year: “; if /* display a number entered by the user */
(year%4==0) float num; cout<<”Enter number: “; cin>>num;
{ cout<<”Leap year\n”; } else cout<<”Number is: “<<”num”<<endl;
1
cout<<”Not a leap year\n”; cin>>year;

4. Each of the following programs has one or


two problems that would not allow it to compile. Find these problems and correct them.
Print the outputs.

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


2. int Main() 2.
3. { 3. void F(int param1, param2)
4. int i=15; 4. {
5. while (i<14) 5. float var1 = 3.2F;
6. cout<<”i is “<<i++<<endl; 6. cout<<param1*param2/var1;
7. return 0; 7. }
8. } 8.
9. int main()
1. #include <iostream.h> 10. {
2. int main() 11. cout<<”initial value: “
3. { 12. <<var1<<endl;
4. float inp; 13. F(3, 2);
5. cout<<”Enter a number: “; 14. return 0;
6. cin>>inp; 15. }
7. cout<<”The natural logarithm”
8. <<” of “<<inp<<” is “
9. <<log(inp)<<endl;
10. }
a) c)

Introduction to Computing: Handout

You might also like