You are on page 1of 53

Bahir Dar University

Bahir Dar Institute of Technology


School of Computing

Laboratory Manual
for
Fundamentals of Programming-I (C++)

Prepared By: Desta Berihu (MSc.)


Reviewed By: Seffi Gebeyehu (MSc.)

January 2007 E.C

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 1
Contents
Introduction ................................................................................................................................................. 4
Lesson-1: Basic elements of programming ................................................................................................ 5
Objective .................................................................................................................................................. 5
Prerequisite ............................................................................................................................................. 5
Lesson-1 Activity ...................................................................................................................................... 5
Lesson-1 Exercise .................................................................................................................................... 8
Lesson-2: Basic elements of programming (continued) ............................................................................ 8
Objective .................................................................................................................................................. 8
Prerequisite ............................................................................................................................................. 8
Lesson-2 Activity ...................................................................................................................................... 8
Lesson-2 Exercise .................................................................................................................................. 11
Lesson-3: Basic Elements of Programming (continued) ......................................................................... 11
Objective ................................................................................................................................................ 11
Prerequisite ........................................................................................................................................... 11
Lesson-3 Activity .................................................................................................................................... 11
Lesson-3 Exercises ................................................................................................................................. 14
Lesson-4: Conditional Statements ........................................................................................................... 14
Objective ................................................................................................................................................ 14
Prerequisites .......................................................................................................................................... 14
Lesson-4 Activities ................................................................................................................................. 14
Lesson-4 Exercises ................................................................................................................................. 18
Lesson-5: Conditional Statements (continued) ........................................................................................ 18
Objective ................................................................................................................................................ 18
Prerequisites .......................................................................................................................................... 18
Lesson-5 Activity .................................................................................................................................... 18
Lesson-5 Exercises ................................................................................................................................. 20
Lesson-6: Looping statements .................................................................................................................. 21
Objective ................................................................................................................................................ 21
Prerequisites .......................................................................................................................................... 21
Lesson-6 Activity .................................................................................................................................... 21
Lesson-6 Exercise .................................................................................................................................. 25
Lesson-7: Looping statements (continued) .............................................................................................. 25
Objective ................................................................................................................................................ 25
Prerequisites .......................................................................................................................................... 25
Lesson-7 Activity .................................................................................................................................... 25

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 2
Lesson-7 Exercise .................................................................................................................................. 29
Lesson-8: Jumping Statements ................................................................................................................ 30
Objective ................................................................................................................................................ 30
Prerequisites .......................................................................................................................................... 30
Lesson-7 Activity .................................................................................................................................... 30
Lesson-8 Exercise .................................................................................................................................. 34
Lesson-9: C++ Function ........................................................................................................................... 35
Objective ................................................................................................................................................ 35
Prerequisites .......................................................................................................................................... 35
Lesson-9 Activity .................................................................................................................................... 35
Lesson-9 Exercise .................................................................................................................................. 37
Lesson-10: C++ Function (continued) ..................................................................................................... 37
Objective ................................................................................................................................................ 37
Prerequisites .......................................................................................................................................... 37
Lesson-10 Activity .................................................................................................................................. 38
Lesson-10 Exercises ............................................................................................................................... 39
Lesson-11: C++ Function (continued) ..................................................................................................... 40
Objective ................................................................................................................................................ 40
Prerequisites .......................................................................................................................................... 40
Lesson-11 Activity .................................................................................................................................. 40
Lesson-11 Exercise................................................................................................................................. 47
Lesson-12: C++ Function (continued) ..................................................................................................... 47
Objective ................................................................................................................................................ 47
Prerequisites .......................................................................................................................................... 47
Lesson-12 Activity .................................................................................................................................. 47
Lesson-12 Exercise................................................................................................................................. 50
Lesson-13: C++ Function: working with overloaded functions .............................................................. 51
Objective ................................................................................................................................................ 51
Prerequisites .......................................................................................................................................... 51
Lesson-13 Activity .................................................................................................................................. 51

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 3
Introduction
This is a laboratory manual for the course Fundamentals of Programming-I in C++. The content is
organized into lessons corresponding to the lecture content outlined on the curriculum. And the
code in this manual is written (edited), compiled and run using the Borland C++ editor.

Each of the lessons does have objectives, prerequisites to the lesson, activities to be done at home
and during the laboratory session and at last, exercises to the respective lesson.

The objective of the lesson will describe the reason why you will be in the laboratory by that
session. That is, it will tell you what to achieve at the end of completing that session.

The prerequisite of the lesson will tell you the activities and studies YOU SHALL WORK AT
HOME before you come and sit for the respective laboratory session. That is, it highlights the
reading points that you must study before coming to that laboratory session.

The activities section of the lesson will tell you what to do during that session towards achieving
the objective of the lesson by giving at least one example and letting you carry on with the
remaining tasks based on the given example. Besides, it provides a-line-by-line code analysis of the
solved problems in order to help the students understand and solve similar problems with the same
fashion. Note that all students are intended to practice and understand these solved problems at
home and come to the laboratory for asking and further deepening their understanding on that
lesson.

At last, all lessons do have exercises relevant to the respective lesson to help the students deepening
their skill and, ultimately, understand the theme of the lesson.

As a final notice, this manual is now ready to be given to the trainees (students) to help them
acquire the necessary skills and understandings, and then lead them to the level that they would
produce software-based solutions to the miscellaneous societal problems we have today!

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 4
Lesson-1: Basic elements of programming
Objective:- the main objective of this lesson is to help students understand and apply the C++
operators in their programs.
Prerequisite:- students should read and understand the C++ operators and their usage in
programming
Lesson-1 Activity
Task-1: What is the output of the following program?

Fig.1: code sample on the C++ operators

Code analysis for the program in Fig.1


In Line-1:- #include<iostream.h>
 # is read as hash. It can be considered as NB or remark for it urges the compiler to include (add
or import) the file enclosed under the angle brackets (i.e., the file iostream.h) from the
standard library of C++.
 Keyword include is used to include the external file to our code.
 < > are brackets used to bound the target file to be imported from the library of the language.

In line-3:- void main()


 void :- is return type of the function named as main. It means that the method doesn‟t have
value to be returned to the caller. But still, mind you that functions return the control to their

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 5
caller no matter whether they return value or not.
 main:- is the name of the method. Function name is given by the programmer and can be any
name that expresses the activity accomplished by that method. But still, it must be a valid
identifier.
 ( ): is a method marker operator. It tells that the identifier preceding it is a method name.
