You are on page 1of 76

Bahir Dar University

Bahir Dar Institute of Technology


School of Computing

Laboratory Manual

Course title: Fundamentals of Programming II

Prepared By: Mekonnen Fentaw

Reviewed By: Sefi Gebeyehu

2007E.C
Bahir Dar University

Bahir Dar Institute of Technology

School of Computing

Approval Certification of the Reviewer

I have certified and approved Fundamental of Programming laboratory manual prepared by


Mekonnen Fentaw. As I have reviewed and commented the manual it carries out the objectives,
tasks, exercises and completes practical parts of the course and fulfills the standard of the
curriculum of the course.

Sefi Gebeyehu ____________________ ________________

Name Signature Date


Contents
Objectives ..................................................................................................................................................... 5
Introduction ................................................................................................................................................... 1
Week 1: Fundamental Programming I Revision............................................................................................ 5
Objective ................................................................................................................................................... 5
Prerequisite ............................................................................................................................................... 5
Expression evaluation ............................................................................................................................... 5
Condition evaluation................................................................................................................................. 9
Loops ....................................................................................................................................................... 13
Week 2 Array-I ............................................................................................................................................ 15
Objective ................................................................................................................................................. 15
Prerequisite ............................................................................................................................................. 15
Week3 Array-II ............................................................................................................................................ 23
Objective ................................................................................................................................................. 23
Prerequisite ............................................................................................................................................. 23
Week 4 String-I............................................................................................................................................ 28
Objective ................................................................................................................................................. 28
Prerequisite ............................................................................................................................................. 28
Important points to be remembered...................................................................................................... 28
Week5 Record/Structure I .......................................................................................................................... 32
Objective ................................................................................................................................................. 32
Important points to be remembered...................................................................................................... 32
Week 6 Record/Structure II ........................................................................................................................ 37
Objective ................................................................................................................................................. 37
Prerequisite ............................................................................................................................................. 37
Important points to be remembered...................................................................................................... 37
Week 7 Record/Structure III ....................................................................................................................... 44
Objective ................................................................................................................................................. 44
Prerequisite ............................................................................................................................................. 44
Important points to be remembered...................................................................................................... 44
Week 8 Linked List/Pointer-I ....................................................................................................................... 49
Objective ................................................................................................................................................. 49
Important points to be remembered...................................................................................................... 49
Week 9 Linked List/Pointer-II ...................................................................................................................... 54
Objective ................................................................................................................................................. 54
Prerequisite ............................................................................................................................................. 54
Important points to be remembered...................................................................................................... 54
Week 10 Recursion -I .................................................................................................................................. 59
Objective ................................................................................................................................................. 59
Prerequisite ............................................................................................................................................. 59
Important points to be remembered...................................................................................................... 59
Week 11 Recursion -II ................................................................................................................................. 62
Objective ................................................................................................................................................. 62
Prerequisite ............................................................................................................................................. 62
Important points to be remembered...................................................................................................... 63
Week 12 Recursion -III ................................................................................................................................ 64
Objective ................................................................................................................................................. 64
Prerequisite ............................................................................................................................................. 65
Important points to be remembered...................................................................................................... 65
Week 13 File I/O -I ...................................................................................................................................... 67
Objective ................................................................................................................................................. 67
Important points to be remembered...................................................................................................... 67
Objectives
After successful completion of this laboratory exercises, students will be able to

1. Develop algorithms for solving simple problems.


2. Use Borland 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 files
FUNDAMENTALS OF PROGRAMMING II

Introduction

Borland C++ provides an environment for writing and running C and C++ programs and for
creating DOS and Windows applications using these languages. The environment is called an
Integrated Development Environment or IDE

Starting The IDE

To launch the IDE for C++, choose Programming from the Public menu on the Windows taskbar
then choose Borland C++ from the ++ Compiler option.

The initial screen should appear like this:

Across the top of the window is the title bar with the minimize, maximize and close buttons on
the right-hand side. Under the title bar are eleven menus.

The File, Edit and Search menus have all the usual Windows options, whilst the other menus
contain options specific to the C++ environment.

At the bottom of the screen is an information bar that provides information on the current
operation and displays the cursor position as line and column number.

PREPARED BY MEKONNEN FENTAW


1
FUNDAMENTALS OF PROGRAMMING II

The Menus

The File menu provides commands for creating new files, opening existing files, saving, printing
and exiting the C++ environment.

The Edit menu provides the usual cut, copy, paste and clipboard commands.

