Computer-Programming-Lab-Manual
Computer-Programming-Lab-Manual
To install the Microsoft Visual Studio 2012 follows the steps that are shown in the videos on the
e-class.
1
PART 2: Introduction to C++ programming:
Examples
#include<iostream>
using namespace std;
int main()
{
int feet;
cout << "Enter an integer:";
cin >> feet;
cout << endl;
cout << feet <<" Feet = " << 12* feet << " Inches"<<
endl;
system("PAUSE");
return 0;
The output:
Enter an integer:3
3 Feet = 36 Inches
Press any key to continue . . .
2
3. An example of the data types sizes.
#include<iostream>
using namespace std;
int main()
{
cout << "the size of char is:" << sizeof(char) << endl;
cout << "the size of int is:" << sizeof(int) << endl;
cout << "the size float is:" << sizeof(float) << endl;
cout << "the size of double is:" << sizeof(double) << endl;
system("PAUSE");
return 0;
}
The output:
Exercises
3
Solve the following questions:
2. Write a C++ program that reads radius „r‟ and height „h‟ of a cone and computes its
volume.
.
3. Write a C++ program that computes a salary of a part time employee based on:
- Number of days worked.
- Number of hours per day assuming that he worked the same hours every day.
- The hourly wage.
Choose the suitable data type for each variable.
4. Write a program that reads radius and height of a cylinder and computes its volume and
surface area. The surface area is the surface of the 2 circular bases and the surface of the
lateral side.
volume r 2 h surface area 2r r h 2 r 2
4
Lab No. 2: Predefined Functions and Formatting Output
Examples:
Example 1: This example illustrates how to use predefined functions in a program. More
specifically, we use some math functions, from the header file cmath, and the string function
length, from the header file string. Note that the function length determines the length of a string.
Solution code:
#include<iostream>
#include<cmath>
#include<string>
using namespace std;
int main()
{
double u, v;
string str;
cout << "Line1: 2 to the power of 6 = " <<
static_cast<int>(pow(2.0,6.0)) << endl; //Line 1
u = 12.5; //Line 2
v = 3.0; //Line 3
cout << "Line4: " << u << " to the power of " << v << "=" << pow(u,v)
<< endl; //Line 4
cout << "Line5: Square root of 24 = " << sqrt(24.0) << endl; //Line 5
u = pow(8.0,2.5); //Line 6
cout << "Line7: u = " << u << endl; //Line 7
str = "Programming with C++"; //Line 8
cout << "Line9: Length of str =" << str.length() << endl; //Line 9
system("pause");
return 0;
}
Output:
Line1: 2 to the power of 6 = 64
Line4: 12.5 to the power of 3=1953.13
Line5: Square root of 24 = 4.89898
Line7: u = 181.019
Line9: Length of str =20
5
Example 2: This example illustrates how to use the manipulators setprecision, fixed, and
showpoint.
Solution code:
#include<iostream> //Line 1
#include<iomanip> //Line 2
using namespace std; //Line 3
const double PI = 3.14159265; //Line 4
int main()
{
double radius =12.67; //Line 7
double height = 12.00; //Line 8
cout<< fixed << showpoint; //Line 9
cout << setprecision(3) << "Line 10: setprecision(3)" << endl; //Line 10
cout<< "Line 11: radius ="<<radius<<endl; //Line 11
cout<< "Line 12: height ="<<height<<endl; //Line 12
cout<< "Line 13: volume =" << PI * radius * radius * height <<endl; //Line 13
cout<< "Line 14: PI = "<<PI<<endll; //Line 14
cout<< "Line 15: " << setprecision(3) << radius << " , " << setprecision(2)
<< height << " , " << setprecision(5) << PI << endl; //Line 15
cout<< "12345678901234567890" << endl; //Line 16
cout<< setw(7) << radius << setw(8) << "Warm" << endl;//Line17
cout<< left<< setfill('*') << setw(8) << "Warm" << endl;//Line18
system("pause");
return 0; //Line 19
}
Output:
Line 10: setprecision(3)
Line 11: radius =12.670
Line 12: height =12.000
Line 13: volume =6051.797
Line 14: PI = 3.142
Line 15: 12.670 , 12.00 , 3.14159
12345678901234567890
12.67000 Warm
Warm****
6
Exercises
Exercise 1: Write a C++ program that prompts the user to enter radius of sphere and radius
and height of cylinder, the program will determine the volume of the two shapes, and the results
will be displayed on console screen.
,
Note: results must be displayed in three decimal places.
Exercise 2: Write a C++ program that prompts the user to enter coefficients of quadratic
2
equation (ax +bx+c), it will determine the roots that equation.
√
Note: use the quadratic formula
Exercise 3: Write a C++ program that prompts the user to enter numeric value that will be
substituted in the following mathematical formula, and the result will be displayed on the console.
Exercise 4: Write a C++ program that prompts the user to enter numeric value that will be
substituted in the following mathematical formula, and the result will be displayed on the console.
7
Exercise 5:
اكحب بشَايجا يحسب و يطبع صافي يشجب يوظف ،إرا عهًث أٌ صافي انشاجب يحسب بعذ حسى يجًوعة يٍ انًصاسيف و
هي كانحاني:
عهى بشَايجك انسًاح نهًسحخذو بإدخال اسى انًوظف باإلضافة إنى انشاجب انكهي قبم انخصى ( .)Gross Amountويٍ ثى
طباعة قسيًة ساجب هزا انًوظف انحفصيهية كًا هو يبيٍ في انًثال انحاني:
Ali
Gross Amount:. . . . . . . . . . . . . . . . $ 3575.00
Federal Tax: . . . . . . . . . . . . . . . . $ 536.25
State Tax: . . . . . . . . . . . . . . . . . $ 125.13
Social Security Tax: . . . . . . . . . . . . $ 205.56
Medicare / Medicaid Tax: . . . . . . . . . . $ 98.31
Pension Plan: . . . . . . . . . . . . . . . $ 178.75
Health Insurance: . . . . . . . . . . . . . $ 75.00
Net Pay: . . . . . . . . . . . . . . . . . . $ 2356.00
مالحظة :انعايود األول يٍ انيساس يجب أٌ جكوٌ انبياَات فيه يحارية نهيساس بيًُا جكوٌ بياَات انعايود انثاَي يحارية نهيًيٍ
8
Lab No. 3: Files
Examples:
Example 1: Write a complete C++ program that reads 3 numbers from file (num.txt) and then
prints out the numbers on screen.
#include<iostream>
using namespace std;
int main()
{
int x,y,z;
ifstream InFile;
InFile.open(“num.txt”);
InFile>>x>>y>>z;
cout<<x<<endl;
cout<<y<<endl;
cout<<z<<endl;
InFile.close();
system("pause");
return 0;
}
9
Exercises
Exercise 1: Write a complete C++ program that reads 2 integer numbers from a file (in.txt)
that stored in c:\students folder, then prints out the sum of those numbers in another file (out.txt).
Exercise 2: Write a complete C++ program that reads a student name from file (student.txt),
reads 3 marks from file (marks.txt), then print the name and average on screen.
Exercise 3: Data are stored in (data.txt) file as in the figure. Write a complete C++ program
that prints out on screen the name of the first student with his average.
Ali 87:77:80
Ahmad 88:90:92
Samer 70:78:75
Exercise 4: Write a complete C++ program that allows user to enter the file name with its path,
reads a number from the file, and print it on screen.
Note: Create a new file in c:\students with the name numbers.txt and write a number
in it.
11
Lab No. 4: if and if…else
Examples:
Example 1: An example is to find the absolute value of an entered number (One-Way Selection)
Solution code:
#include<iostream>
using namespace std;
int main()
{
double x;
cout << "Enter any Number: ";
cin >> x;
if(x<0)
x = -1*x;
cout << "Absolute value= " << x << endl;
system("pause");
return 0;
}
Output:
11
Example 2: Write a C++ program that computes the weekly salary of a part time employee based on:
- Number of hours worked
- The hourly wage.
If number of hours worked exceed 40 wage include overtime payment by 50%. (Two-
Way Selection)
Solution code:
#include<iostream>
using namespace std;
int main()
{
double hours,wage,salary;
cout << "Enter Working hours: ";
cin >> hours;
cout << "Enter wage: ";
cin >> wage;
if(hours > 40)
salary = 40*wage+1.5*wage*(hours - 40);
else
salary = hours*wage;
cout << "The salary= $" << salary << endl;
system("PAUSE");
return 0;
}
Output:
Enter Working hours: 50
Enter wage: 10
The salary= $550
Press any key to continue. . .
12
Exercises
Exercise 1: Write a program that prompts the user to input an integer between 0 and 35. If the
number is less than or equal to 9, the program should output the number; otherwise, it should output A
for 10, B for 11, ..., and Z for 35. (Hint: use the cast operator, static_cast<char>( ), for numbers >=
10)
Exercise 2: Write a complete C++ program that asks the user to enter a number, the program will
determine if that number is odd or even and display the results on the console?
Exercise 3: Write a complete C++ program that prompts the user to enter a letter, the program will
determine whether that letter is Uppercase or Lowercase letter. Display the result on console screen?
Exercise 4:
Exercise 5: Write a C++ program that prompts the user to enter a number that consists of four digits.
The program will determine if that number is Palindrome or not Palindrome .Display the results on
console screen?
Note: the following are examples of palindrome and non palindrome numbers
Palindrome 313 11 2332 5
Not Palindrome 65 4749 314 122212
13
Lab No. 5: Nested if and switch
Examples:
Example 3: Write a complete C++ program that asks the user to enter a Mark (between 40 and 100)
the program will print student grade according to the following table? (using if then using switch)
Mark Grade
Mark<=100 and Mark>=90 A
Mark<90 and Mark>=80 B
Mark<80 and Mark>=70 C
Mark<70 and Mark>=60 D
Mark<60 and Mark>=40 F
Otherwise Invalid
Solution code:
Nested-if Switch
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int Mark; int Mark;
cout << "Enter your Mark: "; cout << "Enter your Mark: ";
cin >> Mark; cin >> Mark;
if(Mark > 100 || Mark < 40) switch(Mark/10)
cout << "Invalid Mark\n"; {
else if(Mark >= 90) case 9: cout << "Grade is A\n"; break;
cout << "Grade is A\n"; case 8: cout << "Grade is B\n"; break;
else if(Mark >= 80) case 7: cout << "Grade is C\n"; break;
cout << "Grade is B\n"; case 6: cout << "Grade is D\n"; break;
else if(Mark >= 70) case 5:
cout << "Grade is C\n"; case 4: cout << "Grade is F\n";break;
else if(Mark >= 60) default: cout << "Invalid Mark\n" << endl;
cout << "Grade is D\n"; }
else if(Mark >= 40) system("pause");
cout << "Grade is F\n"; return 0;
system("pause"); }
return 0;
}
Output:
Enter your Mark: 85
Grade is B
Press any key to continue . . .
14
Example 4: Write a C++ program that prints the following menu and prompts the user to enter a
Choice.
1-Circle
2-Square
3-Rectangle
Enter your choice:
The program will prompt the user to enter the appropriate parameters for the selected shape and will
determine the area of it and display the result on the console?
Note: Results must be displayed in three decimal places
Solution code:
#include <iostream>
#include <iomanip>
using namespace std;
const double PI = 22.0/7;
int main()
{
int choice;
double r,e,w,h,area;
cout << fixed << setprecision(3);
cout << "1. Circle\n"
<< "2. Square\n"
<< "3. Rectangle\n"
<< "Enter your choice: ";
cin >> choice;
switch(choice)
{
case 1:cout << "Enter the radius: ";
cin >> r;
area = r*r*PI;
cout << "Area= " << area << endl;
break;
case 2:cout << "Enter the edge: ";
cin >> e;
area = e*e;
cout << "Area= " << area << endl;
break;
case 3:cout << "Enter height and width: ";
cin >> h>>w;
area = h*w;
cout << "Area= " << area << endl;
break;
default:
cout << "Invalid choice!!!" << endl;
}
system("pause");
return 0;
}
Output:
1. Circle
2. Square
3. Rectangle
Enter your choice: 1
Enter the radius: 2.5
Area= 19.643 15
Press any key to continue . . .
Exercises
Exercise 1: Write a complete C++ program that reads an integer number, then it determines whether
the number is POSITIVE, NEGATIVE or ZERO.
Exercise 2: Write a complete C++ program that prompts the user to enter a character data, the
program will determine if that character is letter, digit or symbol. Display the result on console screen.
Exercise 3: Write a complete C++ program that prompts the user to enter three numeric values; it will
determine the maximum and minimum values. Display the results on console screen.
Exercise 4: Write a program that determines if an integer entered number is ODD or EVEN (using
switch).
Exercise 5: Write a C++ program that prompts the user to enter two numeric values; it will determine
the minimum value. Display the results on console screen? (use ? : operator)
16
Lab No. 6: Iterative Control Structure (While & For Loop)
Example 1:
Write a C++ program that prints all even & odd numbers between 0 and 35. Display results on screen.
Solution code:
#include<iostream>
using namespace std;
int main()
{
int x=0;
cout<<"Even numbers: ";
while(x<=35)
{
if(x%2==0)
cout<<x<<" ";
x++;
}
x=0;
cout<<endl;
cout<<"Odd numbers: ";
while(x<=35)
{
if(x%2!=0)
cout<<x<<" ";
x++;
}
cout<<endl;
return 0;
}
Output:
. Even numbers: 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34
Odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35
17
Example2:
Write a C++ program that prompts the user to enter 10 numeric values, and then calculate the sum and
average of these values. Display results on screen.
Note:
Display results in two decimal places.
Solution code:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x,sum=0;
double avg;
int i=0;
cout<<"Enter 10 numbers:";
while(i<10)
{
cin>>x;
sum=sum+x;
i++;
}
avg=sum/10.0;
cout<<fixed<<showpoint;
cout<<setprecision(2);
cout<<"Sum is: "<<sum<<endl;
cout<<"Average is :"<<avg<<endl;
return 0;
}
Output:
Enter 10 numbers: 19 -4 6 8 1 -8 0 15 17 38
Sum is: 92
Average is: 9.20
18
Example 3:
Write a C++ program that reads the content of text file named data.txt which contains numeric values.
It will determine number of odds and number of evens in that file. Display results on console screen.
Solution code:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int cOdd=0,cEven=0;
int x;
ifstream indata;
indata.open("data.txt");
if(!indata)
{
cout<<"File doesn't exist";
return 1;
}
indata>>x;
while(indata)
{
if(x%2==0)
cOdd++;
else
cEven++;
indata>>x;
}
indata.close();
cout<<"Number of odd numbers is:"<<cOdd<<endl;
cout<<"Number of even numbers is:"<<cEven<<endl;
return 0;
}
90 -5 88 75
12 0 7 89
1
data.txt
output :
19
Exercises
Exercise 1:
Write a C++ program that calculates the approximated vale of pi (π) using the Gregory-Leibniz series as
provided below. Determine it using 20 elements of the series. Display result on screen.
Exercise 2:
Write a C++ program that prompts the user to enter a number. It will determine whether that number is a
prime or not .Display result on screen.
Note: prime number is a natural number that has exactly two distinct natural number divisors: 1 and
itself. [Wikipedia]
Exercise 3:
Write a C++ program that prints the following menu and prompts the user to enter a choice
1- Capital & smalls will read the content of text file named letter.txt and determine number of
capitals and number of smalls.
2- Vowels and consonants will read the content of text file named letter.txt and determine number
of vowels and number of consonants.
3- Exit the program will continue to execute until the user selects this choice.
letter.txt
Write a C++ program that prints the Extended ASCII Table in the following format.
Exercise #B:
Write a C++ program that prompts the user to enter a number. It will determine the factorial of that
number. Display results on screen.
Enter a number: 5
Enter a number: -8
21
Lab No. 7 Iterative Control Structure (do while and Nested Loops)
Examples
Example 1:
Write a C++ program that prints the following shape.
Note: Use only one asterisk character * in your program.
Solution code:
#include<iostream>
using namespace std;
int main()
{
int i,j;
for(i=0;i<6;i++)
{
for(j=0;j<=i;j++)
cout<<"*";
cout<<endl;
}
return 0;
}
Example 2:
Write a C++ program that prints the following shape.
Note: Use only one asterisk character * in your program.
Solution code:
#include<iostream>
using namespace std;
int main()
{
int i,j;
for(i=0;i<6;i++)
{
for(j=5;j>=i;j--)
cout<<"*";
cout<<endl;
}
return 0;
}
22
Example 2:
Write a C++ program that prints the menu:
Volume Calculator
1- Cube
2- Cone
3- Sphere
4- Exit
Enter your choice:
The user enters his/her choice then it will prompt him/her to enter parameters for that shape. It will
determine volume of that shape.
Note: The program must continue to execute until the user selects the fourth choice.
Solution code:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
int choice;
double x,r,h,pi=22.0/7;
do
{
system("cls");//Clears console screen
cout<<"Volume Calculator"<<endl;
cout<<"1- Cube"<<endl;
cout<<"2- Cone"<<endl;
cout<<"3- Sphere"<<endl;
cout<<"Exit"<<endl;
cout<<"Enter your choice"<<endl;
cout<<fixed<<showpoint;
cout<<setprecision(2);
cin>>choice;
if(choice==1)
{
cout<<"Enter edge of cube:";
cin>>x;
cout<<"Volume of cube :"<<pow(x,3)<<endl;
}
else if(choice==2)
{
cout<<"Enter radius and height of cone:";
cin>>r>>h;
cout<<"Volume of cone :"<<1.0/3*pi*pow(r,2)*h<<endl;
}
else if(choice==3)
{
cout<<"Enter radius sphere";
cin>>r;
cout<<"Volume of sphere: "<<4.0/3*pi*pow(r,3)<<endl;
}
23
system("pause"); //Stop execution until keystroke
}while(choice!=4);
return 0;
}
Exercises
Exercise 1:
Write a C++ program that prompts the user to enter number of students in the class (N), followed by
number of marks for each student (M), then ask the user to enter the marks for each student, and finally
print out the class average.
Exercise 2:
Write a C++ program that prompts the user to enter number of rows of a triangle it will display the
following shape with the given number of rows.
24
Exercise 3:
Write a C++ program that displays multiplication table in the following format on console screen.
Output:
1 2 3 4 5 6 7 8 9
--------------------------------------------
1| 1 2 3 4 5 6 7 8 9
2| 2 4 6 8 10 12 14 16 18
3| 3 6 9 12 15 18 21 24 27
4| 4 8 12 16 20 24 28 32 36
5| 5 10 15 20 25 30 35 40 45
6| 6 12 18 24 30 36 42 48 54
7| 7 14 21 28 35 42 49 56 63
8| 8 16 24 32 40 48 56 64 72
9| 9 18 27 36 45 54 63 72 81
25
Lab No. 8: Functions I (Call By Value)
Examples:
Example 1:
Write a complete C++ program that reads 3 numbers as integer, then define and use a function named
Avg() that returns the average of three integer parameters.
Solution code:
#include<iostream>
using namespace std;
int main()
{
int num1,num2,num3;
double average;
system("pause");
return 0;
}
Output:
26
Example 2:
Write a complete C++ program that reads ten numbers as integers, then using function max(), find the
max value of these numbers?
Solution code:
#include<iostream>
using namespace std;
int maximum(void);
int main()
{
int mx;
mx= maximum();
system("pause");
return 0;
}
int maximum()
{
int max,num,i=1;
cout<<"please enter the first number"<<endl;
cin>>num;
max=num;
do
{
cout<<"please enter the next number"<<endl;
cin>>num;
if(num>max)
max=num;
i++;
}while(i<10);
return max;
}
27
Exercises
Exercise 1: Write a complete C++ program that reads a number n from the user, and then calls a
function Fact (n) that computes and prints the factorial of n?
Exercise 2: Write a complete C++ program that prints out on screen the following menu:
n
1. Call a function Power ( ) that finds the result of X
2. Enter Two integers and determine which one is multiple of the other, using function
Ismultiple( ).
3. Exit
Exercise 3: Write complete C++ program that calls a function CheckPal ( ) that checks an entered
number whether it is palindrome or not.
Exercise 4: Write complete C++ program that uses a function power(), and function Sum(), to find
the result of the following series:
r r r
y=1 +2 +…….n
28
Lab No. 9: Functions II (Call By Reference)
Examples:
Example 1:
Write a complete C++ program that reads two double numbers, then using function Swap(), exchange
the two values and call a function Print() to print them.
Solution code:
#include<iostream>
using namespace std;
int main ()
{
double x,y;
system("pause");
return 0;
}
}
void swap(double &x, double &y)
{
double temp;
temp=x;
x=y;
y=temp;
}
Output:
29
Example 2:
Write a complete C++ program that uses a function getscore( ) that inputs the score of a student, then
calls a function showgrade() to print the grade, and then call a function modify() to add 5% to that score.
Solution code:
#include<iostream>
using namespace std;
getScore(score);
cout << endl << " Course score is "<< score << endl;
printGrade(score);
Modify(score);
cout<<"The modified course score is : "<<score<<endl;
system("pause");
return 0;
}
}
void printGrade(int cScore)
{
cout << "Your grade for the course is ";
if (cScore >= 90)
cout << "A." << endl;
else if (cScore >= 80)
cout << "B." << endl;
else if(cScore >= 70)
cout << "C." << endl;
else if (cScore >= 60)
cout << "D." << endl;
else
cout << "F." << endl;
}
31
Output:
Exercises
Exercise 1: Write a complete C++ program that finds the salary for 10 employees, according to the
hour rate and number of hours worked, using the following functions:
1. GetData() that prompts the user to input his name, the hours worked and rate per hour.
2. CalculateSalary() that calculates and returns the amount to be paid to an employee.
3. UpdateSalary() that apply 15% tax to the salary.
4. Printdata() that prints the employee name, hours worked, rate per hour, and the salary.
Exercise 2: Write a complete C++ program that reads 10 Decimal numbers, then convert them to
Binary. Using the following functions:
AbcdefrerI
78 95 74 85 96 78 85 96 85 74
in.txt
Then write a complete C++ program that contains two functions:
Letters( ): that read 10 letters from file and return the number of upper ones.
Numbers(): that read 10 numbers from file and return their average.
In main, call these two functions to print the number of upper letters and average of numbers.
Examples:
Example 1:
Write a C++ program that performs the following options:
Declare an array of type integer and set the size to be 10, initialize the array with the
following values: 1, 2, 3, …, 10.
Print out the contents of the array.
Print out the contents of the array in reverse order.
Send the array and its size to a function that returns the sum of the members of the array then
print it in the main.
Solution code:
#include<iostream>
using namespace std;
int main()
{
const int SIZE = 10;
int a[SIZE] = {1,2,3,4,5,6,7,8,9,10};
cout<<"Array contents:\n";
for(int i=0;i<SIZE;i++)
cout << a[i] << " ";
cout<<endl <<endl;
return total;
}
32
Output:
Exercises
Exercise 1: Write a C++ program that asks the user to enter 10 integer numbers and store them into an
array, then find and print the maximum and minimum numbers along with their indices.
Exercise 2: Write a C++program that reads n numbers representing marks of students in a class, store
them in an array, then call a function Count() that accepts the array as input and return number of
students who obtained marks greater than class average.
Exercise 3: Write a C++ program that asks the user to enter 5 floating numbers in an array, then send it
to a function called subtotal() that takes the following parameters:
(1) An array of floating point values;
(2) The size of the array as integer variable
The function should replace the contents of each cell with the sum of the contents of all the preceding it.
Example:
5.8 2.6 9.1 3.4 7.0
Then when the function returns, the array will look like this:
Exercise 4:Write a C++ program that reads 20 numbers, stores them in an array, then calls a function
Sort() that sorts the contents of the array in ascending order, then prints the array contents in main after
sorting.
33
Lab No. 11: Strings
Examples
Example 1:
Write a C++ program that prompts the user to enter first, middle and last names for two users. It will
determine if users are Bothers, Relative or Not Relatives. Result must be displayed on console screen.
Note: use the following function declaration.
void relation(string Mname1,string Lname1,string Mname2,string Lname2);
Solution code:
#include<iostream>
#include<string>
using namespace std;
void relation(string Mname1,string Lname1,string Mname2,string Lname2);
int main()
{
string fName1,mName1,lName1;
cout<<"Enter first, middle and last name of first user:"<<endl;
cin>>fName1>>mName1>>lName1;
cout<<"Enter first, middle and last name of second user:"<<endl;
cin>>fName2>>mName2>>lName2;
relation(mName1,lName1,mName2,lName2);
return 0;
}
void relation(string Mname1,string Lname1,string Mname2,string Lname2)
{
if(Mname1==Mname2 && Lname1==Lname2)
cout<<"Users are brothers"<<endl;
else if(Lname1==Lname2)
cout<<"Users are relatives"<<endl;
else
cout<<"Users are not relatives"<<endl;
}
Output:
34
Example 2:
Write a C++ program that reads the content of text file with essay.txt. It will determine the number of
occurrences of a word entered by user. Display results on console screen.
Note: use the following function declaration.
int occur(ifstream &indata, string str);
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int occur(ifstream& indata,string str);
int main()
{
int oc;
string str;
ifstream infile;
infile.open("essay.txt");
if(!infile)
{
cout<<"File does not exist";
return 1;
}
cout<<"Enter a word to search: ";
cin>>str;
oc=occur(infile,str);
cout<<str<<" occured "<< oc <<" times."<<endl;
infile.close();
return 0;
}
int occur(ifstream& indata,string str)
{
int x=0;
string s;
indata>>s;
while(indata)
{
if(s==str)
x++;
indata>>s;
}
return x;
}
35
Sample of Program Execution:
essay.txt
Console Screen
Exercises
Exercise 1:
Write a C++ program that reads the content of text file determined by user. It will determine number of
words which consist of 7 letters and end with ing. Display result on console screen.
letter.txt
Console Screen
Exercise 2:
Write a C++ program that prompts the user to enter two words. The program will search for the first
word in text file with name article.txt and replace it with the second word and write the modified text
on another file named modified.txt. It will print number of replaces on console screen.
36
Sample of Program Execution:
Console Screen
Article.txt modified.txt
37
Lab No. 12: Two Dimensional Array
Examples:
Example 1: Write a C++ program that performs the following options:
Declare an integer array with 2 rows and 3 columns, initialize it with the following array
Solution code:
#include<iostream>
using namespace std;
int main()
{
int a[2][3] = {{2,-4,5},{10,3,20}};
cout<<"array contents:\n";
for(int i=0;i<2;i++)
{
for(int j = 0 ; j<3 ; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<"Sum = "<<sum(a)<<endl;
system("pause");
return 0;
}
int sum(int a[][3])
{
int total=0;
for(int i=0;i<2;i++)
for(int j = 0 ; j<3 ; j++)
total+= a[i][j];
return total;
38
Output:
Exercises
Exercise 1:
Write a complete C++ program that declares a 3 x 4 integer array, asks user to enter the array elements,
stores them in the array and then finds:
Exercise 2:
Write a complete C++ program that declares a 100 x 100 integer array, ask user to enter the order of his
square matrix (Square Matrix is a matrix in which number of rows equals the number of columns), then
asks him to enter his matrix and determines whether the matrix is diagonal or not. (A square matrix is
called diagonal if every term off the main diagonal is zero)
Example: Example:
[ ] [ ]
9 9
Is diagonal Is not diagonal
Exercise 3:
Write a complete program that declares a 100 x 100 integer array, asks user to enter the order of his
matrix (# of rows and # of columns) then asks him to enter his matrix and stores the transpose of the
matrix to another matrix, then prints the transpose.
* + [ ]
Exercise 4:
Write a complete program that declares a 4x4 array, fills it by random numbers and then prints the array
contents. Use rand() function from cstdlib Library.
39
Lab No. 13: Structs
Examples:
a. Write the type declaration for a struct data type named Student to contain the following
information about a student: Name (string) , Id (integer number), GPA (float number)
b. Define a variable named Student1 of type Student.
c. Write assignment statements to store in Student1 the data for a student with the following
properties: name: “Ahmad”, id: 99357, GPA: 83.7
d. Define a variable named Student2 of type Student, ask user to enter a name, id, and GPA for a
student, and then store them into Student2.
e. Print Student1 and Student2 information.
Solution code:
#include<iostream>
#include<string>
using namespace std;
int main()
{
struct Student
{
string name;
int id;
float GPA;
};
Student student1;
student1.name = "Ahmad";
student1.id = 99357;
student1.GPA = 83.7;
cout<<"Student1 name: "<<student1.name<<endl
<<"Student1 id: "<<student1.id<<endl
<<"Student1 GPA: "<<student1.GPA<<endl;
Student student2;
cout<<"Enter information for student2(name, id, GPA): "<<endl;
cin>>student2.name>>student2.id>>student2.GPA;
cout<<"Student2 name: "<<student2.name<<endl
<<"Student2 id: "<<student2.id<<endl
<<"Student2 GPA: "<<student2.GPA<<endl;
return 0;
}
41
Exercises
Exercise 1: Write the type declaration for a struct data type named Date with the following
Define a variable named currentDate of type Date, ask user to enter the current date.
Define a variable named DateOfBirth of type Date, ask user to enter his date of birth.
Pass currentDate and DateOfBirth to a function FindAge() that will return a Date struct
that contain the age of user of type Date and print age (age of user in years, months and
days) in main. (Note: month = 30 days , year = 12 months)
Exercise 2: Write the type declaration for a struct data type named Date with following members:
Declare a hierarchical struct data type named StudentRec that consists: name (string), id
(integer), Grades (array with size 5 of type integer), and DateOfBirth (of type Date).
Define a variable named Student1 of type StudentRec, then write assignment statements to
store in Student1 the data for a student with the following properties: name: “ahmad”,
number: 99367, Grades 60, 65, 70, 75,80 and DateOfBirth: 23-7-1995.
Define a variable named Student2 of type StudentRec, copy the contents of Student1 to
Student2, and then print out name, number, average of grades, and Date of birth of
student2.
41
Contents
Lab No. 1: Introduction ............................................................................................................................... 1
Lab No. 2: Predefined Functions and Formatting Output ........................................................................... 5
Lab No. 3: Files ........................................................................................................................................... 9
Lab No. 4: if and if…else .......................................................................................................................... 11
Lab No. 5: Nested if and switch ................................................................................................................ 14
Lab No. 6: Iterative Control Structure (While & For Loop) ..................................................................... 17
Lab No. 7 Iterative Control Structure (do while and Nested Loops) ........................................................ 22
Lab No. 8: Functions I (Call By Value) .................................................................................................... 26
Lab No. 9: Functions II (Call By Reference) ............................................................................................ 29
Lab No. 10 One Dimensional Array.......................................................................................................... 32
Lab No. 11: Strings.................................................................................................................................... 34
Lab No. 12: Two Dimensional Array ........................................................................................................ 38
Lab No. 13: Structs ................................................................................................................................... 40
42