In line-4: {
 {:- is read as begin. It marks that it is the beginning of the body of the method.
In line-5:- int x=2, y=2, z;
This line is declaring variables. These are x, y and z. In C++, variables must first be declared
before use. By declaring, we mean telling (announcing) to the compiler that you will use this
memory holder (variable) later in your code.
 int:- is an integer data type. It is telling the compiler about the content and dimension of the
memory holder (variable) next to it. That is, it describes two things about the variable that:
o the content of the variable is only integers specified under the range of the data type int.
o the dimension of the variable is only 4-bytes.
All data types tell these two aspects of the data in the variable: content type and dimension.
 x=2, y=2, z;
o Here, x, y and z are variable names (named memory areas in the RAM).
o = read as „assign into‟ is the assignment operator. It means put the value (in this case, 2)
written to the right side of it into the area named, for example, as x.
o Comma (,) is the variable declaration delimiter operator.
o Semicolon (;) is an end of statement marker. It tells the compiler the end of the statement.
In Line-6:- z = x++;

 There are two variables (the z and x) and two operators (the = and ++). Now, since the ++ is a
post increment operator, it is evaluated after the assignment operator. For this reason, first, the
original value of x is assigned to z. And then, the value of x is incremented by 1.
In Line-7:- y = ++z;
 The ++ is a pre-increment operator and hence, has higher priority when compared with the
assignment operator. For this reason, first, the pre-increment operator is evaluated and then the
affected new value of z will be assigned to y.
In Line-8:- x -=y-- + --z;
 Here, there are four operators namely subtraction assignment, post-decrement, addition, and

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 6
pre-decrement operators. Now, this statement can also be re-written as:
x = x-(y-- + --z);
For this reason, the expression under the ( ) is evaluated first. From the operators found inside
of the ( ), the pre-increment operator takes the highest precedence and hence value of z will be
deducted by 1. Since post-decrement operators are evaluated after the assignment operator, the
addition operator will take the second precedence and hence, the original value of y will be
added with the deducted new value of z. And then, the summation value of the bracket will be
deducted from the x and finally will be assigned to x. At last, the post-decrement of y will be
evaluated and deducts value of y by 1.
In Line-8:- x = (y>z)?z:y;
 This statement has got three operators namely the assignment operator, the greater than
operator and the conditional operator (?:). Now, according to the operator precedence order of
C++, the expression under the ( ) should be evaluated first. Accordingly, the expression y>z is
evaluated to either value true or false. If it is evaluated to true, value of z will be assigned to x,
other wise value of y will be assigned to x.
 In general, you will find the following intermediate and final outputs indicated after the :
#include<iostream.h>
void main()
{
int x=2, y=2, z; Output
z = x++;  x=3,z=2
y = ++z;  y=3,z=3
x -= y-- + --z;  x=-2, y=2,z=2
y += x + z--;  x=-2, y=2, z=1
x = (y>z)?z:y;  x=1, y=2, z=1
cout<<"\n X="+x;  X=1
}

Task-2: Write a C++ program which accepts the value of X and Y from the keyboard and display
the result of the evaluation of each of the following expressions.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 7
Lesson-1 Exercise
1) Write a C++ program which accepts the height and base of a triangle and displays the area
of a rectangle.
2) Write a C++ program which accepts the radius of a circle and calculates its area and
circumference.
3) Write a C++ program which accepts the radius of a sphere and calculates the volume and
surface area. [Note that volume = ¾π(radius)3 and area = 4π(radius)2. Take π to be 3.14159265]

Lesson-2: Basic elements of programming (continued)


Objective: at the end of this lesson, students will be able to understand and apply the basic
programming elements such as identifiers, variables, data types, etc.
Prerequisite: - students should come to laboratory session after studying and understanding the
basic programming elements of C++ such as identifiers, variables, data types,
expressions, etc.
Lesson-2 Activity
Task-1: Write a C++ program which accepts two numbers from the keyword and displays the
summation of the numbers.
Here below is the program for this task.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 8
Fig.2: code sample on the C++ basic programming elements
Code analysis for the program in Fig.2
Line-2: #include<iostream.h> is a header file statement. It is including the file iostream.h
found in the standard C++ library to the program. Note that this file contains the cin and
cout keywords in it. So, if one wants to use these standard input and output streams, then
including this file is a must!
Line-4: void main(){
This is the signature of the function named as main. In this statement, void is the return type
of the function and it means no-return-type.
Line-5: int firstNum, secondNum, summation;
is the declaration statement.
 It is declaring three variables namely firstNum, secondNum, and summation.
Remember that variables are identifiers and hence should meet the identifier-validity-rules.
For example, you can‟t declare like the following:
int first Num, 2secondNum, summation;
This declaration statement has two errors:
 The variable firstNum is made to have a space in between its two words: first and Num.
Space is not allowed in C++ identifiers.
 The variable secondNum starts with digit. It should not start with digit. C++ identifiers
should not start with digits but can contain digits next to the first character.
Line-6: cout<<"Enter the first number"<<endl; is an output statement.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 9
 cout:- is the output stream object which represents the C++ standard output stream
(outputting to the monitor).
 <<:- is called insertion operator or output redirection operator. It is used to combine the
output data and redirects it to the screen.
 Everything under the double quotation is called literal string and is displayed to the screen as
is.
 endl:- is an abbreviation of „end of line’. It takes the output cursor to the new line and by
doing so, makes the next line to be printed in new line.
Line-7: cin>>firstNum; is an input statement.
o cin:- is an input stream object which represents the C++ standard input stream (inputting
from the keyword).
 >>:- is called an extraction operator or an input redirection operator. It is used to extract (take
into) an input from the input stream. i.e., It is used to accept an input from the keyboard.
 firstNum:- is the name of the variable which is made ready to hold the first
number coming from the keyboard. That is, the first number entered from the
keyboard is stored in this available.
Line-11: summation = firstNum + secondNum; is the process statement.
Here, there are two operators: = and +. Now, first, the expression to the right side of the equal-to
operator is evaluated. Accordingly, the two numbers will be added up. And then, the result (the
summation) is „assigned into‟ the variable summation.

At last, you will see the following output:

Please note that everything which was written under the double quotation is printed (displayed) as
part of the output as was written in the program.

Task-2: Write a program which accepts width and height of a rectangle and displays the area of
the rectangle.
Task-3: Write a program which accepts a number and displays the square and cube of that number.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 10
Lesson-2 Exercise
1) Draw a flow chart which accepts mass and acceleration of an object and displays the force
applied over that object. [Hint: Force = Mass * Acceleration]. Finally, change the flowchart to
its C++ equivalent.
2) Write a program which accepts a decimal number, changes it into its binary number equivalent
and finally display the binary number.
3) Write a program which accepts mid and final exam result of a student, compute the total mark
and, finally, determines whether the student passed or not given that passing mark is 50.

Lesson-3: Basic Elements of Programming (continued)