The Search menu allows you to find and replace text and to search for objects and symbols in the
program you are editing.

The View menu allows you to view a number of windows containing program and environment
information.

The Project menu is for the manipulation of project files and control of all aspects of a project,
allowing you to compile all or part of a program.

The Script menu provides facilities for creating, managing and running program scripts

The Tool menu allows you to run other programs, tools and utilities useful in the development of
Windows applications, without leaving the IDE.

The Debug menu provides commands for running and debugging programs.

The Options menu allows you to edit project and environment settings and save them to a
configuration file.

The Window menu contains window management commands and selections.

The Help menu gives you access to on-line help including programming syntax, examples and
library information.

Pointing to a menu option and holding down the mouse button displays a description in the
information bar at the bottom of the screen

PREPARED BY MEKONNEN FENTAW


2
FUNDAMENTALS OF PROGRAMMING II

How to start Borland C++

• Start Borland C++


1. Click start button
2. click All Programs
3. select Borland C++ 4.5
You will see the following user interface.

4. click Borland C++

How to compile and test C++ program?

To compile : click Project menuclick Compile or Alt +F9


To run:-click Debug menu click Run Or Ctrl + F9

PREPARED BY MEKONNEN FENTAW


3
FUNDAMENTALS OF PROGRAMMING II

How to open new code editor?

1. Click File menu

The following user interface is displayed when you clicked file menu.

2. Click New

PREPARED BY MEKONNEN FENTAW


4
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‫ ݔ‬+ ඥ‫ ݕ‬ଶ + 4‫ݕݔ‬
‫= ݐ݈ݑݏ݁ݎ‬
2‫ݖ‬

PREPARED BY MEKONNEN FENTAW


5
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

ଶ௫ାඥ௬ మ ାସ௫௬
‫= ݐ݈ݑݏ݁ݎ‬ ଶ௭
result=(numerator)/(denominator)

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

Step-5:- display the final output

PREPARED BY MEKONNEN FENTAW


6
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

PREPARED BY MEKONNEN FENTAW


7
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

PREPARED BY MEKONNEN FENTAW


8
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

PREPARED BY MEKONNEN FENTAW


9
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

PREPARED BY MEKONNEN FENTAW


10
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

PREPARED BY MEKONNEN FENTAW


11
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

PREPARED BY MEKONNEN FENTAW


12
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

PREPARED BY MEKONNEN FENTAW


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

PREPARED BY MEKONNEN FENTAW


14
FUNDAMENTALS OF PROGRAMMING II

Sample input output

Week 2 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

PREPARED BY MEKONNEN FENTAW


15
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

PREPARED BY MEKONNEN FENTAW


16
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

PREPARED BY MEKONNEN FENTAW


17
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

j<10 Yes

average=sum/5
min<a[j] No

display sum
Yes
and average

min=a[j]
end j=j+1

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++){

PREPARED BY MEKONNEN FENTAW


18
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


19
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++){

PREPARED BY MEKONNEN FENTAW


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

PREPARED BY MEKONNEN FENTAW


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

PREPARED BY MEKONNEN FENTAW


22
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

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

PREPARED BY MEKONNEN FENTAW


23
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


24
FUNDAMENTALS OF PROGRAMMING II

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

//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++){

PREPARED BY MEKONNEN FENTAW


25
FUNDAMENTALS OF PROGRAMMING II

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

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

PREPARED BY MEKONNEN FENTAW


26
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


27
FUNDAMENTALS OF PROGRAMMING II

}
}
Sample input and output

Week 4 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
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.

PREPARED BY MEKONNEN FENTAW


28
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


29
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

PREPARED BY MEKONNEN FENTAW


30
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(name[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 ;

PREPARED BY MEKONNEN FENTAW


31
FUNDAMENTALS OF PROGRAMMING II

//reverse the name and display results


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

Week5 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

PREPARED BY MEKONNEN FENTAW


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

PREPARED BY MEKONNEN FENTAW


33
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

PREPARED BY MEKONNEN FENTAW


34
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


35
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


36
FUNDAMENTALS OF PROGRAMMING II

Sample Inout/Output

Week 6 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.

PREPARED BY MEKONNEN FENTAW


37
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


38
FUNDAMENTALS OF PROGRAMMING II

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;

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

PREPARED BY MEKONNEN FENTAW


39
FUNDAMENTALS OF PROGRAMMING II

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)

Algorithm

Begin
//accept values of array elements
For every rows i from 0 to 5
Begin
Accept id, name of ith record

PREPARED BY MEKONNEN FENTAW


40
FUNDAMENTALS OF PROGRAMMING II

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

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

PREPARED BY MEKONNEN FENTAW


41
FUNDAMENTALS OF PROGRAMMING II

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;
else
return 0;
}

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;

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

