0% found this document useful (0 votes)
17 views95 pages

Fundamentals of Programming II Draft

fundamentals of programing

Uploaded by

mulukengashaw666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views95 pages

Fundamentals of Programming II Draft

fundamentals of programing

Uploaded by

mulukengashaw666
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Mekidela Amba University

Laboratory Manual

Course title: Fundamentals of Programming II

College of Computing and Informatics

Depatment Of Software Engineering

Prepared By: Taye A.


Software Engineering
06/03/2017
Table of contents
Week 1: Fundamental Programming I Revision.............................................................................................................6
Objective: ........................................................................................................................................................ 6
Prerequisite ...................................................................................................................................................... 6
Expression evaluation ......................................................................................................................................6

Program ............................................................................................................................................................................ 10
Sample input output ..........................................................................................................................................................10
Condition evaluation ......................................................................................................................................10

Program ............................................................................................................................................................................ 11
Program ............................................................................................................................................................................ 13
Sample input output ..........................................................................................................................................................14
Program ............................................................................................................................................................................ 15
Sample input output ..........................................................................................................................................................16
Lesson-1: C++ Function ...............................................................................................................................................16
Fig.15: code sample on C++ functions ........................................................................................................................... 16
In Line-2: .......................................................................................................................................................17
NB: ................................................................................................................................................................ 17
Code analysis for the program ...................................................................................................................... 18

Lesson-2: C++ Function (continued) ........................................................................................................................... 19


Code analysis for the program ......................................................................................................................................... 20
Lesson-3: C++ Function (continued) ........................................................................................................................... 22
Code analysis for the program in ..................................................................................................................................... 23
Code analysis for the program in .................................................................................................................. 27

Lesson-4: C++ Function (continued) ........................................................................................................................... 29


Code analysis for the program ..........................................................................................................................................31
Lesson-5: C++ Function: working with overloaded functions .....................................................................................34
Code analysis for the program ..........................................................................................................................................35
Array-I.......................................................................................................................................................................... 37
Objective ....................................................................................................................................................... 37
Prerequisite .................................................................................................................................................... 37

o Displaying elements of array elements .........................................................................................................................37


Program ............................................................................................................................................................................ 39
Program ............................................................................................................................................................................ 42
Program ............................................................................................................................................................................ 44
Sample input and output ................................................................................................................................................... 45
Array-II.........................................................................................................................................................................46
Objective ....................................................................................................................................................... 46
Prerequisite .................................................................................................................................................... 46

Sample input and output ................................................................................................................................................... 50


String-I..........................................................................................................................................................................50
Objective ....................................................................................................................................................... 50
Prerequisite .................................................................................................................................................... 50
Important points to be remembered ............................................................................................................... 50

Sample input and output ................................................................................................................................................... 55


Record/Structure I........................................................................................................................................................ 55
Objective ....................................................................................................................................................... 55
Important points to be remembered ............................................................................................................... 55

Record/Structure II....................................................................................................................................................... 60
Objective ....................................................................................................................................................... 60
Prerequisite .................................................................................................................................................... 60
Important points to be remembered ............................................................................................................... 60

Record/Structure III ......................................................................................................................................................68


Objective ....................................................................................................................................................... 68
Prerequisite .................................................................................................................................................... 68
Important points to be remembered ............................................................................................................... 68

Output ............................................................................................................................................................................... 73
Linked List/Pointer-I.................................................................................................................................................... 73
Objective ....................................................................................................................................................... 73
Important points to be remembered ............................................................................................................... 73

Sample input and output ................................................................................................................................................... 77


Linked List/Pointer-II................................................................................................................................................... 78
Objective ....................................................................................................................................................... 78
Prerequisite .................................................................................................................................................... 78
Important points to be remembered ............................................................................................................... 78

Algorithm..........................................................................................................................................................................78
Sample input and output ................................................................................................................................................... 83
Recursion -I.................................................................................................................................................................. 84
Objective ....................................................................................................................................................... 84
Prerequisite .................................................................................................................................................... 84
Important points to be remembered ............................................................................................................... 84

Sample input and output ................................................................................................................................................... 86


Recursion -II.................................................................................................................................................................87
Objective ....................................................................................................................................................... 87
Prerequisite .................................................................................................................................................... 87
Important points to be remembered ............................................................................................................... 87

Algorithm..........................................................................................................................................................................87
Recursion -III................................................................................................................................................................89
Objective ....................................................................................................................................................... 89
Prerequisite .................................................................................................................................................... 89
Important points to be remembered ............................................................................................................... 89

File I/O -I......................................................................................................................................................................91


Objective ....................................................................................................................................................... 91
Important points to be remembered ............................................................................................................... 91

Sample input and output ................................................................................................................................................... 95


Objectives
After successful completion of this laboratory exercises, students will be able to

1. Develop algorithms for solving simple problems.


2. Use Dev C++ to implement, test, and debug algorithms for solving simple
problems.
3. Write programs that use each of the following data structures: arrays, records, strings
and linked lists.
4. Write, test, and debug simple recursive functions and procedures.
5. Read and write text file
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Week 1: Fundamental Programming I Revision


Objective:

Students will revise translation of algebraic expression to C++ expression equivalent, branching
and looping statements.

Prerequisite
Students should revise Fundamentals of Programming I.
Important points to be remembered
 Expression evaluation: students will examine precedence order of different operators in
C++ program. In addition, students will convert a given algebraic expression to C++
programming expression.
 Controls: students will use if statements and loop controls to solve some problems

Expression evaluation
Task 1. Write a C++ program that accept three numbers x, y and z and compute the
following algebraic expression
2 +√ 2 +4
=
2

Taye Alemneh
6
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Flow chart

In addition to typing detail C++ codes of the above algorithm, you need to do the following task

Step-1:- include header files such as iostream.h and math.h

Step-2:- type empty main function

Step-2:- declare 4 float variables in order to hold three inputs and one output value

Step-3:- read inputs from keyboard

Step-4:-convert the given algebraic expression into C++ expression equivalent

2
+√ +4
=2 result=(numerator)/(denominator) 2

result=(2*x + sqrt(y*y-4*x*y))/(2*z);

Step-5:- display the final output

Taye Alemneh
7
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Your final code looks like the following

Sample Inputs and outputs

Task 2. Write a C++ program that takes total amount of money to be withdrawn from
ATM machine, and calculates number of Hundred birr notes , fifty birr notes, ten birr
notes, five birr notes and one birr notes
Example - If 297 is entered the output should be
297=2 hundred birr, 1 fifty birr, 4 ten birr , one five birr and 2 one birr notes

Taye Alemneh
8
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Algorithm