Objective: at the end of this lesson, students will be able to understand and apply the basic
programming elements such as identifiers, variables, literals, comments, data types,
operators, expressions, constants, statements etc.
Prerequisite: students should come to laboratory with the deep theoretical readings and
understanding of all the basic programming elements of C++.

Lesson-3 Activity
Task-1: Write a C++ program which accepts three numbers x, y and z and compute the following
algebraic expression:
2 +
a) � � =
−2

In C++, the expression in the above equation is written as (2*x+y)/(z-2). An expression, as you may
know, is a combination of operators and operands. The above expression contains two operands and
six operators. Now, the important question that must be answered here is question of precedence
order (evaluation priority) of the operators.

According to the precedence order of operators in C++, operands under the ( ) are operated first.
Under the first bracket () again, we have two operators. So, the multiplication has higher
precedence order than the addition. Expression under the second bracket () follows. Finally, the
division operator is evaluated.

Here below is the program.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 11
Fig.3: code sample on the basic programming elements of C++
Code analysis for the program in Fig.3
Line-2: is a header file which includes the iostream.h file to our program.
Line-4: is the signature of the main() function. Note that the return type of the function is now
changed into int. In the previous lessons, we were writing void as a return type of the
main() function. Now, int in line-4 means that after the main() function finished doing
its tasks, it returns an integer value. And for this, the function must have a return
statement at the very end of its body (as given in line-13). In line-13, the value 0 is an
integer.
Line-6: is declaring variables x, y, z and result.
Line-7: is displaying a prompting message to the user on the screen.
Line-8: is accepting an input from the keyboard.
Line-10: is the process statement. It is evaluating the expression is assigning the evualtion value to
the result variable using the assignment (=) operator.
Line-12: is an output statement. It is displaying the output to the consol. Everything under the
double quotation together with the value of variable result is displayed to the consol.
Line-13: is the return statement. It is always used to return the control and value from the function
to the caller of the function. I will discuss in later lessons about a function and concepts
related to it.
After you compile and run the above program, you would see an output such as the following.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 12
Task-2: Write a C++ program which accepts total number of days and converts it into years,
months, weeks and days.
Example:- If 544 is entered, the output should be:
544 days is equal to 1 year, 5 months, 2 weeks, and 1 day
Here below is the program for question.

Fig.4: additional code sample on the basic programming elements of C++

Code analysis for the program in Fig.4


Line-1: is the header file.
Line-3: is the signature of the main function.
Line-5: is variable declaration statement. Six integer variables are declared.
Line-6: is the output statement which prints the literal string under the double quotation.
Line-7: is the input statement. It accepts the total number of days to be changed to years-months-days.
Line-8: The value entered from keyword is stored in totalNumberOfDays and we assigned this value to
another variable named remainingDays. This is needed for later calculation reasons.
Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 13
Line-11: We divide the total number of days by 365 to find the number of years.
Line-12: The remainder of the division the total days by 365 is taken to find the months and so on.
Line-22: is the output statement. Note the skip characters in the program above.
 \n means new line. \t means one tab horizontal space.
After you compile and run the above program, you would see an output such as the following.

Task-3: Takes total number of days and converts it into hours, minutes or seconds.
Example - If 544 are entered the output should be:-
544 days is equal to 6528 hours or 391680 or 23500800 seconds
Lesson-3 Exercises
1) Write a C++ program which accepts three numbers x, y and z and compute the following
algebraic expression. Finally, the program should displays the value of result.
2 + 2 +4
� � =
2
2) Write a program which computes the equivalent resistance of two resistors connected in parallel
when the two resistors are entered by a user. Note that 1/Req = 1/R1 + 1/R2.

Lesson-4: Conditional Statements


Objective: at the end of this lesson, students will be able to implement the conditional statements of
C++ (if…else if…else, and switch…case) in solving different problems.
Prerequisites: Before they come to this laboratory session, students should study the syntax of the
if…else if…else, and switch…case conditional statements of C++.
Lesson-4 Activities
Task-1: Write a C++ program which accepts a number and determines whether it is odd or
even.[Use if…else]
Here below is the program for the above question.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 14
Fig.5: code sample on the if…else statements of C++
Code analysis for the program in Fig.5
Line-1: is a white space and will be ignored by the compiler. White spaces are all ignored by the compiler.
Line-2: is the header file for this program.
Line-3: is the function signature of the main() function.
Line-5: is declaring a variable of type int.
Line-6: is prompting the user to enter the number from the keyboard.
Line-7: is accepting the input from the keyword.
Line-9: is testing if the number entered from the keyboard is even or not. If a number is divisible by
two without remainder, then it means the number is even. Otherwise, it is odd. Note that
the expression of the if-statement should be evaluated to either true or false.
Line-10: is display a message that tells the number is even. This is executed if the condition of the
if-statement is evaluated into true.
Line-15: is the output if the condition in line-9 is evaluated into false.
After you compile and run the above program, you would see an output such as the following.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 15
Task-2: Write a C++ program which accepts grade of a student and determines the status of the
student based on the following given tabular data. [Use Switch…case]

Grade Status
A or a Excellent
B or b Very Good
C or c Good
D or d Satisfactory
F or f Failed
Here below is the program of the above task.

Fig.6: code sample on the switch…case statements of C++

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 16
Code analysis for the program in Fig.6
Line-1: is the header file to the program. This is added to the program because we need to use the
cout and cin objects found in this standard library.
Line-4: we declare a char variable named grade. It is used to store the grade character coming
from the keyboard.
Line-6: is accepting the grade character from the keyboard (i.e., from the user).
Line-8: the keyword switch is the indicator of the beginning of the switch block. It takes an
expression, which should be evaluated to constant value, as an argument.
Line-9: is the case clause. The keyword case indicates one possible value which equates the value
of the expression in this switch. Next to the keyword case is the value which will be
compared with the value of the expression.
Line-10: another possible value which may match with the value of the expression. Note that line-9
and line-10 are being considered as equal options (values) to satisfy the expression in the
switch. They are read as incase the value is „A‟ or „a‟, then display “Status = Excellent”.
Line-12: break- means go out off the switch block. And hence, execution flow does not proceed to
the next line after the break statement, rather goes out off the switch block.
Line-33: is the default case which executed if there is no any case (option) from the previous cases
which satisfy the expression of the switch. This is equivalent to else-block of the if statement.
NB: the default clause ends with colon (:).
After you compile and run the above program, you would see an output such as the following.

Task-3: Write a program which accepts an age of a person and displays his/her age category based
on the following age-category-range table.

Age range Age category