PREPARED BY MEKONNEN FENTAW


42
FUNDAMENTALS OF PROGRAMMING II

//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');
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++){

PREPARED BY MEKONNEN FENTAW


43
FUNDAMENTALS OF PROGRAMMING II

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;

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

PREPARED BY MEKONNEN FENTAW


44
FUNDAMENTALS OF PROGRAMMING II

For every rows i from 0 to 5


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

PREPARED BY MEKONNEN FENTAW


45
FUNDAMENTALS OF PROGRAMMING II

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>>studNew.stnumber;
cout<<"enter student name: ";
cin>>studNew.stname;
cout<<"enter mid result: ";
cin>>studNew.mid;
cout<<"enter final result: ";
cin>>studNew.final;

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

PREPARED BY MEKONNEN FENTAW


46
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


47
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


48
FUNDAMENTALS OF PROGRAMMING II

Output

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

PREPARED BY MEKONNEN FENTAW


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

Algorithm
Declare pointer variable p

PREPARED BY MEKONNEN FENTAW


50
FUNDAMENTALS OF PROGRAMMING II

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)

PREPARED BY MEKONNEN FENTAW


51
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

PREPARED BY MEKONNEN FENTAW


52
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

PREPARED BY MEKONNEN FENTAW


53
FUNDAMENTALS OF PROGRAMMING II

Week 9 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

PREPARED BY MEKONNEN FENTAW


54
FUNDAMENTALS OF PROGRAMMING II

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

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{
last->next=current;
last= current ;
}
}
cout<<"\nenter the key to be searched:\n";

PREPARED BY MEKONNEN FENTAW


55
FUNDAMENTALS OF PROGRAMMING II

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

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

PREPARED BY MEKONNEN FENTAW


56
FUNDAMENTALS OF PROGRAMMING II

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>
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{
last->next=current;
last= current ;
}
}
//display information of five students
student *curr;
curr=root;

PREPARED BY MEKONNEN FENTAW


57
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


58
FUNDAMENTALS OF PROGRAMMING II

Sample input and output

Week 10 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

PREPARED BY MEKONNEN FENTAW


59
FUNDAMENTALS OF PROGRAMMING II

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

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

PREPARED BY MEKONNEN FENTAW


60
FUNDAMENTALS OF PROGRAMMING II

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

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(){

PREPARED BY MEKONNEN FENTAW


61
FUNDAMENTALS OF PROGRAMMING II

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

Week 11 Recursion -II


Objective
Students will use recursive function.

Prerequisite
Students should revise C++ function.

PREPARED BY MEKONNEN FENTAW


62
FUNDAMENTALS OF PROGRAMMING II

Important points to be remembered


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

Task 30. Write 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

PREPARED BY MEKONNEN FENTAW


63
FUNDAMENTALS OF PROGRAMMING II

Task 31. Write 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);
}

Week 12 Recursion -III


Objective
Students will use recursive function.

PREPARED BY MEKONNEN FENTAW


64
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


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

PREPARED BY MEKONNEN FENTAW


66
FUNDAMENTALS OF PROGRAMMING II

Sample input and output

Week 13 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 test.txt 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;

PREPARED BY MEKONNEN FENTAW


67
FUNDAMENTALS OF PROGRAMMING II

ofstream out("c:\\test.txt");
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:\test.txt to see the out output
}

Sample input and output


Console output

File output

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

Algorithm
While not end of the first file
Begin
Copy the content to the second file
End

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

void main(){
int n;
ifstream in("c:\\source.txt"); //create source.txt at c:\ before compilation
ofstream out("c:\\destination.txt",ios::app);
char str[100];
while(!in.eof()) {
in.getline(str,100);

PREPARED BY MEKONNEN FENTAW


68
FUNDAMENTALS OF PROGRAMMING II

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

Sample input and output


open the file c:\\destination.txt and check whether the content of c:\\source.txt 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

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

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

PREPARED BY MEKONNEN FENTAW


69
FUNDAMENTALS OF PROGRAMMING II

Sample input and output

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

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

void main(){
int n;

PREPARED BY MEKONNEN FENTAW


70
FUNDAMENTALS OF PROGRAMMING II

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

PREPARED BY MEKONNEN FENTAW


71

You might also like