Вы находитесь на странице: 1из 31

Adama University

Lab-2
What is the out put of the following programs?
Example 1
#include<iostream.h>
#include<conio.h>
int main ( )
{
clrscr();
int x;
int y;
x= 10<5 || 5>=10;
y = x>0;
cout<< !20 << endl;
cout<< (10 && 5)<< endl;
cout<< x << endl;
cout<< y<< endl;
getch();
}
Example3
#include<iostream.h>
#include<conio.h>
void main( )
{
clrscr();
double d=3*int(3.15);
long k=3.14-5;
cout <<d<<endl<<k;
getch();
}
Example 4
#include <iostream .h>
#include<conio.h>
void main( )
{
clrscr();
int a = 10;
int b = 5;
cout<<"a =" << a<<", b = "<<b<< endl;
a = b;
cout<<"a = " <<a<<", b = "<< b<< endl;
b = 7;
cout<<"a = " <<a<<", b = "<<b<<endl;
getch();
}
1

Example5
#include<iostream.h>
#include<conio.h>
int main ( )
{
clrscr();
int x=10;
int y=2;
cout<<" the value of the expression x+=y is: "<< x+=y<<endl;
cout<<" the value of the expression x-=y is: "<< x-=y<<endl;
cout<<" the value of the expression x/=y is: "<< x/=y<<endl;
cout<<" the value of the expression x*=y is: "<< x*=y<<endl;
cout<<" the value of the expression x%=y is: "<< x%=y<<endl;
getch();
return 0;
}
Example 6
#include<iostream.h>
#include<conio.h>
int main ( )
{
clrscr();
int m = 1, n = 2;
int min = (m < n ? m : n); // min receives 1
cout <<"The minimum value is = :"<<min;
getch();
return 0;
}
Example 7:
#include <iostream.h>
#include<conio.h>
int main ( )
{
clrscr();
cout << "char size = " << sizeof(char) << " bytes\n";
cout << "short size = " << sizeof(short) << " bytes\n";
cout << "int size = " << sizeof(int) << " bytes\n";
cout << "long size = " << sizeof(long) << " bytes\n";
cout << "float size = " << sizeof(float) << " bytes\n";
cout << "double size = " << sizeof(double) << " bytes\n";
cout << "1.55 size = " << sizeof(1.55) << " bytes\n";
cout << "1.55L size = " << sizeof(1.55L) << " bytes\n";
cout << "HELLO size = " << sizeof("HELLO") << " bytes\n";
getch();

return 0;
}