[0 - 20] Wind age
[21 - 40] Fire age
[41 - 60] Water age
[61 - 80] Earth age

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 17
Task-4: Write a program which accepts a number from the user and checks whether the number is
positive, negative or zero.
Lesson-4 Exercises
1) Write a program which accepts two numbers from the user and:
a. displays the largest number
b. finds the maximum and minimum of the numbers.
2) Write a program which accepts weight and height (both integers) of a person and outputs a
descriptive message indicating his/her eligibility to be normal (normal=w/h2 where w=
weight in kg, h=height in m, normal must be between 18 and 25).
3) During a special sale at a store, a 10% discount is taken on purchases over $10.00. Write a
program that asks for the amount of purchases, and then calculates the discounted price. The
purchase amount will be input in cents (as an integer):
Example: Enter amount of purchases:
2000
Discounted price: 1800

Lesson-5: Conditional Statements (continued)


Objective: at the end of this lesson, students will be able to implement the nested conditional
statements of C++ (if…else if…else, and switch…case) in solving different problems.
Prerequisites: Before they come to this laboratory session, students should study the syntax of the
nested if…else if…else, nested if…else and switch…case conditional statements of C++.
Lesson-5 Activity
Task-1: Write a C++ program which accepts three numbers from the keyboard, and displays the
largest number. [Use Nested If---else]
Here below is the program of the above task.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 18
Fig.7: code sample on the nested if…else statements of C++

Code analysis for the program in Fig.7


Line-1: is the header file. We add it as we need to use cout and cin objects.
Line-2: is the signature of the main function. Keyword void is the return type of the function.
Line-4: is variable declaration statement. We declared three variables, each to store the three
numbers coming from keyboard.
Line-5: is declaring a integer variable which can hold the largest number.
Line-6: is prompting the user to enter the numbers from the keyboard.
Line-7: is accepting the numbers as an input from the keyboard.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 19
Line-9: is the if-statement. It is testing if the first number is greater than the second number. The
body of this if-statement is executed if the condition in it (num1>num2) is evaluated to
value true.
Line-11: is a conditional statement in side of another conditional statement- hence, nested if…else.
This condition is executed only if the condition in line-9 is evaluated to true. If this
condition is evaluated to true, then the largest will be num1.
Line-14: is another conditional statement to be tested if the condition in line-11 is evaluated to
false. If this condition is true, then the largest number will be num2.
Line-18: this is the last possible conditional option. It is executed when on other previous
conditions (options) are not executed.
Line-23: is another condition corresponding to the if-statement in line-9. This condition has also
two nested conditions under it – the condition in line-24 and in line-28.

Here below is the output of the above program.

Task-2: Write a program which accepts coefficients a, b and c of quadratic equation and computes
real roots of the quadratic equations.

Lesson-5 Exercises
1. Write a program which accepts a word and checks if the word is palindrome. Example of
palindrome words: omo, racecar, alula, civic, level, etc.
2. Write a program that determines a student‟s grade. The program will read three types of scores
(quiz, mid-term, and final scores) and determine the grade based on the following scale:
Average score Grade
>=90% A
>= 70% and <90% B
>=60% and <70% C
>=50% and <60 % D
<50% F

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 20
3. Write a program that asks the user to type an integer N between 0 and 20 (both included) and
writes N+17. If someone types a wrong value, the program writes ERROR and the program
should force him/her to type another value.
4. Write a program that asks the user to type an integer N and that writes the number of prime
numbers lesser or equal to N.
5. Write a program which displays the following menu and lets the user to choose and enter the key
of either of the months in the menu. And then, the program should list all possible governmental
and religious festivals/holidays of Ethiopia. For instance, if the user enters 1, then the program
should display:
o Ethiopian New Year
o EOTC Meskel Holiday
o Ethiopian Muslim Ramadan Holiday
Your program should ask the user to continue entering another key or exiting from the program
by giving yes/no options.
Month key Month Name Month key Month Name
1 September 7 March
2 October 8 April
3 November 9 May
4 December 10 June
5 January 11 July
6 February 12 August

Lesson-6: Looping statements


Objective: at the end of this lesson, students will be able to solve problems using C++ loops.
Prerequisites: Before they come to this laboratory session, students should study the syntax and
usage of the three types of C++ loops.
Lesson-6 Activity
Task-1:- Write a program which adds the numbers from 1 to 100 and finally displays their sum.
Here below is the program of the above task.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 21
Fig.8: code sample on for-loop statements of C++

Code analysis for the program in Fig.8


Line-6: is declaring two variables. The variable i is declared to be used as a counter variable for
the for-loop written in line-8 and variable sum is used to contain the sum of the numbers.
Line-8: is a for-loop definition. The loop beings at 1 and ends at 100, incrementing by 1 in each of
the iterations.
It is read as starting from 1 to 100 by incrementing by 1, sum of all numbers between 1 and
100. The loop runs until the condition (i<=100) is evaluated to false.
Line-11: is an output statement. It displays the sum of the numbers between 1 and 100.

Here below is the output of the above program.

Task-2: Write a C++ program which accepts a positive integer and displays the sum of all
positive even integers less than or equal to it.
Here below is the program of the above task.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 22
Fig.9: code sample on while-loop statements of C++

Code analysis for the program in Fig.9


This program has two major activities to do. First, it checks if the number is positive integer.
Second, it further tests if the number is even or not. And then, if it is found to be even, it should be
added to the already existed value of sum, otherwise it is skipped. Accordingly,
Line-10: is checking if the number is positive integer. If it not, the program prompts the user to re-
enter another number which is positive.
Line-13: is going for the other possibility. That is, if the number is positive or zero, then it further
checks if the number is even or odd.
Line-16: is a while-loop statement which is used to add up all even numbers which are less than or
equal to the number entered.
Line-18: is a conditional statement and is checking if the number is divisible by two to know
whether it is even or not. If it is found to be even, then it is added to the previous value of
sum, otherwise it is skipped.
Line-24: is displaying the sum of all even numbers less than or equal to the number as an output.

Here below is the output of the above program.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 23
Task-3: Write a program which computes the following expression.
200

( + )/�
�=1

Here below is the program of the above task.

Fig.10: code sample on loop statements of C++

Code analysis for the program in Fig.10


The main intention of this example is to show you the real application of loops in various
mathematical problems.
Line-8: is accepting the number (x and y) from the keyboard.
Line-10: is adding up the numbers between 1 and 100 as is given in the mathematical expression.
Line-13: Finally, the sum of the numbers is displayed.

Here below is the output of the above task.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 24
Task-4: Write an application to print out the numbers 10 through 49 in the following manner
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49

Lesson-6 Exercise
1. A prime number is an integer greater than one and divisible only by itself and one. The first
seven prime numbers are 2, 3, 5, 7, 11, 13, and 17. Write a program that displays all the prime
numbers between 1 and 100.
2. Write a program that counts the number of digits in an integer number. For example; 23,498 has
five digits.

Lesson-7: Looping statements (continued)