Step 1: start
Step 2: accept total amount of money y
Step 3: find hundred birr note hundred=y/100
Step 4: find remaining amount remaining=y%100
Step 5: find fifty birr note fifty=remaining/50
Step 6: find remaining amount remaining = remaining %50
Step 7: find ten birr note ten = remaining /10
Step 8: find remaining amount remaining = remaining %10
Step 9: find five birr note five = remaining /5
Step 10: find one birr not one = remaining %5
Step 11: display output (result)
Flow chart

Taye Alemneh
9
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Program

#include <iostream.h>

void main(){
int y,hundred,fifty,ten,five,one,remaining;
cout<<"\nEnter amount of money that you want to withdraw\n";
cin>>y;
hundred=y/100;
remaining=y%100;
fifty=remaining/50;
remaining=remaining%50;
ten=remaining/10;
remaining=remaining%10;
five=remaining/5;
one=remaining%5;
cout<<"hundred birr note="<<hundred <<"fifty birr note="<<fifty
<<"ten birr note="<<ten <<"five birr note="<<five
<<"one birr note="<<one;
}

Sample input output

Condition evaluation

Task 3. Write a C++ program that accept a number and check whether the number is
multiple of 3 or not.

Algorithm
Step 1: start
Step 2: accept a number n
Step 3: check whether n is evenly divisible by 3
Step 4: if n is evenly divisible by 3, display the message the number is multiple of 3

Taye Alemneh
10
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Step 5: if n is not evenly divisible by 3, display the message the number is not multiple
of 3

Flow chart

start

input n

Yes n%3==0 No

display 'the number display 'the number is


is multiple of 3 ' not multiple of 3 '

end

Program
#include <iostream.h>

void main(){
int n;
cout<<"\nEnter an integer\n";
cin>>n;
if(n%3==0)
cout<<n<<" is multiple of 3";
else
cout<<n<<" is not multiple of 3";
}

Sample input output

Taye Alemneh
11
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Task 4. Write a C++ program that receives 3 numbers and display the largest number

Algorithm
Step 1: start
Step 2: accept a number a,b,c
Step 3: identify the largest number
if a>b then
begin
If a>c then, a is largest number
Else if a<c, c is largest number
Else, a and c are largest numbers
End
Else if a<b then
Begin
If b>c then, b is largest number
Else if b<c, c is largest number
Else, b and c are largest numbers
End
Else
Begin
If a>c then, a and b are largest numbers
Else if a=c then, the three numbers are equal
Else, c is the largest number
End

Taye Alemneh
12
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Flow chart

Program
#include <iostream.h>

void
main(){ int
a,b,c;
cout<<"\nEnter three integers\n";
cin>>a>>b>>c;
if(a>b)
if(a>c)
cout<<a<<" is largest";
else if(a<c)
cout<<c<<" is largest";
else
cout<<a<<" and "<<c<<" are largest";
else if(a<b)
if(b>c)
cout<<b<<" is largest";
else if(b<c)
cout<<c<<" is largest";
else
Taye Alemneh
13
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

cout<<b<<" and "<<c<<" are largest";


else
if(a>c)
cout<<a<<" and "<<b<<" is largest";
else if(a<c)
cout<<c<<" is largest";
else
cout<<a<<","<<b<<" and "<<c<<" are equal";
}

Sample input output

Loops
Task 5. Write a C++ program that adds even numbers between 0 and any positive integer
number given by the user.

Algorithm
Step 1: start
Step 2: accept a number n
Step 3: check whether n is positive integer
Step 4: if n is positive integer, go Step 6
Step 5: if n is not positive integer, display the message enter positive integer
Step 6: compute sum of even numbers between 0 and n
Initialize loop counter variable i=0
Initialize loop sum =0
while(i<n)
begin
if i%2=0,then sum=sum+i

Taye Alemneh
14
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

i=i+1
end
Step 7: display sum
Flow chart

start

input n

i=0
sum=0

i<=n No

sum=sum+i
i=i+1 Yes display sum

end

Program
#include <iostream.h>

void main(){
int n,sum=0;
cout<<"\nEnter an integer\n";
cin>>n;
for(int
i=0;i<=n;i++){ if(i%2==0)
sum=sum+i;
}
cout<<"sum="<<sum;
}

Taye Alemneh
15
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Sample input output

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

Taye Alemneh
16
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
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.
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) ነው።

code sample on C++ functions

Taye Alemneh
17
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
Code analysis for the program
Note why the function is written before the main()function. In C++, there two possible ways ofputting
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.
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-1 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.

Taye Alemneh
18
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Lesson-2: 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.

Taye Alemneh
19
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
Lesson-2 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.

code sample on C++ recursive functions

Code analysis for the program


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

Taye Alemneh
20
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
existence of such of a method after the main()function.

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 havebody,
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 andnumber 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 Fibonaccivalue
of that number. You should use recursion.

Taye Alemneh
21
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
Lesson-2 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).
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.
2. Write a program which contains a function named greatestCommonFactor()which takes to two
parameters and returns the gcf of the two numbers.

Lesson-3: 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-3 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.

Taye Alemneh
22
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

code sample on C++ function call, prototype and definition

Code analysis for the program in


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

Taye Alemneh
23
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
 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.

Taye Alemneh
24
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
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.

Taye Alemneh
25
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

code sample on C++ function call, prototype and definition

Taye Alemneh
26
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
Code analysis for the program in
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.

Taye Alemneh
27
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
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.

Taye Alemneh
28
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
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-3 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


Ethiopiancalendar 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-4: 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-4 Activity

Taye Alemneh
29
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
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.

Taye Alemneh
30
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
Here below is the program to this question.

code sample on how functions call each other and control flow of execution

Code analysis for the program

Line-4 to line-7: are prototypes to all the functions written in the code except the main()[Link], 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.

Taye Alemneh
31
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
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 toline-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 valueof 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 likeof 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-31to
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

Taye Alemneh
32
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
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-4 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 resultantdate after
adding the days to the date entered.
b) Function addDaysToEthioDate()should call function acceptInput() to accept thedate and the
days to be added to the date.
c) Both function addDaysToEthioDate()and acceptInput()should be written beforethe 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.

Taye Alemneh
33
Software Engineering
FUNDAMENTALS OF PROGRAMMING II
Lesson-5: 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-5 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.

Taye Alemneh
34
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

code sample on how overloaded functions are defined and work.

Code analysis for the program


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 returnedvalue is
stored in the variable evenOdd.
Line-16: is calling the overloaded function validate()with two [Link] the returnedvalue is
stored in the variable sumGth100
Line-17: is calling the overloaded function validate()with three parameters. And the returnedvalue
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 booleanvariable evenOddand 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.

Taye Alemneh
35
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

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.

