Professional Documents
Culture Documents
Laboratory Manual
2007E.C
Bahir Dar University
School of Computing
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
To launch the IDE for C++, choose Programming from the Public menu on the Windows taskbar
then choose Borland C++ from the ++ Compiler option.
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.
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 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
The following user interface is displayed when you clicked file menu.
2. Click New
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ݖ
Flow chart
In addition to typing detail C++ codes of the above algorithm, you need to do the following task
Step-2:- declare 4 float variables in order to hold three inputs and one output value
ଶ௫ାඥ௬ మ ାସ௫௬
= ݐ݈ݑݏ݁ݎ ଶ௭
result=(numerator)/(denominator)
result=(2*x + sqrt(y*y-4*x*y))/(2*z);
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
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
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;
}
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
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
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";
}
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
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
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
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;
}
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
Flow chart
start
i=0
sum=0
i<5
j<5
average=sum/5
sum=sum+j
display sum
and average
j=j+1
end
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;
}
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
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";
cin>>n[i];
}
//assume the fisrt element is smallest number
min=n[0];
}
//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
Flow chart
Program
#include <iostream.h>
void main(){
int n[10],min=0;
cout<<"\nEnter 10 integers\n";
if(n[j]<n[i]){
int temp=n[i];
n[i]=n[j];
n[j]=temp;
}
}
}
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)
Flow chart
Program
#include <iostream.h>
void main(){
int mid[5],final[5],total[5];
char grade[5];
cout<<"\nEnter 5 integers\n";
grade[i]='D';
else
grade[i]='F';
}
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.
• 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
Program
#include <iostream.h>
void main(){
int m1[2][2],m2[2][2],sum[2][2],min=0;
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];
}
for(int j=0;j<2;j++)
cout<<m1[i][j]<<" ";
cout<<endl;
}
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
#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
Week 4 String-I
Objective
Students will use two dimensional arrays to store and process list of names
Prerequisite
Students should revise array.
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];
//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);
}
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
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;
Week5 Record/Structure I
Objective
Students will use structure to store multiple values of different data type.
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
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;
}
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
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;
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
Week 6 Record/Structure II
Objective
Students will use structure store and process records
Prerequisite
Students should revise C++ structure.
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;
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;
}
cout<<"\nid="<<stud[maxIndex].stnumber<<"\nname="
<<stud[maxIndex].stname
<<"\nmid="<<stud[maxIndex].mid
<<"\nfinal="<<stud[maxIndex].final
<<"\ntotal="<<stud[maxIndex].total;
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
//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;
};
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;
}
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';
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;
for( i=1;i<5;i++){
Prerequisite
Students should revise C++ structure.
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
//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;
//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
//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
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;
}
Output
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};
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
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;
}
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)
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]<<" ";
}
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
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
Prerequisite
Students should revise linked list.
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
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";
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";
}
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
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;
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;
}
}
Week 10 Recursion -I
Objective
Students will use recursive function.
Prerequisite
Students should revise C++ function.
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>
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)
Program
#include <iostream.h>
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>
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;
}
Prerequisite
Students should revise C++ function.
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>
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
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>
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);
}
Prerequisite
Students should revise C++ function.
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);
}
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);
}
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;
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
}
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);
out<<str;
}
cout<<"content copied successfully!!";
}
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 ";
}
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;
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