Objective: at the end of this lesson, students will be able to apply C++ loops to solve different
figure-like designs and problems.
Prerequisites: Before they come to this laboratory session, students should study the syntax and
usage of the three types of C++ loops.
Lesson-7 Activity
Task-1: Write a C++ program which prints the following.
(a) (b) (c) (d) (e) (f) (g)

Here below is the program for the diagram (a):

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 25
Fig.11: code sample on loop statements of C++

Code analysis for the program in Fig.11


To solve the problem in diagram (a), we first look at the pattern of the asterisks (*) and we
understand that the number of rows and columns are the same. Besides, the number of asterisks in
rows is the same as in columns.

As can be seen from the code above, we used nested for-loop to solve the problem. The outer-loop
is used to count the rows and the inner loop to count the columns. In view of that:
Line-10: is the outer loop. The counter for this loop (i.e., i) is running from 1 to the height entered
from keyboard.
Line-11: is introducing two tab spaces for all rows. The scape character \t is to mean tab
(horizontal space).
Line-12: is the inner loop. The counter for this loop (i.e., j) is running from 1 to the height entered
from keyboard. The reason for the fact that both the counter (i and j) are running from 1 to
height is because the figure is square.
Line-16: is forcing the output cursor to go to the newline when it finishes iterating the inner loop.
That is, when it finishes displaying all the asterisks in one row.

After you finish composing, compiling and running the program, you will see the diagram as an
output, which its height depends on the height value you entered such as the following.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 26
Here below is the program for the diagram (b):

Fig.12: code sample on loop statements of C++

Code analysis for the program in Fig.12


Here, the main thing to deal with is to learn the pattern of the asterisks (*) per row and column.
Accordingly, we can simply learn from the given diagram a pattern that each row contains number
of asterisks exactly to the number of the row itself.
That is, Row-1 contains 1 asterisk
Row-2 contains 2 asterisks
Row-3 contains 3 asterisks, etc.
From this extracted pattern, we can conclude that the number of asterisks (*) are exactly the same
as the row number. So, the outer loop (line-10) counts the number of rows and the inner loop (line-
11) counts the number of asterisks (*) per row (in another word, the number of columns). Hence,
the counter i is running from 1 to the height entered. Counter j is running from 1 to the number
of row (i.e., i).

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 27
After you compose, compile and run the program, you will see the diagram based on the height you
entered as follows.

Here below is the program for the diagram (c):

Fig.13: code sample on loop statements of C++

Code analysis for the program in Fig.13


Similar to the problem in (b), we should learn a pattern to solve this problem too.

Value of i Number of spaces = height-i


Number of asterisks = i
Now, we observe that:
Row-1 has height-1 spaces and 1 asterisk
Row-2 has height-2 spaces and 2 asterisks
Row-3 has height-3 spaces and 3 asterisks
Row-4 has height-4 spaces and 4 asterisks, etc.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 28
That is,
 i is a counter for the row and is running from 1 to height.
 J is a counter for the column and is running from 1 to height-i to print the spaces and
exactly to the number of i (i.e., to the number of the row) to print the asterisks.
With this view;
Line-8: is accepting the height of the rectangle (the diagram).
Line-10: is the outer loop with a counter i which counts the rows of the diagram. Note that i is
running from 1 to height, where height is the entered value.
Line-11: is the inner loop with a counter j which counts the columns of the diagram. Note that the
column of the diagram contains height-row (or height-i, since i is counting rows)
spaces and i (which is equal to the row count) number of asterisks. For this reason, the
inner loop prints spaces for all j from 1 to height-i and asterisks when j exceeds
height-i.
Line-18: takes the output cursor to newline so that all rows will be displayed in newlines.

After you compose, compile and run the program, you will see the diagram based on the height you
entered such as the following.

The programs for diagrams (d) to (g) are left as exercises for the students.
Lesson-7 Exercise
1. Write a program which prints a 12 X 12 timetable.
2. Write a application that can compute the letter grade of a student after accepting the
student‟s mid and final mark. The program should only accept mid result [0-40] and final
[0- 60]. If the data entered violates this rule, the program should display that the user should
enter the mark in the specified range. The program is also expected to run until the user
refuses to continue.
Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 29
3. Write a program that computes the sum of the following series.
Sum = 1! + 2! + 3! + 4! + …n!
The program should accept the number from the user.

Lesson-8: Jumping Statements


Objective: at the end of this lesson, students will be able to apply the jumping statements in solving
various problems.
Prerequisites: Before they come to this laboratory session, students should study the syntax and
usage of the jumping statements.

Lesson-7 Activity
Task-1: Write a program which prints the average of only even numbers between 1 and 20.
Here below is the program of the above task.

Fig.14: code sample on jumping statements of C++

Code analysis for the program in Fig.14


Line-7: this loop is used to iterate over numbers between 1 and 20.
Line-8: is a conditional statement which checks if the number is even or not. If the number is odd
then the iteration is skipped using the continue statement.
Line-10: is a continue statement. It makes the iteration to skip all statements after the continue
statement and go on to the next iteration.
Line-14: is adding up all the even numbers.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 30
Line-15: is counting the even numbers added.
Line-18: is calculating the average of the numbers by dividing their sum by their count.
Line-19: is displaying the average of the even numbers as an output of the program.

After you compose, compile and run the program, you will see an output such as the following.

Task-2: Write a program which lets the user to play a simple game by entering integers between 1 and 7.
When the user enters all integers in the range [1-7] except 5, then it should confirm the user by
displaying “Very great! play again.”. But, when the user enters integer 5, the program should
display message “You entered BOMB!!”
Here below is the program of the above task.

Fig.14: code sample on jumping statements of C++

Code analysis for the program in Fig.14


Line-6: is for loop which iterates over number from 1 to 7.
Line-8: is prompting the user to enter numbers between 1 to 7.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 31
Line-9: is testing if the number entered is 5 or not. If it is 5, then it breaks (i.e., it goes out of the
loop) and continues to line-20 (to the statement next to the loop).
Line-11: is a break statement. It forces the execution flow to go out of the loop and continues to
line-20.
Line-13: is testing if the number entered is out of the range [1-7]. If the number entered is not in the
range [1-7], the break statement (in line-15) forces the flow control to go out of the loop and
continues to line-20.
Line-20: is testing if the number entered was 5. That is, if line-10 was executed. If it is true, then
message “You entered BOMB!! ....stop!!” is displayed.

After you compose, compile and run the program, you will see an output such as the following.

Task-3: Write a program in C++ which reads 10 integers in the range 0 – 100 from the keyboard,
and count how many of them are greater than 50, and finally displays the count and the list of the
numbers.
Here below is the program of the above program.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 32
Fig.14: code sample on jumping statements of C++