Exercises
2.1 Write expressions for the following:
To test if a number n is even.
To test if a character c is a digit.
To test if a character c is a letter.
To do the test: n is odd and positive or n is even and negative.
To give the absolute value of a number n.
2.2 Add extra brackets to the following expressions to explicitly show the order in
Which the operators are evaluated:
(n <= p + q && n >= p - q || n == 0)
( (p < q ? n < p ? q * n - 2 : q / n + 1 : q - n)
2.3 What will be the value of each of the following variables after its initialization?
double d = 2 * int(3.16);
long k = 3.16 - 3;
char c=a+3 ;
char c2=d+c-a ;
2.4 Write a program which inputs a positive integer n and outputs 2 raised to the power of
n.
Hint: check the library functions in the <math.h> header file.
2.5 Write a program which inputs three numbers and outputs the message sorted if the
numbers are in ascending order, and outputs not sorted otherwise.
2.6 Write a program that accept an integer from the user and print the last digit of the entered
integer.
2.7 Write a program that accepts three numbers from the user and return the average of the
three numbers.
2.8 Write a program that accepts the temperature in F0 form and generate the C0 equivalent.
Hint: C0 =(F0 32) 5/9

Adama University
Department of CSIT
Cpp-Lab-3 and lab-4 Exercise
What is out put?
Example: 1
#include <iostream.h>
void main ()
{
int x;
cout << "Please guess a number I have inmind from 1-10:";
cin >> x;
if (x > 10)
cout << "That number is too big!" << endl;
if (x < 1)
cout << "That number is too small!" << endl;
if (x != 5)
cout << "You didn't get the right number!" << endl;
if (x==5)
cout << "You didn't get the right number!" << endl;
cout << "Thank you and goodbye!" << endl;
}

Example: 2
#include<iostream.h>
Void main()
{
cout << "Please type the number 8 : ";
cin >> x;
if (x == 8)
cout << "Thank you! I appreciate that." << endl;
else
{
cout << "Why can't you follow simple instructions?<< endl;
}
}

Example: 3
#include<iostream.h>
Void main ()
{
Char ch;
Cout<<"Enter

a character"<<endl;

Cin>>ch;
if (ch >= 0 && ch <= 9)
cout<<"the character "<<ch<<"is
else
{

a number";

if (ch >= 'A' && ch <= 'Z')


cout<<"the character "<<ch<<"capital letter";
else
{
if (ch >= 'a' && ch <= 'z')
cout<<"the character "<<ch<<"Small letter letter";
else
cout<<"the character "<<ch<<"It is a special character";
}
}

Or

#include<iostream.h>

Void main ()
{
Char ch;
Cout<<"Enter

a character"<<endl;

Cin>>ch;
if (ch >= '0' && ch <= '9')
cout<<"the character "<<ch<<"is a number";
else if (cha >= 'A' && ch <= 'Z')
cout<<"the character "<<ch<<"capital letter";
else if (ch >= 'a' && ch <= 'z')
cout<<"the character "<<ch<<"Small letter letter";
else
cout<<"the character "<<ch<<"It is a special character";

}
Example 4
# include <iostream.h>
# include <conio.h>
void main()
{
int operand1, operand2;

char optr;
cout <<"enter two numbers"<<endl;
cin >> operand1>>operand2;
cout <<"enter one of the these operators
cin>> optr;
switch (optr)
{
case '+':
cout<<operand1 + operand2;
break;
case '-':
cout<<operand1 - operand2;
break;
case '*':
cout<<operand1 * operand2;

+ , * , / , % "<<endl;

break;
case '/':
cout<<operand1 / operand2;
break;
default:
cout << "unknown operator: " << operator << \n';
break;
}
}

Or
void main()
{
int operand1, operand2;

char operator;
double result;
cout <<" Enter two Integers "<<endl;
cin >> operand1>>operand2;
cout <<"Enter one of the arithmetic operators + , * , / , % "<<endl;
cin>> operator;
if (operator == '+')
cout<<operand1 + operand2;
else if (operator == '-')
cout<< operand1 - operand2;
else if (operator == 'x' || operator == '*')
cout<< operand1 * operand2;
else if (operator == '/')
cout<< operand1 / operand2;
else
cout << "unknown operator: " << operator << '\n';
}

Example:5
#include<iomanip.h> // for setw( ),
void main ( )
{
int n;
for (n=1; n<=20;n++)
{ cout<<setw(4) <<n;
int sq = n*n;
cout<<setw (6) << sq<<endl;
} //end of loop
} // end of program.

Example: 6
#include <iostream.h>
void main ()
{
int x, limit, sum;
cout << "Please enter a number bigger than 1 : ";
cin >> limit;
sum = 0;
for (x = 1; x <= limit; x++)
{
cout << "I am adding " << x << endl;
sum = sum + x;
}

cout << endl;


cout << "The sum of all the numbers from 1 to ";
cout << limit << " is " << sum;
return;
}

Example: 7
#include<iostream.h>
#include<conio.h>
void main ()
{
char ch;
do
{
cout<<"Hello!\n";
cout<<"Do you want to display more Hello's (Y/N) ";
cin >>ch;
} while (ch != 'N');
getch();
}
Example: 8
#include <iostream.h>
void main ()
{
int my_number;
int valid;
// 1 if the number is valid,
// 0 otherwise
cout << "Please enter a number from 1 to 10 : ";
do
{ cin >> my_number;
valid = 1;
// by default
if (my_number < 1)
valid = 0;
if (my_number > 10)
valid = 0;
if (valid == 0)
cout << "I said from 1 to 10! Try again : ";
}
while (valid == 0);
cout << "Thank you." << endl;
}
Example: 9
{

int min, i = 10, j = 20;


While(i<=j)
min = (i < j ? i : j);
cout << min << '\n';

i++;
j--;
}

Example: 10
#include <iostream.h>
void main ()
{ int x, answer;
for (x = 1; x <= 10; x++)
{
cout << "Question " << x << endl;
cout << "What is the answer to " << 2*x
<< " + " << (30 - x) << " ? : ";
do
{ cin >> answer;
if (answer == 2*x + 30 - x)
cout << "Correct!" << endl;
else
cout << "No, try again!" << endl;
}
while (answer != 2*x + 30 - x);
}
}
Example: 11
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main ()
{
for (int i=1; i<=100; i++)
{
if (i%2!= 0)
continue;
else
cout<<setw(4)<<i<<endl;
}
getch(); }

Example: 12

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main ()
{

for (i = 0; i < attempts; ++i) {


cout << "Please enter your password: ";
cin >> password;
if (Verify(password)) // check password for correctness
goto out;
// drop out of the loop
cout << "Incorrect!\n";
}
out:
getch();

Exercises
1.

Write a program which inputs a persons height (in centimetres) and weight (in
kilograms) and outputs one of the messages: underweight, normal, or overweight,
using the criteria:

Underweight:
weight < height/2.5
Normal:
height/2.5 <= weight <= height/2.3
Overweight:
height/2.3 < weight
2. Write a program which inputs a date in the format dd/mm/yy and outputs it in the
format month dd, year.
For example, 25/12/61 becomes: December 25, 1961
3.Write a program which produces a simple multiplication table of the following format
for integers in the range 1 to 9:
1 x 1 = 1
1 x 2 = 2
...
9 x 9 = 81

4.

Write a program that display numbers from 0 to 10 using three loops.

5.

write for loop that will produce each of the following sequence
2, 4, 6, .44
5, 7, 9,...45
The sum of numbers between 2 to 44 inclusive
The sum of the first 20 numbers in the series 1, 4, 7, 10

6. Re write the following code fragment using one switch statement

if (ch = = E|| ch= = e)


cout<<" this is either the value of E or e";
else if (ch = = A|| ch= = a)
cout<<" this is either the value of A or a";
else if (ch = = r|| ch= = i)
cout<<" this is either the value of i or r";

else
cout<<" Enter the correct choice";

7.

If the originally x=2 ,y=1 and z=1, what are the value of x, y, z after executing
the following code?
Switch(x)
{
case 0 : x = 2;

y =3;
case 1 : x =4;
Default:
y = 3;
x = 1;
}
8. Write a program that creates the following number pattern.
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
9. Write a program that accepts student mark out of 100, and return the corresponding
letter grade based on the following condition:
if mark is greater than or equal to 90 A
if mark is greater than or equal to 80 and less than 90 B
if mark is greater than or equal to60 and less than 80 C
if mark is greater than or equal to 40 and less than 60 D
if mark is less than 40 F
for other cases NG
N.B write the program using both switch and else-if.

10

Adama University
Department of CSIT
Cpp-Lab- 5 Exercise
Functions
Example: 1
#include<iostream.h>
#include<conio.h>
void Add ( );
void sub ( );
void main ()
{
char ch;
cout <<" what do you want ? A: Add, S: subtract \n";
cin>>ch;
switch(ch)
{
case 'A':
// A for addition
Add ( ) ;
break;
case 'S' :
// b for subtraction
sub ( );
break;
}
}
void Add()
{ int a,b,c;
cout<<"enter two numbers \n";
cin>> a>>b;
c = a + b;
cout <<" the sum is \t "<< c;
}
void sub ( )
{int a,b,c;
cout<<"Enter two numbers \n";
cin>>a>>b;
cout<<"the difference is \t "<<a-b;
}
Example: 2
#include<iostream.h> // the program adds two
#include<conio.h>
//numbers, or
void func(char ch,int a,int b);
// does subtraction
11

void main ()
{ char op;
int op1,op2;
cout<<"Enter the two numbers\n";
cin>>op1>>op2;
cout<<"Enter an operator [+ or *]\n";
cin >> op;
func(op,op1,op2); // calling the function
}
void func(char a, int b, int c)
{
int sum, diff, prod, result;
switch (a)
{
case '+':
cout << " sum is \t " << b+c;
break;
case'*':
cout<<"product is \t"<<b*c;
} // End switch statement.
}
Example: 3
The following example passes arguments by reference.
#include<iostream.h>
#include<conio.h>
void to_Kg(float&w);
void main ( )
{
float weigt;
cout<<"Enter weigt in pound: ";
cin>>weigt;
to_Kg(weigt);
cout<<"changed to kilograms is "<<weigt;
getch ( );
}
void to_Kg(float &w)
{
w*=0.4536;
}
Example: 3
#include<iostream.h>
#include<conio.h>
void add (int,int);

12

void add (int, int, int);


void main ( )
{
add (2,3);
add (2,3,4);
getch( );
}
void add(int a, int b)
{ int sum;
sum= a+b;
cout <<"sum of two integers\t"<<sum<<endl;
}
void add (int a, int b, int c)
{
cout<<"sum of three integers\t "<<a+b+c;
}
Example: 4
#include<iostream.h>
#include<conio.h>
void add (int, int );
void add (float, float);
void main ()
{
int x=2,y=5;
float l=11.5,m=5.7;
add (x,y);
add (l,m);
getch();
}
void add (int a, int b )
{
cout <<"sum of two integers \t"<<a+b<<"\n";
}
void add (float c, float d)
{
cout << "sum of two floats \t"<<c+d;
}
Example: 5
#include<iostream.h>
#include<conio.h>
void nat(int i=1,int j=10);
void main ( )
{

13

nat ( );
nat (5);
nat (1,15);
getch();
}
void nat (int a, int b)
{
for (int k =a; k<=b; k++)
cout <<k;
cout<<endl;
}
Example: 6
#include<iostream.h>
#include<conio.h>
void fun ( ) ;
void main()
{
fun();
fun();
fun();
getch();
}
void fun( )
{
for (int i=1; i<=30; i++)
if (i%5==0)
cout <<i<<endl;
else
continue;
static int count=0;
count ++;
cout <<"Function call "<<count<<endl;
}
void sub ( )
{int a,b,c;
cout<<"Enter two numbers \n";
cin>>a>>b;
cout<<"the difference is \t "<<a-b;
}

14

Adama University
Department of CSIT
Cpp-Lab-6&7 Exercises
Example 1
The following program stores 10 natural numbers in one array and displays them (with
enough space between the numbers when displayed).
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main ( )
{
int n[10];
for(int i = 0;i<10;i++)
{
cout <<"enter natural number "<<i+1<<" ";
cin>>n[i];
}
cout<<"Now displaying ";
for(int j = 0;j<10;j++)
cout<<setw(4)<<n[j];
getch();
}
Example 2
The following program finds average of numbers that are stored in array.
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main ( )
{
int num[10]= { 10,20,50,70,75,60,80,95,55,100};
float sum = 0;
float av;
for(int i = 0;i<10; i++)
sum+=num[i];
av=sum/10;
cout<<"The average is\t"<<av;
getch();
}
Example 3
#include <iostream.h>
int main()

15

{
// We know that we need a constant number of elements
const int max = 10;
int number[max];
// We will calculate their sum
int sum = 0;
cout << "Please type 10 integers.\n";
for( int i = 0; i < max; i++ )
{
cout << "Number " << i + 1 << ": ";
cin >> number[i];
sum += number[i];
}
cout << "\n\nThe sum of these numbers is " << Sum << "\n\n";
return 0;
}
Example 3
#include <iostream.h>
using namespace std;
int main()
{
// Declare the members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int find;
int i, m = 8;
cout << "Enter a number to search: ";
cin >> find;
for (i = 0; (i < m) && (Numbers[i] != Find); ++i)
continue;
// Find whether the number typed is a member of the array
if (i == m)
cout << find << " is not in the list" << endl;
else
cout << find << " is the " << i + 1
<< "th element in the list" << endl;

16

return 0;
}
Example 4
// Example of finding the minimum member of an array
#include <iostream.h>
int main()
{
// The members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int minimum = numbers[0];
int a = 8;
// Compare the members
for (int i = 1; i < a; ++i) {
if (numbers[i] < minimum)
minimum = numbers[i];
}
// Announce the result
cout << "The lowest member value of the array is "
<< minimum << "." << endl;
return 0;
}
Example 5
#include <iostream.h>
void DisplayTheArray(double member[]);
int main()
{
const int numberOfItems = 5;
double distance [numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
cout << "Members of the array";
DisplayTheArray(distance);
return 0;
}
void DisplayTheArray(double member[])
{
for(int i = 0; i < 5; ++i)
cout << "\nDistance " << i + 1 << ": " << member[i];
cout << endl;
}

17

Example 6
#include <iostream.h>
void DisplayTheArray(double mbr[], int count);
int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};
// Processing 5 members of the array
cout << "Members of the array";
DisplayTheArray(distance, 5);
// Processing all members of the array
int sizeOfArray = sizeof(Distance)/sizeof(double);
cout << "\nMembers of the array";
DisplayTheArray(distance, sizeOfArray);
return 0;
}
void DisplayTheArray(double member[], int counter)
{
for(int i = 0; i < counter; ++i)
cout << "\nDistance " << i + 1 << ": " << member[i];
cout << endl;
}
Example 7
The following program finds the highest temperature out of the three cities and the four
seasons.
int main()
{
const int rows = 3;
const int columns = 4;
int seasonTemp[rows][columns] = { {26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}};
int highest = 0;
for (register i = 0; i < rows; ++i)
for (register j = 0; j < columns; ++j)
if (temp[i][j] > highest)
{
highest = temp[i][j];
cout<<"The highest temperature is =:"<<highest;

18

}
}
Example 8
The following program stores sales of commodities in 5 stations for 3 months. You can also
display what you stored for checkup purpose.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main ( )
{
float sales[5][3];
for(int s=0;s<5;s++)
for (int m=0;m<3;m++)
{ cout <<"enter sales for station "<<s+1;
cout<<" month "<<m+1<<" ";
cin>>sales[s][m];
}
for (int j=0; j<=4; j++)
for (int k=0;k<=2;k++)
{cout<<" sales "<<j+1 <<" month "<<k+1;
cout<<setw(4)<<sales[j][k];
if (k= =2)
cout<<"\n";
}
getch( );
}
Examples 9
The following C++ program reads your name from keyboard and displays it.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main ()
{ char name[20];
cout<<"Enter your name \t";
cin>>setw(20)>>name;
cout<<name;
getch();
}

19

Examples 10
#include<iostream.h>
#include<conio.h>
void main ( )
{
char str [20];
cout<<"Enter Full Name\t";
cin.get(str,20);
cout<<"your name and fathers name is \n"<< str;
}
Example 11
The following program reads multiple lines of text and stores it in an array.
#include<iostream.h>
#include<conio.h>
void main ( )
{char str[100];
cout<<"Enter a sstring and $ when finish \n";
cin.get (str,100,'$');
cout<<"you entered \n"<<str;
getch ( ) ;
}
Example 12
The following program stores list of people in an array and display it.
#include<iostream.h>
#include<conio.h>
void main( )
{
char name[5][10]={"kebede", "Ayele","Tufa","Almaz", "Kasa"};
for (int i=0; i<5;i++)
cout<<name[i]<<'\n';
}
Example 13
The following program takes your name and tells the length of your name.
#include<iostream.h>
#include<string.h>
#include<conio.h>
void main()
{
char name[25];
cout<<"Enter your name: ";

20

cin>>name;
cout<<"your name is "<<strlen(name)<<" characters long";
getch();
}
Example 14
#include<iostream.h>
#include<string.h>
#include<conio.h>
void main ()
{
const int SIZE=100;
char str1[SIZE];
char str2[SIZE];
cout<<"Enter a string\n";
cin.get(str1,SIZE);
strcpy(str2,str1);
cout<<"Copy of your string is \n"<<str2;
getch ();
}
Example 15
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main ( )
{ const int p=30;
char ch1[50],ch2[100]="I am proud ";
cout<<ch2<<endl;
cout<<"Enter a string to concatenate :";
cin.get(ch1,50);
strcat(ch2,ch1);
cout<<"The concatenated is "<<ch2;
getch();
}
Example: the following program takes two words from a user and compares their
alphabetical precedence.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
const int p=15;
char ch1[p],ch2[p];
cout<<"Enter first string: ";
cin>>ch1;
cout<<"enter second string: ";

21

cin>>ch2;
if(strcmp(ch1,ch2) = = 0)
cout<<"The two words are the same";
else if(strcmp(ch1,ch2)>0)
cout<<ch2<<" comes first alphabetically";
else if(strcmp(ch1,ch2)<0)
cout<<ch1<<" comes first alphabetically";
getch();
}
Examples
The following C++ program reads your name from keyboard and display it in reverse order.
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<iomanip.h>
void main ( )
{ char name[20];
cout<<"Enter your name \t";
cin>>setw(20)>>name;
for(int i=(strlen(name)-1);i>=0;i--)
cout<<name[i];
getch();
}

Exercise
1. Define two functions which, respectively, input values for the elements of an array
of reals and output the array elements:
void ReadArray (double nums[], const int size);
void WriteArray (double nums[], const int size);

2. Define a function which reverses the order of the elements of an array of reals:
void Reverse (double nums[], const int size);

3. The following table specifies the major contents of four brands of breakfast cereals.
Define a two-dimensional array to capture this data:
Top Flake
Cornabix
Oatabix
Ultrabran

Fiber
12g
22g
28g
32g

Sugar
25g
4g
5g
7g

Fat
16g
8g
9g
2g

Salt
0.4g
0.3g
0.5g
0.2g

Write a function which outputs this table element by element.


4. Write a C++ program that stores a 4 by 5 integer matrix and display it.
5. Write a C++ program that adds two matrices.
22

Structure
Example. 1
#include<iostream.h>
#include<conio.h>
struct student
{
char name [20];
char id_num[11];
int age ;
};
Void main ( )
{
clrscr( );
student stud1;
cout<<"Enter name of the student: ";
cin>> stud1. name;
cout<<"id number: ";
cin>>stud1. id_num;
cout<<"Enter age: ";
cin>>stud1.age;
cout<<"\n Name: "<< stud1.name;
cout<<"\n id Number: "<<stud1.id_num;
cout<<"\n age: "<<stud1.age;
getch( );
}
Example.2
#include <iostream.h>
#include <string.h>
#include <conio.h>
struct movies_t {
char title [60];
int year;
} mine, yours;
void printmovie (movies_t movie);
int main ()
{
strcpy(mine.title,"2001 A Space Odyssey");
mine.year = 1968;

23

cout << "Enter your favorite Film title: \n";


cin.get (yours.title,60);
cout << "Enter year: \n";
cin>>yours.year;
cout << "\n My favorite movie is:\n ";
printmovie (mine);
cout << "And yours is:\n ";
printmovie (yours);
return 0;
}
void printmovie (movies_t movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
Example.3
#include<iostream.h>
#include<conio.h>
const int NAME = 25;
const int ID = 11;
struct student
{
char name [NAME];
char id-num[ID];
int age;
}
Void main ( )
{
clrscr( );
student stud1 = { Alem , 019/97,25};
student stud2;
stud2= stud1;
cout<<name:<<stud1.name:
cout<<\nID: << stud1. id_num;
cout\n Copied data << endl;
cout<<Name: << stud2. name;
cont<<\nID: <<stud2.id_num;
cout<<\n Age:<<stud2.age;
getch ( );
}
Example.4

24

#include<iostream.h>
#include<conio.h>
struct person
{
string name;
int age;
//of course, member variables must be present
void print ()
{
cout << name << ";" << age << endl;
/*we don't have to mention what "name" and "age" are,
because it automatically refers back to the
member variables */
}
};
int main ()
{
person a, b;
a.name = "Wales";
b.name = "Jones";
a.age = 30;
b.age = 20;
cout << a.name << ": " << a.age << endl;
cout << b.name << ": " << b.age << endl;
a.print();
b.print();
return 0;
}
a and b above are called senders, and each of them will refer to their own member variables
when the print() function is executed.
Example.5
movies_t user [N];
#include <iostream.h>
#include <string.h>
#include <sstream.h>
#define N 50
struct movies_t {

25

char title [60];


int year;
} user [N];
void printmovie (movies_t movie);
int main ()
{
for (int n=0; n<N ; n++)
{
cout << "Enter title: ";
cin.get (user[n].title,N);
cout << "Enter year: ";
cin>>user[n].year;
}
cout << "\nYou have entered these movies:\n";
for (n=0; n<N_MOVIES; n++)
printmovie (films[n]);
return 0;
}
void printmovie (movies_t movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
Example 6
// pointers to structures
#include <iostream.h>#include <string.h>
#include <sstream.h>
struct movies_t {
char title[50];
int year;
};
int main ()
{ string mystr;
movies_t amovie;
movies_t * pmovie;
pmovie = &amovie;

26

cout << "Enter title: ";


cin.get (pmovie->title, 50);
cout << "Enter year: ";
cin>>year;
cout << "\nYou have entered:\n";
cout << pmovie->title;
cout << " (" << pmovie->year << ")\n";
return 0;
}
Example 7
#include <iostream.h>
#include <conio.h>
const int STR = 30 ;
struct address
{
char street [STR];
char post ;
float distance ; //in kilometers
};
struct employee
{
address branch;
address home ;
}
void main( )
{
clrscr ( );
employee emp1;
// employee branch adderase
cout << enter branch street of the employee:;
cin.get (emp1. branch.street, STR);
cout<<enter branch post address;
cin>>emp1.branch. Post;
cout<<enter distance of the branch;
cin>>emp1.branch.distance;
// employee home adderase
cout << enter home street of the employee:;
cin.get (emp1. home.street, STR);

27

cout<<enter home post address;


cin>>emp1.home. Post;
cout<<enter distance of the home;
cin>>emp1.home.distance;
cout<< Employees branch street is :<<emp1.
branch. street <<and it is <<emp1.
Branch. distance << kms. Away ;
getch( );
}
Exercise:
Write a program using structure which accepts information on five books. The inf. includes
title of the book, and publication year. There is another information about the book, called
status, status will automatically be given by the program based on the publication year
entered by the user, if year of put publication is before 1990, the status is a Out dated; if
the book is published between 1991-2000, the status will automatically be medium, for
books published after the year 2000, status will be latest, the program should output what
is entered by the user in the following ways as an example.
Title:
Publication year:
Status:

Adama University
Department of CSIT
Cpp-Lab-8&9 Exercise
FILE INPUT/OUTPUT
Example1 : the following program writes strings to a file
#include<fstream.h>
// for ofstream
void main( )
{
ofstream my_ofile ("test.txt");
my_ofile<<"This is a trial text\n";
my_ofile<<"to be written in disk file \n";
my_ofile<<"by file name \"Test\".\n";
}
Example2

the following program reads string from file.


#include<fstream.h>
#include<conio.h>
void main ( )
{
const int MAX=80;
char line[MAX];

28

ifstream my_ifile("test.txt");
while (my_ifile)
{
my_ifile.getline(line,MAX);
cout<<line<<endl;
}
getch( );
}
Example 3

the following program writes as string, character by character, to a file.

#include<fstream.h>
#include<string.h>
void main ( )
{
char str[]="this string will be written to a file character by character";
ofstream o_file("test2.txt");
for(int j=0;j<strlen(str);j++)
o_file.put(str[j]);
}
Example 4
The following program reads characters from a file and displays then to the monitor.
#include <fstream.h>
#include<conio.h>
void main()
{
char ch;
ifstream i_file ("test2.txt");
while (i_file)
{
i_file.get(ch);
cout<<ch;
}
getch( );
}
Example 5
#include<fstream.h>
#include<conio.h>
#include<ctype.h>
// for the function toupper( )
struct person
{
char name [25];
int age;
};
void main ( )
{ clrscr();
char ans;
person pers;
fstream my_rec;
my_rec.open ("record1",ios::app|ios::out);
do{
cout<<"Enter name: ";

29

cin>>pers.name;
cout<<"Enter age: ";
cin>>pers.age;
my_rec.write ((char*)& pers, sizeof(pers));
cout<<"Add more? [Y/N]";
cin>>ans;
ans=toupper(ans);
} while(ans=='Y');
getch();
}

Example 6 : opening a file both for writing and reading.


#include<fstream.h>
#include<conio.h>
#include<ctype.h>
// for the function toupper( )
struct person
{
char name[25];
int age;
};
void main()
{
clrscr();
char ans;
person pers;
fstream my_rec;
my_rec.open ("record2",ios::app|ios::out| ios:: in );
do{
cout<<"Enter name ";
cin>>pers.name;
cout<<"Enter age ";
cin>>pers.age;
my_rec.write((char*)&pers, sizeof(pers));
cout <<"Add more? [Y/N] ";
cin >> ans;
ans=toupper(ans);
}while (ans=='Y');
cout<<"The data in the file is :\n";
my_rec.seekg(0);
my_rec.read((char*)&pers,sizeof(pers));
while(!my_rec.eof())
{
cout<<"\nName :"<<pers.name<<endl;
cout<<"Age :"<< pers.age <<endl;
my_rec.read((char*)&pers, sizeof(pers));
}
my_rec.close(); // optional
getch();
}
After the while loop and before closing the opened file in the above program, you can add the
following piece of code to know how many persons data is in the opened file.

30

:
int pos;
my_rec.seekg(0,ios::end);
pos=(my_rec.tellg()/sizeof(pers));
cout<<"\nThere are "<<pos<<" people in the file";
:
Remember that the function tellg( ) returns the file pointer byte number (an integer value).
The following program can also read a persons information at a specific number in the file (the file
created by the above program).
#include<fstream.h>
#include<conio.h>
struct person
{
char name[25];
int age;
};
void main()
{
clrscr();
int num,pos;
person pers;
ifstream my_rec("record2");
cout<<"Enter the person's number: ";
cin>>num;
pos=(num-1)*sizeof(pers);
my_rec.seekg(pos);
my_rec.read((char*)&pers, sizeof(pers));
cout<<"\nName :"<<pers.name<<endl;
cout<<"Age :"<< pers.age <<endl;
getch();
}

31

Вам также может понравиться