Taye Alemneh
36
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Array-I
Objective
Students will use array to store multiple values of the same type on a single variable.

Prerequisite
Students should understand purpose and syntactical usage of an array.
Important points to be remembered
 Array declaration: students will see how to declare an array.
 Accessing array elements: students will see how to access elements of an array
o Assigning values to array elements
o Displaying elements of array elements
 Accept multiple integer values and compute their sum and average.
 Accept multiple integer values and find the smallest and the largest integer, display all
elements in ascending orders.
 Accept multiple integer values and display all elements in ascending orders.

Task 6. Write a C++ program that accepts 5 numbers and compute their sum and average
( use array to store and process the input numbers).

Algorithm
Step 1: start
Step 2: Take variables namely i, a, sum

Taye Alemneh
37
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Step3: initialize sum=0


Step4: accept five numbers and store them on array
for(i=0;i<5;i++)
read a[i] value

Step 5: compute the sum of elements of the array


for(i=0;i<5;i++)
sum=sum + a[i]
Step 6: compute the average of elements of the array
Average=sum/5
Step 7: display sum and average

Flow chart

start

i=0
sum=0

i<5

j=0 input a[i]


i=i+1

j<5

average=sum/5
sum=sum+j

display sum
and average
j=j+1

end

Taye Alemneh
38
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Program
#include <iostream.h>

void main(){
int n[5],sum=0,average;
cout<<"\nEnter 5 integers\n";
//input five numbers
for(int i=0;i<5;i++){
cin>>n[i];
}
//compute the sum of five numbers
for(i=0;i<5;i++){ sum=
sum+n[i];
}
//compute the average of five numbers
average=sum/5;
//display the outputs
cout<<"sum="<<sum<<"\naverage="<<average;
}

Sample input output

Task 7. Accept 10 integers from the user and display the smallest value
Algorithm
Step 1: start
Step 2: Take variables namely i, a[10], min
Step4: accept ten numbers and store them on array
for(i=0;i<10;i++)
read a[i] value

Step3: initialize min=a[0]


Step 5: identify the smallest number

Taye Alemneh
39
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

for(i=1;i<10;i++)
begin
if a[i] <min then
min=a[i]
end
Step 7: display min

Flow chart

start

i=0
sum=0

i<10

j=1
min=a[0] input a[i] i=i+1

average=sum/5

display sum
and average

end

Program
#include <iostream.h>

void main(){
int n[10],min=0;
cout<<"\nEnter 10 integers\n";

Taye Alemneh
40
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

//input ten numbers


for(int i=0;i<10;i++){

cin>>n[i];
}
//assume the fisrt element is smallest number
min=n[0];

//check whether there is other number smaller than min


for(i=1;i<10;i++){
if(min<n[i])
min=n[i];

}
//display the outputs
cout<<"minimum="<<min;
}
Sample input and output

Task 8. Accept 10 integers from the user and display the numbers in ascending order

Taye Alemneh
41
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Flow chart

Program
#include <iostream.h>

void main(){
int n[10],min=0;
cout<<"\nEnter 10 integers\n";

//input ten numbers


for(int
i=0;i<10;i++){ cin>>
n[i];
}

//sort elements of array


for(i=1;i<10;i++){
for(int j=i+1;j<10;j++){

Taye Alemneh
42
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

if(n[j]<n[i]){
int temp=n[i];
n[i]=n[j];
n[j]=temp;
}
}
}

//display elements of array


cout<<"\nSorted array\n";
for( i=0;i<10;i++){ cout<
<n[i]<<endl;
}
}

Sample input and output

Task 9. Calculate the letter grades of 5 students. The program should accept the mid result
and the final result of the students. Use appropriate validity control mechanism to prevent
wrong inputs. (assume array index is identification number of students)

Taye Alemneh
43
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Flow chart

Program
#include <iostream.h>

void main(){
int mid[5],final[5],total[5];
char grade[5];
cout<<"\nEnter 5 integers\n";

//input ten numbers


for(int i=0;i<5;i++){
cout<<"mid and final result of "<<i+1<<"\n";
cin>>mid[i];
cin>>final[i];
}

//display elements of array


cout<<"\nSorted array\n";
for(i=0;i<5;i++){ total[i]
=mid[i]+final[i];
if(total[i]>90)
grade[i]='A';
else if(total[i]>80)
grade[i]='B';
else if(total[i]>70)
grade[i]='C';
else if(total[i]>60)
Taye Alemneh
44
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

grade[i]='D';
else
grade[i]='F';
}

//display elements of array


cout<<"\nSorted array\n";
for(i=0;i<5;i++){
cout<<"grade["<<(i+1)<<"]:"<<grade[i]<<endl;
}
}
Sample input and output

Taye Alemneh
45
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Array-II
Objective
Students will use two dimensional arrays to store values in two dimensions fashions

Prerequisite
Students should revise matrix in algebra.
Important points to be remembered
 Two dimensional array declarations: students will see how to declare a two dimensional
array

 Accessing a two dimensional array elements: students will see how to access elements
of a two dimensional array
o Assigning values to array elements
o Displaying elements of array elements
 Compute sum of two matrixes
 Assign a value to diagonal elements of an array
 Assign a value to upper triangle of an array
 Assign a value to lower triangle of an array

Task 10. Read two 2x2 matrixes and then print a matrix which is addition of these two
matrixes.

Flow chart
Begin
//accept values of the first matrix
For every rows i from 0 to 2
Begin
For every columns j from o to 2
Accept values at (i,j) of first matrix
End
//accept values of the second matrix
For every rows i from 0 to 2
Begin
For every columns j from o to 2
Taye Alemneh
46
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Accept values at (i,j) of the second matrix


end

//Compute the same of the two matrixes and put the result on another matrix
For every rows i from 0 to 2
Begin
For every columns j from o to 2

Result[i,j]= matrix1[i,j]+ matrix2[i,j];


end
//display values of the matrix Result
For every rows i from 0 to 2
Begin
For every columns j from o to 2
Display Result[i,j];
End
End

Program
#include <iostream.h>