Code analysis for the program in Fig.14


Line-6: is declaring a constant variable. Keyword is const is used to declare a constant variable.
Line-7: is declaring an array of 10 integers.
Line-11: is a loop and is filling the array declared in line-7.
Line-15: is displaying the message “Numbers >= 50 are:”. In this line, note that we used \t
unprintable character (called tab escape character). This character is used to print one
horizontal tab.
Line-16: is a loop which iterates 10 times. It is iterating over the elements of the array to test them
whether they are less than fifty or not.
Line-17: is a conditional statement and is testing each of the elements of the array whether they are
less than fifty or not.
Line-18: is one of the jumping statements of C++. Statement continue makes the current
iteration to skip the statements next to it and goes back to the next iteration. If the
condition in line-17 is evaluated to true, then continue statement is executed and
statements next to continue (i.e., line-19, line-20 and line-21) are all skipped.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 33
Nevertheless, if the condition in line-17 is evaluated to false, then line-20 and line-21 are
executed. That is, numbers above 50 are all printed as an output of the program.
Line-23: is displaying the output to the screen. Note that we have used the \n (newline escape
character) to print the output statement in newline and the \t (tab escape character) to
indent the output statement one tab horizontally as is shown in the output diagram below.
After you compose, compile and run the program above, you will see an output something like the
following.

Task-4: Write a program which displays all consonant block letter English alphabets based on
their ASCII code. Your program should also display as many countries as possible whose name
begins with each of the consonant letters.

Lesson-8 Exercise
1. Write a program which lets the user to enter all small letter English alphabets and counts the
vowels. And displays the order, name and ASCII code of the vowels in tabular form. The
program should validate that the input should be in the range [a - z].
Order of vowels Name of vowels ASCII of vowels
1 a 97
… … …

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 34
Lesson-9: C++ Function
Objective: at the end of this lesson, students will be able to write function-based programs thereby
understand the syntax and semantics of function definition, function prototype and
function call.

Prerequisites: Before they come to this laboratory session, students should study the syntax and
semantics of function definition, function call and function prototype.

Lesson-9 Activity
Task-1: Write a C++ function named cube() that accepts an integer and returns the cube of the
number.
When we put the function alone, it seems as given here below.

Fig.15: code sample on C++ functions

Code analysis for the program in Fig.15


A function in C++ is defined by putting a return type, function name, function parenthesis, and
function parameter list. Accordingly, lets see the syntax and semantics of the function given in
fig.15.

In Line-2:
 long: is the return type of the function.
 cube : is the name of the function.
 int: - is the data type of the parameter variable
 number:- is the name of the variable.
 ():- is the function marker parenthesis.
 {}:- is the curly brace which bounds the body of the function.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 35
In Line-3:
 long:- is the data type of the local variable numberCube.
 numberCube:- is the name of the local variable.
 = :- is an assignment operator which assigns the evaluated value of the right side expression
back to the variable to the left side of the assignment.
NB:
1) The return type of the function should be exact match with the return data of the function.
2) Data type of the parameter can be either of the data types of the language. And it is used to
define the type of the content of the parameter variable, in this case the data of variable
number.
When we put the above function in a program to calculate the cube of a number, it is written as
follows:

ይህ የአስሌው ስርዓት
[funtion definition] ነው ።

ይህ የአስሌው ጥሪ (Function call) ነው።

Fig.16: code sample on C++ functions

Code analysis for the program in Fig.16


Note why the function is written before the main() function. In C++, there two possible ways of
putting user defined functions in our program. These are:
i) before the main() function:- In this case, writing prototype for the function is not needed.
ii) after the main() function:- if the user defined function is written after the main() function,
then writing prototype of the function before the main() function is mandatory.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 36
In line-14: the function cube() is invoked. i.e. the function cube() is made to work.

Variable name Function Call

cubeOfNum = cube(num);

If the return type of a function is different from void, then the returned
value may be assigned to a variable for later computation.

The output of the above program is given as follows:

Task-2: Write program which contains a function that, given a letter of the alphabet, returns true if
the letter is a vowel (lower or uppercase) and returns false if the letter is not a vowel.

Lesson-9 Exercise
1. The formula for a line is normally given as y = mx + b. Write a function Line() that expects
three float parameters, a slop m, a y-intercept b, and an x-coordinate x. the function computes
the y-coordinate associated with the line specified by m and b at x-coordinate.
2. Write a function intersect() with four float parameters m1,b1,m2,b2. The parameters come
conceptually in two pairs. The first pair contains the coefficients describing one line; the second
pair contains coefficients describing a second line. The function returns 1 if the two lines
intersect. Otherwise, it should return 0;
3. Write a random-number generator that returns a number from 1 to N (rather than 0 to N–1),
where N is the integer argument passed to it.

Lesson-10: C++ Function (continued)


Objective: at the end of this lesson, students will be able to understand the syntax and semantics of
recursive functions. Besides, you will also be very clear with the real application of
recursion functions.

Prerequisites: Before they come to this laboratory session, students should study the syntax and
semantics of function definition, function call and function prototype.
Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 37
Lesson-10 Activity
Task-1: Write a program which accepts any positive integer and return the factorial of the number.
Use recursive function calling here.

Here below is the program.

Fig.17: code sample on C++ recursive functions

Code analysis for the program in Fig.17


Line-2: #include <iostream.h>
This is the header file statement.
Line-4: int factorialValue = 1;
 int: - data type of the variable factorialValue
 factorialValue:- is the name of the global variable.
NB: In C++, any variable declared outside of any function (or block) is called a global variable.
Line-5: int factorial(int);
This statement is called function prototype. Function prototype does nothing but announces that
existence of such of a method after the main() function.
Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 38
 int: is the return type of the data to be returned from the function factorial().
 factorial(int); :- is the prototype of the function. Function prototype does not have
body, it rather has semicolon at the end.
Line-6: facto = factorial(number);
 facto: is the name of the variable intended to contain the returned factorial value from the
factorial function.
 factorial(number); :- is the function call to the function factorial(). Please do not
forget the only is the name and argument (value) is needed to call a function. The type and
number of arguments (values) should be exactly the same to the type and number of
parameters in the definition of the function.
Line-18 to Line-26: is definition of the factorial function. Here note that the function accepts a
number, n, as its input and checks if the number is equal to 1. If it equal to 1, then the function
returns value 1 as the factorial value of the number. Otherwise it calls itself recursively to
calculate the factorial value of numbers n, n-1, n-2,…2. The call to the factorial function in
line-23 is call to the function itself, and hence, is recursive call.
 Recursive function calls itself so many times until it fulfills some exit conditions like the
value 1 for the factorial function.

The output of the program is given here below.

Task-2: Write another program that accepts a number from the user and returns the Fibonacci
value of that number. You should use recursion.

Lesson-10 Exercises
1. Write a program which calculates the binomial coefficient which is defined as follows:
� �!
= , given integer values of n and r are greater than zero (both > 0).
! �− !

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 39
2. Write a program that calculates triangle numbers by using a recursive function. A triangle
number is the sum of all whole numbers from 1 to N, in which N is the number specified. For
example, triangle (5) = 5 + 4 + 3 + 2 + 1.
3. Write a program which contains a function named greatestCommonFactor()which takes
to two parameters and returns the gcf of the two numbers.

Lesson-11: C++ Function (continued)


Objective: at the end of this lesson, students will be able to understand how to define several
functions in a given program and make them call each other.

Prerequisites: Before they come to this laboratory session, students should study the syntax and
semantics of function definition, call and prototype.
Lesson-11 Activity
Task-1: write a program which accepts two numbers and displays their sum, difference, product
and quotient. Define functions add(), subtract(), multiply() and division()
respectively to calculate the summation, difference, product and quotient of the numbers. All the
functions should be called from within the main() method.

Here below is the program to the problem above.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 40
Fig.18: code sample on C++ function call, prototype and definition

Code analysis for the program in Fig.18


 Line-4 to line-7 are function prototype statements. Note that function prototypes don‟t have
function body. They instead do have semicolon at the end. Their parameter list may be only
data types or parameter name with their data types.
 Line-27 to line-31 is the function definition of the add function.
Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 41
 Line-33 to line-37 is the function definition of the subtract function.
 Line-39 to line-43 is the function definition of the multiply function.
 Line-44 to line-48 is the function definition of the divide function.
You can see that all functions return an integer datum. For this reason, the return type of
each of the functions is marked as int and all have return statement at the end of their
body. A return statement marks two things for the function:-
 The return value of the called function to the caller.
 The end of the respective function. It may not be the last statement to be written in
the function. But, it must be the last statement to be executed in the function!!

 Lins-16 to line-19 is the function call statements. Note how to call a function. We call a
function from within another function by using its name and arguments (values) list
equivalent to the number and type of the parameters of the function invoked.

Note again that function prototypes are needed only if the definition of the functions to be called
directly or indirectly from within the main function are written after the main() function.

Here below is the output of the above program.

Task-2: Write a program that asks a user to enter (choose) either of the mathematical arithmetic
operators by displaying a menu and further asks the user to enter the numbers to be
operated using the operator chosen. Finally, the program should display the computed
value. Note that the program should check if the user entered is valid input and should
prompt the user the question “Do you want to continue?” repeatedly until the user enters
“N or n“, which means “ No” and makes the program to stop.

Here below is the program to this question.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 42
Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 43
Fig.19: code sample on C++ function call, prototype and definition

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 44
Code analysis for the program in Fig.19
Line-4 to line-10: are function prototypes of the seven function definitions defined after the
main() function. Note that function prototype is needed only if the function is defined after
the main() function and contains only the signature of the definition of the function.

Line-13 to Line-17: is the main function of the program. Note here that the main() function
contains only a single statement, i.e., a call to the displayOperatorsMenu() function.
Line-15: is a call to the displayOperatorsMenu() function.
Line-18 to line-69 is the definition of the displayOperatorsMenu() function.
Line-20 to line-22 is local variables defined within this function.
Line-24 to line-29 is displaying the menu to the user.
Line-31 is prompting the user to enter an operator of his/her preference from the menu given.
Line-32 is entering the input (symbol of the operator) from a keyboard.
Line-34 to line-68 is the switch-case block. It contains four cases to be tested and one default
clause. If the entered symbol is addition operator (+), then statements from line-36 to
line-41 are executed.

Line-36 is prompting the user to enter the numbers to be operated


Line-37 is entering the inputs from keyboard.
Line-38 is calling a function named addNumbers(). Moreover, num1 and num2 are
arguments (values) to the function. Note that the total number and data type
of arguments should always be the same as the total number and data type of
parameters. In addition, since this function returns a value, we prepared a
variable (in this case, summation) to contain the return value.
Line-39 is displaying the sum of the two numbers entered from keyboard.
Line-40 is a call to the function named doYouWantToContinue().
Line-41 is an exit statement from the switch block.

The case in line-43, 51 and 59 are also executed in the same fashion as the case in line-35 if
the entered operator symbols are *, / or -. If the entered input (operator symbol) is different
from +, *, / or - then it prints the statement in line-67.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 45
Line-71 to line-87: is the definition of the function named doYouWantToContinue(). The basic
task of this function is to check whether the user wants to continue or not by accepting a
symbol in the set {Y, y, N, n}. The switch-case block from line-75 to line-86 is checking if
the entered character is either character Y or y, just to mean 'Yes' or character N or n to
mean 'No'.

Line-76 and line-77: are checking if the input is {Y or y}. In this case, it calls a function named
displayOperatorMenu() to start entering his/her preference again (line-78). If the
symbol entered is {N, n}, then it displays the message in line-82. Otherwise, line-85 is
executed to indicate that the user has entered a symbol which is not in the set {N, n, Y, y}.

Line-89 to line-91 is the definition of the function named addNumbers().


Line-92 to line-94 is the definition of the function named multiplyNumbers().
Line-95 to line-97 is the definition of the function named substractNumbers().
Line-98 to line-100 is the definition of the function named dicideNumbers().

After you finish composing, compiling and running the above program, you will see an output
which looks like the following.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 46
Task-2: Write a function-based program which accepts a value of Ɵ in degree and calculates its
corresponding sin, cos, sec, csc, tan and cotan value. In addition, your program should
let the user to enter his/her preference by displaying a MENU of the functions and does
the computation according the precedence order entered. Furthermore, the program
should also change the degree value to radian. At last, your program should ask the
user if s/he wants to continue or not.

Lesson-11 Exercise
1. Write a program which accepts a date according to the Gregorian calendar and converts to its
Ethiopian calendar equivalent. The conversion process should consider the issue of leap year and
the like.

2. Write a program which automates the calendar computation (called „ባሕረ ሓሳብ‟) of the Ethiopian
calendar and then outputs:
a) the entire calendar of a given year by highlighting all national and religious festivity.
b) The name of the day (Monday, Tuesday, etc) on which Ethiopian new year festivity
(Meskerem 1st of the year) was.
c) The name of previous days by accepting the date of that day. For instance, the battle of
Adewa was conducted in 23/06/1888 EC. Now, your program should display whether this
day was Monday, Tuesday or other after accepting the date of the event. Do the same for
your birth date and other major events in your life.

Lesson-12: C++ Function (continued)


Objective: at the end of this lesson, students will be able to understand how function call other
functions and control the flow of execution by making tracing and code analysis methods.