void main(){
int m1[2][2],m2[2][2],sum[2][2],min=0;

cout<<"\nEnter the first 2x2 matrix\n";

//input elements of first matrix


for(int i=0;i<2;i++){
cout<<(i+1)<<"th row of first matrix\n";
for(int j=0;j<2;j++)
cin>>m1[i][j];

Taye Alemneh
47
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

//input elements of second matrix


cout<<"\nEnter the second 2x2 matrix\n";

for( i=0;i<2;i++){
cout<<(i+1)<<"th row of second matrix\n";
for(int j=0;j<2;j++)
cin>>m2[i][j];
}

//compute sum of the two matrixes


for( i=0;i<2;i++){
for(int j=0;j<2;j++)
sum[i][j]=m1[i][j]+m2[i][j];
}
//Display the first matrix
cout<<"\nthe first matrix\n" ;
for( i=0;i<2;i++){

for(int j=0;j<2;j++)
cout<<m1[i][j]<<" ";
cout<<endl;
}

//Display the second matrix


cout<<"\nthe second matrix\n";
for( i=0;i<2;i++){
for(int j=0;j<2;j++)
cout<<m2[i][j]<<" ";
cout<<endl;
}

//Display the sum


cout<<"\nthe sum of the two matrixes\n";
for( i=0;i<2;i++){
for(int j=0;j<2;j++)
cout<<sum[i][j]<<" ";
cout<<endl;
}
}
Sample input and output

Taye Alemneh
48
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Task 11. Write C++ program to display a matrix as shown below. The diagonal of the
matrix fills with 0. The lower side fills will -1s and the upper side fills with 1s.
0 1 1 1 1
-1 0 1 1 1
-1 -1 0 1 1
-1 -1 -1 0 1
-1 -1 -1 -1 0
Flow chart
For every rows
Begin
For every columns
Begin
If(row number and column number are equal)
Assign zero
Else If( row number is greater than column number)
Assign 1
Else If(row number is less than column number )
Assign -1
end
end
display values of array elements
Program
Taye Alemneh
49
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

#include <iostream.h>
#include <iomanip.h>

void main(){
int matrix[5][5];
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
{ if(i==j)
matrix[i][j]=0;
else if(i>j)
matrix[i][j]=-1;
else
matrix[i][j]=1;
}
//display
for( i=0;i<5;i++)
{ for(int j=0;j<5;j++)
cout<<setw(3)<<matrix[i][j]<<" ";
cout<<endl;
}
}
Sample input and output

String-I
Objective
Students will use two dimensional arrays to store and process list of names

Prerequisite
Students should revise array.

Important points to be remembered


 Two dimensional array declarations: students will see how to use two dimensional array
to store list of names.
 Accessing a two dimensional array elements: students will see how to sort, swap ad
Taye Alemneh
50
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

display elements of a two dimensional array


o Assigning values to array elements
o Sort elements
o Displaying elements of array elements

Task 12. Write a C++ program that accepts ten names and display them in alphabetical
order.

Flow chart
Accept ten names
Sort names
Display names
Program
#include <iostream.h>
#include<string.h>

void main(){
char name[10][20];
//input 10 names
cout<<"\nEnter ten names\n";
for(int i=0;i<10;i++)
cin>> name[i];

//display before sorting


cout<<"\nnames before sorting\n";
for( i=0;i<10;i++)
cout<< name[i]<<" ";

//sort names
for( i=0;i<10;i++)
for(int j=i;j<10;j++)
if(strcmp(name[i],name[j])>0){
char temp[20];
strcpy(temp,name[i]);
Taye Alemneh
51
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

strcpy(name[i],name[j]);
strcpy(name[j],temp);
}

//display after sorting


cout<<"\nnames after sorting\n";
for( i=0;i<10;i++)
cout<<name[i]<<" ";

Taye Alemneh
52
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Sample input and output

Task 13. Develop a C++ program that accepts the name of a person and then counts how
many vowels the person’s name have.

Flow chart
Accept a name
Initialize count=0
For every character s in the name
Begin
If(s is equal to one of a,A,e,E,i,I, o,O,u,U)
Count=count+1;
End
Display the name and count

Program
#include <iostream.h>

void main(){
char name[10];
int vowelCount=0 ;
char vowels[]={'a','A','e','E','i','I','o','O','u','U'};
//accept a name

Taye Alemneh
53
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

cout<<"\nenter person's name\n";


cin>>name;

//count the number of vowels


for(int i=0;i<strlen(name);i++){
for(int
j=0;j<strlen(vowels);j++){ if(na
me[i]==vowels[j])
vowelCount++;
}
}

cout<<"The name "<<name<<" has "<<vowelCount<<" Vowels\n";

Sample input and output

Task 14. Accept a word from the user and then displays the word after reversing it.

Flow chart
Accept a name
Reverse the name using built in function
Display the name and count

Program
#include <iostream.h>
#include<string.h>

void main(){
char name[10],reversedName[10];

//accept a name
cout<<"\nenter person's name\n";
cin>>name;

cout<<"The original name "<<name ;

Taye Alemneh
54
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

//reverse the name and display results


cout<<"\nThe reversed name "<<strrev(name);
}
Sample input and output

Record/Structure I
Objective
Students will use structure to store multiple values of different data type.

Important points to be remembered


 Structure definition: students will see how to define structure definition.
 Structure variable declaration: students will see how to declare structure variable
 Accessing structure variable: students will see how to assign and display elements of the
variable

Task 15. Write a C++ program to accept and display records of 5 students. The information
of each student contains ID, Name, and Sex

Algorithm

Begin
For every rows i from 0 to 5
Accept id, name and sex of ith record

Taye Alemneh
55
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

//display values of array elements


For every rows i from 0 to 5
Display id, name and sex of ith record
End

Program
#include <iostream.h>
#include <iomanip.h>

struct student{
int stnumber;
char stname[20];
char sex;
};

void main()
{
student stud[5];
//input
for(int i=0;i<5;i++)
{
cout<<"enter "<<(i+1)<<"th student information\n";
cout<<"enter student number: ";
cin>>stud[i].stnumber;
cout<<"enter student name: ";
cin>>stud[i].stname;
cout<<"enter student sex: ";
cin>>stud[i].sex;
}

//display

cout<<setw(10)<<"id"<<setw(20)<<"name"<<setw(10)<<"sex\n";
for( i=0;i<5;i++)
{
cout<<setw(10)<<stud[i].stnumber<<setw(20)

<<stud[i].stname<<setw(10)<<stud[i].sex<<endl;
}

Taye Alemneh
56
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Sample Input/Output

Task 16. Write a C++ program to accept records of 5 students. The information of each
student contains ID, Name, mid-term score, final score, and total score. Your program
should sort records by total scores in ascending order and display the sorted records.

Algorithm
Begin
//accept values of array elements
For every rows i from 0 to 5
Accept id, name, midScore and FinalScore of ith record
//Compute totalScore of each student
For every rows i from 0 to 5
totalScore of ith record=midScore of ith record + totalScore of ith record
//Sort records based on totalScore

For every rows i from 0 to 5


For every rows j from i to 5
If(totalScore of ith record is less than totalScore of jth record)
Swap the values
//display values of array elements
For every rows i from 0 to 5
Taye Alemneh
57
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

display id, name, midScore and FinalScore of ith record


End

Program

#include <iostream.h>
#include <iomanip.h>
#include <string.h>

struct student{
int stnumber;
char stname[20];
float mid;
float final;
float total;
};

void main()
{
student stud[5];
//input
for(int i=0;i<5;i++)
{
cout<<"enter "<<(i+1)<<"th student information\n";
cout<<"enter student number: ";
cin>>stud[i].stnumber;
cout<<"enter student name: ";
cin>>stud[i].stname;
cout<<"enter mid: ";
cin>>stud[i].mid;
cout<<"enter final: ";
cin>>stud[i].final;
stud[i].total=stud[i].mid + stud[i].final;

}
//sort records by result
for( i=0;i<5;i++)
for(int j=i+1;j<5;j++)
if (stud[i].total> stud[j].total)

{
int tem=stud[i].stnumber;
stud[i].stnumber=stud[j].stnumber;
stud[j].stnumber=tem;

char tempName[20];
strcpy(tempName,stud[i].stname);
strcpy(stud[i].stname,stud[j].stname);
strcpy(stud[j].stname,tempName);

float temp=stud[i].total;
stud[i].total=stud[j].total;
Taye Alemneh
58
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

stud[j].total=temp;

temp=stud[i].mid;
stud[i].mid=stud[j].mid;
stud[j].mid=temp;

temp=stud[i].final;
stud[i].final=stud[j].final;
stud[j].final=temp;
}

//display

cout<<setw(5)<<"id"<<setw(15)<<"name"<<setw(8)<<"mid"<<setw(8)<<"final"<<setw(8)
<<"total\n";
for( i=0;i<5;i++)
{
cout<<setw(5)<<stud[i].stnumber
<<setw(15)<<stud[i].stname
<<setw(8)<<stud[i].mid
<<setw(8)<<stud[i].final
<<setw(8)<<stud[i].total<<endl;
}
}

Sample Inout/Output

Taye Alemneh
59
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Record/Structure II
Objective
Students will use structure store and process records

Prerequisite
Students should revise C++ structure.

Important points to be remembered


 Computation:
o Compute total value for each records and find the record with smallest total
values
o Compute total value for each records and find the record with largest total values
o Compute total value for each records and convert total value to letter grade based
on given scale.

Task 17. Write a C++ program to accept records of 5 students. The information of each
student contains ID, Name, mid-term score, final score, and total score. Your program
should show student who gets the max total score and student who gets the min total
score
Algorithm

Begin
//accept values of array elements
For every rows i from 0 to 5
Accept id, name, midScore and FinalScore of ith record
//Compute totalScore of each student
For every rows i from 0 to 5
totalScore of ith record=midScore of ith record + totalScore of ith record
//Find a record with max and min totalScore
Assume 0th record has max totalScore and min totalScore
=>maxIndex=0 and minIndex=0;
For every rows i from 1 to 5
begin
If(totalScore of a record at maxIndex is less than totalScore ith record) then
maxIndex=i;
Taye Alemneh
60
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

If(totalScore of a record at maxIndex is greater than totalScore ith record) then


minIndex=i;
end

//display records with max and min totalScore


Display id, name and sex of record at maxIndex position
Display id, name and sex of record at maxIndex position
End

Program
#include <iostream.h>

struct student{
int stnumber;
char stname[20];
float mid;
float final;
float total;
};

void main()
{
student stud[5];
int maxIndex=0;
int minIndex=0;

//input
for(int i=0;i<5;i++)
{
cout<<"enter "<<(i+1)<<"th student information\n";
cout<<"enter student number: ";
cin>>stud[i].stnumber;
cout<<"enter student name: ";
cin>>stud[i].stname;
cout<<"enter mid: ";
cin>>stud[i].mid;
cout<<"enter final: ";
cin>>stud[i].final;
stud[i].total=stud[i].mid + stud[i].final;
}

//find records with max and min result


for( i=1;i<5;i++){
if (stud[minIndex].total> stud[i].total)
minIndex=i;
if (stud[maxIndex].total< stud[i].total)
maxIndex=i;

}
Taye Alemneh
61
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

cout<<"The record with max result\n";

cout<<"\nid="<<stud[maxIndex].stnumber<<"\nname="
<<stud[maxIndex].stname
<<"\nmid="<<stud[maxIndex].mid
<<"\nfinal="<<stud[maxIndex].final
<<"\ntotal="<<stud[maxIndex].total;

cout<<"The record with min result\n";

cout<<"\nid="<<stud[minIndex].stnumber

<<"\nname="<<stud[minIndex].stname
<<"\nmid="<<stud[minIndex].mid
<<"\nfinal="<<stud[minIndex].final
<<"\ntotal="<<stud[minIndex].total;
}

Sample Input/Output

Task 18. Write a C++ program to accept records of 5 students. The information of each
student contains ID, Name, GPA and information about three courses that each student is
registered for. Information of each course contains course title, credit, mid-term score,
final score, and total score, and letter Grade. Your program should convert total score of
each course to letter grade based on given grade scale and compute semester GPA of
each student.(Assume the curriculum is conventional)

Taye Alemneh
62
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Algorithm

Begin
//accept values of array elements
For every rows i from 0 to 5
Begin
Accept id, name of ith record
For ever rows j from 0 to 3
Accept courseTitle, credit, midScore, finalScore
End

//Compute totalScore and letterGrade of each student


For every rows i from 0 to 5
Begin
For ever rows j from 0 to 3
Begin
compute totalScore
compute letterGrade based on any arbitrary scale
end
Compute Gpa
end

Taye Alemneh
63
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

//display records
For every rows i from 0 to 5
Begin
Display id, name,gpa of ith student record
For ever rows j from 0 to 3
Display courseTitle, credit, midScore, finalScore, totalScore, letterGrade of
jth course record

End
End

Programming

#include <iostream.h>
#include <iomanip.h>

struct course{
char title[20];
int credit;
char grade;
float total;
};

struct student{
int stnumber;
char stname[20];
course cours[3];
float gpa;
};

int getGradePoint(char grade)


{
if(grade=='A')
return 4;
else if(grade=='B')
return 3;
else if(grade=='C')
return 2;
else if(grade=='D')
return 1;

Taye Alemneh
64
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

else
return 0;
}

void main()
{

Taye Alemneh
65
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

student stud[5];

//input
for(int i=0;i<5;i++)
{
cout<<"enter "<<(i+1)<<"th student information\n";
cout<<"enter student number: ";
cin>>stud[i].stnumber;
cout<<"enter student name: ";
cin>>stud[i].stname;

for(int j=0;j<3;j++)
{
cout<<"enter course title: ";
cin>>stud[i].cours[j].title;
cout<<"enter course credit: ";
cin>>stud[i].cours[j].credit;
cout<<"enter course mark: ";
cin>>stud[i].cours[j].total;
}

//convert numeric grade to letter grade

for( i=1;i<5;i++){
for(int j=0;j<3;j++)
{
if(stud[i].cours[j].total>=90)
stud[i].cours[j].grade='A';
else if(stud[i].cours[j].total>=75)
stud[i].cours[j].grade='B';
else if(stud[i].cours[j].total>=50)
stud[i].cours[j].grade='C';
else if(stud[i].cours[j].total>35)
stud[i].cours[j].grade='D';
else
stud[i].cours[j].grade='F';

//compute GPA for each student

for( i=1;i<5;i++){
float gradePoint=0;
int totalCredit=0;
for(int j=0;j<3;j++)
{
if(stud[i].cours[j].grade=='A')
gradePoint=gradePoint +
stud[i].cours[j].credit*getGradePoint('A');
Taye Alemneh
66
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

else if(stud[i].cours[j].grade=='B')
gradePoint=gradePoint +
stud[i].cours[j].credit*getGradePoint('B');
else if(stud[i].cours[j].grade=='C')
gradePoint=gradePoint +
stud[i].cours[j].credit*getGradePoint('C');
else if(stud[i].cours[j].total=='D')
gradePoint=gradePoint +
stud[i].cours[j].credit*getGradePoint('D');
totalCredit=totalCredit+stud[i].cours[j].credit;

stud[i].gpa=gradePoint/totalCredit;

//Display students infomation

for( i=1;i<5;i++){cout<<"\nID:

"<<stud[i].stnumber<<" Name:

"<<stud[i].stname<<endl;

cout<<setw(15)<<"Title"<<setw

(10)<<"Credit"

<<setw(10)<<"Total"<<setw(10)<<"Grade"<<endl;
for(int j=0;j<3;j++)
{
cout<<setw(15)<<stud[i].cours[j].title
<<setw(10)<<stud[i].cours[j].credit
<<setw(10)<<stud[i].cours[j].total
<<setw(10)<<stud[i].cours[j].grade<<endl;
}
cout<<"\nGPA: "<<stud[i].gpa<<endl;

Taye Alemneh
67
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Record/Structure III
Objective
Students will use structure store and process records

Prerequisite
Students should revise C++ structure.

Important points to be remembered


 Computation:
o Accept a record and insert the record at a given index
o Delete a record at a given index

Task 19. Write a C++ program to accept records of 5 students. The information of each
student contains ID, Name, mid-term score and final score. Your program should accept
one additional student record and insert the new record at 3rd index. Finally, you should
display total records.

Algorithm

Begin
//accept values of array elements

For every rows i from 0 to 5


Begin
Taye Alemneh
68
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Accept ID, Name, midScore and finalScore of ith record


End
//accept new record to be inserted
Accept ID, Name, midScore and finalScore of new record
Shift all records after the 3rd index to the right
Put the new record at 3rd position

//display records
For every rows i from 0 to 6
Display ID, Name, midScore and finalScore ith student record
End

Program
#include <iostream.h>
#include <iomanip.h>

struct student{
int stnumber;
char stname[20];
float mid;
float final;
};
void main()
{
student stud[6];

//input
for(int i=0;i<5;i++)
{
cout<<"enter "<<(i+1)<<"th student information\n";
cout<<"enter student number: ";
cin>>stud[i].stnumber;
cout<<"enter student name: ";
cin>>stud[i].stname;
cout<<"enter mid result: ";
cin>>stud[i].mid;
cout<<"enter final result: ";
cin>>stud[i].final;
}
//input the new record
cout<<"enter the new record to be inserted\n";
student studNew;
cout<<"enter student number: ";
cin>>[Link];
cout<<"enter student name: ";
cin>>[Link];
Taye Alemneh
69
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

cout<<"enter mid result: ";


cin>>[Link];
cout<<"enter final result: ";
cin>>[Link];

//shift elements of the array to the right after the 3rd position
for( i=5;i>3;i--){
stud[i]=stud[i-1];
}
//insert the new record in 3rd index
stud[3]=studNew;
//Display students infomation
cout<<setw(10)<<"ID"<<setw(20)<<"Name"
<<setw(10)<<"Mid"<<setw(10)<<"Final"<<endl;
for( i=0;i<6;i++){
cout<<setw(10)<<stud[i].stnumber
<<setw(20)<<stud[i].stname
<<setw(10)<<stud[i].mid
<<setw(10)<<stud[i].final<<endl;
}

Sample Input/Output

Task 20. Write a C++ program to accept records of 5 students. The information of each
student contains ID, Name, mid-term score, and final score. Your program should delete
3rd student record. Finally, you should display the final records.

Algorithm
Begin
Taye Alemneh
70
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

//accept values of array elements


For every rows i from 0 to 5
Begin
Accept ID, Name, midScore and finalScore of ith record
End
Shift all records after the 3rd index to the left

//display records
For every rows i from 0 to 4
Display ID, Name, midScore and finalScore ith student record
End

Program
#include <iostream.h>
#include <iomanip.h>

struct student{
int stnumber;
char stname[20];
float mid;
float final;
};

void main()
{
student stud[5];

//input
for(int i=0;i<5;i++)
{
cout<<"enter "<<(i+1)<<"th student information\n";
cout<<"enter student number: ";
cin>>stud[i].stnumber;
cout<<"enter student name: ";
cin>>stud[i].stname;
cout<<"enter mid result: ";
cin>>stud[i].mid;
cout<<"enter final result: ";
cin>>stud[i].final;
}

//shift elements of the array to the left after the 3rd position
for( i=2;i<5;i++){
stud[i]=stud[i+1];
}
//Display students infomation
Taye Alemneh
71
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

cout<<setw(10)<<"ID"<<setw(20)<<"Name"
<<setw(10)<<"Mid"<<setw(10)<<"Final"<<endl;
for( i=0;i<4;i++){
cout<<setw(10)<<stud[i].stnumber
<<setw(20)<<stud[i].stname
<<setw(10)<<stud[i].mid
<<setw(10)<<stud[i].final<<endl;
}

Taye Alemneh
72
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Output

Linked List/Pointer-I
Objective
Students will use pointers and linked list store and values of the same data type.

Important points to be remembered


 Computation and declaration:
o Declaration of pointer and linked list: Students will see how to declare pointer and
linked list.
o Students will use pointer to access elements of an array.
o Students will use single listed list to store multiple values of the same data type.

Task 21. Write a program that prints the values from an array using pointer variable. The
array is given below
int y [4]= {6,2,3,12};

Taye Alemneh
73
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Algorithm
Declare pointer variable p
Assign an array to p;
//display elements
For each row i from 0 to 4
Display *(p+i)

Program
#include <iostream.h>

void main()
{
int n[] ={6,2,3,12};
int *p;
p=n;
for(int i=0;i<4;i++)
{
cout<<*(p+i)<<endl;
}
}
Sample input and output

Task 22. Write a program that display only 6th element of an array given below using
pointers.
int y [10] ={11,22,33, 44,55,66,77,88,99,110}

Taye Alemneh
74
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Algorithm
Declare pointer variable p
Assign an array to p;
//display elements
Display *(p+5)

Program
#include <iostream.h>

void main()
{
int n[] ={6,2,3,12};
int *p;
p=n;
cout<<*(p+5)<<endl;
}

Sample input and output

Task 23. Write a C++ program to accept five integer values from keyword. The five values
will be stored in an array using a pointer. Then print the elements of the array on the screen.
Algorithm
Declare pointer variable p
Assign an array to p;
//accept elements
For each row i from 0 to 5
accept *(p+i)
//display elements
For each row i from 0 to 5
display *(p+i)

Taye Alemneh
75
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Program
#include<iostream.h>

void main()
{
int arr[5];
int *p=arr;
cout<<"Enter five numbers separated by space:";
for(int i=0;i<5;i++)
cin>>*(p+i);
cout<<"\nYour numbers are(accessed using index of array):\n";
for(i=0;i<5;i++)
cout<<arr[i]<<" ";
cout<<"\nYour numbers are(access using pointer):\n";
for(i=0;i<5;i++)
cout<<arr[i]<<" ";
}

Sample input and output

Task 24. Accept and store 5 integers in a single linked list. Print the numbers on the screen.

Algorithm
Declare linked list variable ll
//accept elements
For each row i from 0 to 5
accept integer values of ith linked list variable
//display elements
For each row i from 0 to 5

Taye Alemneh
76
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

display integer values of ith linked list variable


Program
#include<iostream.h>
struct node {
int data;
node *next;
};

void main()
{
node *root=NULL,*last,*current;
int n;
cout<<"\nenter five numbers:-\n";
for(int i=0;i<5;i++)
{
cin>>n;
current = new node;
current->data=n;
current->next=NULL;
if(root==NULL)
{
root=current;
last=current;
}
else{
last->next=current;
last= current ;
}
}
node *nd;
nd=root;
cout<<"Linked list node are:";
while(nd!=NULL)
{
cout<<nd->data<<" ";
nd=nd->next;
}
}
Sample input and output

Taye Alemneh
77
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Linked List/Pointer-II
Objective
Students will use linked list to manipulate values of the same data type

Prerequisite
Students should revise linked list.
Important points to be remembered
 Computation:
o Students will type code used to search a value in a linked list values
o Students will type code used to accept multiple values using linked list variable
and display the values
Task 25. Accept 5 integers and one key from the user and searches the key from the five
numbers.
Algorithm

Declare linked list variable ll


//accept elements
For each row i from 0 to 5
accept integer values of ith linked list variable
//accept a key

Accept key
//search the key
Found=0
For each row i from 0 to 5
Begin
If(key is equal to values of ith linked list variable) then
Found=1
End
If(found=1) then
Display found
Else

Display not found


Taye Alemneh
78
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Program
#include<iostream.h>
struct node {
int data;
node *next;
};

void main()
{
node *root=NULL,*last,*current;
int n,key;
cout<<"\nenter five numbers:-\n";
for(int i=0;i<5;i++)
{
cin>>n;
current = new node;
current->data=n;
current->next=NULL;
if(root==NULL)
{
root=current;
last=current;
}
else{

Taye Alemneh
79
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

last->next=current;
last= current ;
}
}
cout<<"\nenter the key to be searched:\n";

cin>>key;
node *curr;
curr=root;
int flag=0;
while(curr!=NULL)
{
if(curr->data==key)
{
flag=1;
break;
}
curr=curr->next;
}
if(flag==1)
cout<<"key is found";
else
cout<<"key is not found";
}

Taye Alemneh
80
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Sample input and output


Sample 1 Sample 2

Task 26. Holds information of five student (first name, last name, id, gpa) using single
linked list and displays student lists.

Algorithm
Declare linked list variable ll
//accept elements

For each row i from 0 to 5


accept first name, last name, id and gpa of ith linked list variable
//display elements
For each row i from 0 to 5
display first name, last name, id and gpa of ith linked list variable

Program
#include<iostream.h>
#include <iomanip.h>
Taye Alemneh
81
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

struct student {
char fname[30], lname[30];
int id;
float gpa;
student *next;
};

void main()
{
student *root=NULL,*last,*current;

//accepts information of five students


for(int i=0;i<5;i++)
{
current = new student;
cout<<"enter "<<(i+1)<<"th student's first name: ";
cin>>current->fname;
cout<<"enter "<<(i+1)<<"th student's last name: ";
cin>>current->lname;
cout<<"enter "<<(i+1)<<"th student's id: ";
cin>>current->id;
cout<<"enter "<<(i+1)<<"th student's gpa: ";
cin>>current->gpa;
current->next=NULL;
if(root==NULL)
{
root=current;
last=current;
}
else{

Taye Alemneh
82
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

last->next=current;
last= current ;
}
}
//display information of five students
student *curr;
curr=root;
cout<<setw(20)<<"first name"<<setw(20)<<"last
name"<<setw(5)<<"id"<<setw(5)<<"gpa\n"; while(curr!=NULL)
{
cout<<setw(20)<<curr->fname<<setw(20)<<curr->lname<<setw(5)<<curr-
>id<<setw(5)<<curr->gpa<<endl; curr=curr->next;
}
}
Sample input and output

Taye Alemneh
83
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Recursion -I
Objective
Students will use recursive function.

Prerequisite
Students should revise C++ function.

Important points to be remembered


 Computation:
o Define recursive function to make computation in recursive manner.

Task 27. Write a recursive function that accepts a number n and computes 3

Algorithm
//assum name of the function is comput
If(n is equal to 0)
Return 1
Other wise

Return 3*comput(n-1);

Program
#include <iostream.h>

int computePower(int n);

void
main(){ int
n;
cout<<"Enter an integer: ";
cin>>n;
cout<<"Power of the number is "<<computePower(n);
}
int computePower(int
n){ if(n==0 )
return 1;
if( n==1)
return 3;

return 3*computePower(n-1);

Taye Alemneh
84
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Sample input and output

Task 28. Write a recursive function that accepts a number n and computes number of
digits.

Algorithm
//assum name of the function is countDigit
if(n divided by ten is zero)
return 1
other wise
return 1+countDigit(n/10)

Program
#include <iostream.h>

int countDigit(int n);

void main(){
int n;
cout<<"Enter an integer: ";
cin>>n;
cout<<"number of digits of the number is "<<countDigit(n);

}
int countDigit(int
n){ if(n/10==0 )
return 1;
return 1 + countDigit(n/10);
}
Sample input and output

Taye Alemneh
85
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Task 29. Write a recursive function that accepts a number n and computes nth Fibonacci sequence.

Algorithm
//assume name of the function is fibo
int fib0 = 0, fib1 = 1;
for i = 2 to n
begin
tmp = fib0;
fib0 = fib1;
fib1 = tmp + fib1;
end
return fibo1
Program
#include <iostream.h> int fibonacci(int

n); void main(){

int n;

cout<<"Enter an integer: ";


cin>>n;
cout<<"List of fibonacci number <= "<<n<<" are\n";
for(int i=0;i<=n;i++)
cout<<fibonacci(i)<<",";
}
int fibonacci(int n)
{

if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
return fibonacci(n-1) + fibonacci(n-2);
}
Sample input and output

Taye Alemneh
86
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Recursion -II
Objective
Students will use recursive function.
Prerequisite
Students should revise C++ function.

Important points to be remembered


 Computation:
o Define recursive function to make computation in recursive manner.

Task [Link] a recursive function to calculate and return the factorial of any positive integer
number.
Algorithm

//assum name of the function is fact


If(n=0 or n=1) then
Return 1
Return n*fact(n-1)
Program
#include <iostream.h>

int factorial(int n);

void main(){
int n;
cout<<"Enter an integer: ";
cin>>n;
cout<<"factorial of the number is "<<factorial(n);

}
int factorial(int
n){ if(n==0 || n==1 )
return 1;
return n* factorial(n-1);
}

Sample input and output

Taye Alemneh
87
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Task [Link] a recursive C++ function to calculate and return the sum of the following series
then call your function from the main.
Sum=1+2+3+….+N

Algorithm
//assume name of the function is compute
if(n is 0) then
return 1
other wise
return n+ compute(n-1)
Program
#include <iostream.h>

int sum(int n);

void
main(){ int
n;
cout<<"Enter an integer: ";
cin>>n;
cout<<"sum of the numbers less the given number is "<<sum(n);

}
int sum(int
n){ if(n==0 )
return 0;
return n + sum(n-1);
}

Taye Alemneh
88
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Recursion -III
Objective
Students will use recursive function.

Prerequisite
Students should revise C++ function.

Important points to be remembered


 Computation:
o Define recursive function to make computation in recursive manner.

Task 32. Write a C++recursive function to calculate. X*Y (the multiplication of X by Y


where X,Y are integers)

Algorithm
//assume name of the function is compute
if(y is 0) then
return 0
else if ( y is 1) then
return x;
other wise
return x * compute(y-1)

Program
#include <iostream.h>
int compute(int x,int y);
void main(){
int x,y;
cout<<"\nenter two numbers\n";
cin>>x>>y;
cout<<"result="<<compute(x,y);
}
int compute(int x,int
y){ if(y==0)
return 0;
else if(y==1)
return x;

return x*compute(x,y-1);
}
Taye Alemneh
89
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Sample input/output

Task 33. Write a recursive C++ function to calculate the same of multiple of five less than the input
number n: 5+10+15+…+

Algorithm
//assume name of the function is compute
if(n is less than 5) then
return 0
else if ( the remainder when n is divided by 5 is 0) then
return n + compute(n-1);
other wise
return compute(y-1)

Program
#include <iostream.h>
int compute(int n);
void main(){
int n;
cout<<"\nenter number\n";
cin>>n;
cout<<"result="<<compute(n);
}
int compute(int
n){ if(n<5)
return 0;
else if(n%5==0)
return n+compute(n-1);
return compute(n-1);
}
Sample input and output

Taye Alemneh
90
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

File I/O -I
Objective
Students will use write a code to read and write data to/from a file on hard disk.

Important points to be remembered


 Computation:
o Store computed value on hard disk
o Copy content of a file to other file
o Count occurrence of a character in a file

Task 34. Write a program that accepts a number and store the square of the number in a file
named [Link] and located in C:\.

Algorithm
Accept a number n from key board
Compute square of n and store on sq
Write the result on a file
Program
#include <iostream.h>
#include <fstream.h>
void main(){
int n,square;
ofstream out("c:\\[Link]"); cout<<"enter number"; cin>>n;
square=n*n;
out<<"The square of "<<n<<" is "<<square;
cout<<"the output is store on the file successfully!";
//open c:\[Link] to see the out output
}

Sample input and output


Console output

Taye Alemneh
91
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

File output

Task 35. Write a program that copies content of a file named [Link] and append at the
end of content of another file named [Link]. Both the source and destination files
are located in C:\.

#include <iostream.h> #include <fstream.h>

void main(){ int n;


ifstream in("c:\\[Link]"); //create [Link] at c:\ before compilation ofstream
out("c:\\[Link]",ios::app);
char str[100]; while(![Link]()) {
[Link](str,100);

out<<str;
}
cout<<"content copied successfully!!";
}

Sample input and output


open the file c:\\[Link] and check whether the content of c:\\[Link] is copied
or not

Task 36. Write a program, which returns size of the file in bytes.

Algorithm
Initialize size=0;
While (not end of file)
Begin
Read character c from the file
size=size+1
End
Display size
Taye Alemneh
92
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Program
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h> // exit function prototype

void
main(){ int
n;
ifstream in("c:\\[Link]");
if ( !in ) { // exit program if unable to create file
cerr << "File could not be opened" << endl;
exit( 1 );
} // end if
int count=0;
while(![Link]()){
char ch;
[Link](ch);
count++;
}
cout<<"the file has "<<count<<" character ";
}

Sample input and output

Taye Alemneh
93
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Task 37. Write a program that opens a file and counts the whitespace-separated words in
that file.

Algorithm
Initialize count=0
While( not end of file){
Read a character c from file
If(c is space) then
Count=count +1
}
Display count

Taye Alemneh
94
Software Engineering
FUNDAMENTALS OF PROGRAMMING II

Program

#include <iostream.h> #include <fstream.h>


#include <stdlib.h> // exit function prototype

void main(){
int n;

ifstream in("e:\\[Link]");
if ( !in ) { // exit program if unable to create file
cerr << "File could not be opened" << endl;
exit( 1 );
} // end if
int count=1;
while(![Link]()){
char ch;
[Link](ch);
if(ch==' ')
count++;
}
cout<<"the file has "<<count<<" words ";
}
Sample input and output

End Of File

Taye Alemneh
95

You might also like