Prerequisites: Before they come to this laboratory session, students should study the syntax and
semantics of function definition, function call and function prototype and how a function
call another function as well as how it manages the flow of execution.

Lesson-12 Activity
Task-1: predict the output of the following code manually. That is, trace the program given below
by hand to determine its output. After you finish tracing and predicting the output
manually by hand, type the program, compile and run it to know how much correct your
manual work was.
Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 47
Here below is the program to this question.

Fig.20: code sample on how functions call each other and control flow of execution

Code analysis for the program in Fig.20


Line-4 to line-7: are prototypes to all the functions written in the code except the main() function.
Now, please notice that all the functions are defined before the main() function. In this
case, we said that these function prototypes are optional, and hence can be omitted.
Line-9 to line-12: is definition of the function displayMessage1(). This functions accepts an
integer value (rank) as its parameter and displays the message on line-10 and finally returns
the rank parameter by adding value one to it to its caller; i.e., to line-24.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 48
Line-13 to line-16: is definition of the function displayMessage2(). This function accepts an
integer parameter and displays the output in line-14 and line-15. Note that line-15 is also
calling another function, diplaysMessage3(), defined in line-17. For this reason, the
body of the function diplaysMessage3()is executed first and then control goes back to
line-15 by carrying the value return from diplaysMessage3() function. It displays by
concatenating the returned value with the literal string “This is the like
status…”.
Line-17 to line-21: is definition of the function diplaysMessage3(). This function accepts one
integer parameter and displays the literal string “I love BDU!” in line-18. In line-19, it calls
another function named diplaysMessage4()by passing value of rank as an argument.
Note here that even if diplaysMessage4()returns an integer value, the call to it in line-
19 is not storing the returned value. We do something like this when we don‟t want to use
the returned value in further computations. Finally, this method returns value of rank for
its caller.
Line-22 to line-25: is definition of the function diplaysMessage4(). This function takes an
integer parameter and displays the by concatenating the literal string “I love BiT” with value
of the love parameter (line23). In line-24, the function calls diplaysMessage1()by
passing value of variable love to it. Now, diplaysMessage4()returns the value
returned from diplaysMessage1()to its caller in line-31.
Line-27 to line-37: is definition of the main() function.
Line-29: displays the literal string “Welcome to CPP”.
Line-30: is a call to function diplaysMessage2(). In this line, value 5 is an argument
(value) sent to parameter variable like of diplaysMessage2()in line-13.
Line-31: is calling diplaysMessage4()by passing value 4 as an argument. Since
diplaysMessage4()returns a value and we want to use this returned value for
further computation (such as in line-33), we declared a variable rank4 in line-31
to store the returned value.
Line-32: can be understood in similar fashion as line-31.
Line-33: displays an output by concatenating the literal string “Now the rank4 is: ” with the
value stored in variable rank4.
Line-33: displays an output by concatenating the literal string “Now the rank4 is: ” with the

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 49
value stored in variable rank5.

Please be sure that you have a clear understanding of how functions are written and call each other.
The output of the code depicted above is given below.

Lesson-12 Exercise
1. Write a program which accepts a date in Ethiopian calendar in the format dd/mm/yyyy and any
positive integer n and displays the date that can be obtained after adding n days to the date
entered from keyword. Your program must have the following functions:
void acceptInput() // to accept the inputs from keyword.
String addDaysToEthioDate(String ethioDate, int days) // to add the days to date.
Moreover, consider the following points while writing the program.
a) Function main()should call addDaysToEthioDate() function to obtain the resultant
date after adding the days to the date entered.
b) Function addDaysToEthioDate()should call function acceptInput() to accept the
date and the days to be added to the date.
c) Both function addDaysToEthioDate()and acceptInput()should be written before
the main() function.
Example: assume that:
date entered from keyword = 03/05/2007
n days to be added = 50
Now, the output should be 03/05/2007 + 50 days = 23/06/2007.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 50
Lesson-13: C++ Function: working with overloaded functions
Objective: at the end of this lesson, students will be able to understand how overloaded functions
work.

Prerequisites: Before they come to this laboratory session, students should study the syntax and
semantics of overloaded functions. They should come after clearing the concept of how
overloaded functions are written and why are they needed.

Lesson-13 Activity
Task-1: Write an overloaded function named validate(). The first function accepts an integer and
checks whether the number is even or not. The second function accepts two integers and checks
whether the sum of the numbers is greater than or equal to 100. The third function accepts three
integers and checks if at least one of them is multiple of three.

Here below is the program to this question.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 51
Fig.21: code sample on how overloaded functions are defined and work.

Code analysis for the program in Fig.21


Line-3 to line-6: are the prototypes of the overloaded functions defined after the main() function.
Line-9: is declaring three integer variables to store the three numbers coming from keyboard.
Line-10: is declaring three boolean variables. Note the bool data type.
Line-12: is displaying a text which informs the user to enter the three numbers.
Line-13: is accepting the input from keyboard.
Line-15: is calling the overloaded function validate() with one parameter. And the returned
value is stored in the variable evenOdd.
Line-16: is calling the overloaded function validate() with two parameters.And the returned
value is stored in the variable sumGth100
Line-17: is calling the overloaded function validate() with three parameters. And the returned
value is stored in the variable oneIsMultipleThree.
Line-19 to Line-21: are displaying the output.
Line-23: is a return statement. This line is added at the end of the main() function as the return
type of the main() function is int. It returns O for no meaningful return value is expected
from the main() method.

Line-27 to Line-32: is the definition of the overloaded function validate() with one parameter.
Line-28: is declaring a boolean variable evenOdd and is initializing to value false.
Line-29: is a conditional statement which tests if the number passed as a parameter to the
function is even or not.

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 52
Line-30: is assigning value true to boolean variable evenOdd.
Line-31: is returning value true or false.
Line-35 to Line-41: is the definition of the overloaded function validate() with two parameters.
This function is adding the first two numbers and checks if their sum is greater than 100 or
not, and finally returns true or false based on the test.

Line-44 to Line-49: is the definition of the overloaded function validate() with three
parameters. This function is testing if at least one of the three numbers is multiple of three
or not, and finally returns value true or false based on the output of the test.
After you finish composing, compiling and running the above program, you will see an output
which looks like the following.

Task-2: Write a program with three overloaded functions with the name status() which determines
the status of a student as “Promoted”, “Warning”, and “Failed”. The first function accepts
semesterGPA of a student, the second one accepts sem1GPA and sem2GPA to determine the status
and the third function accepts sem1GPA, sem2GPA and comulativeGPA of a student and
determines the status of the student accordingly.

…………..// END //……………

Fundamentals of Programming-I Laboratory Manual --- prepared by Desta Berihu Weldegiorgis Page 53

You might also like