C++Good EXAMPLES

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 97

SEQUENCE PROGRAMS float F,C;

cout<< "\nEnter temperature in Farenheit : ";


#include<iostream.h>
cin>>F;
using namespace std;
int main() C=5*(F-32)/9;
{ cout<<"Temperature in celcius is : "<<C;
cout<<"subject " <<"\tmarks"<<"\nmathematic\t"
system(“PAUSE”);
<<90<<"\ncomputer\t"<<77<<"\nchemistry\t"<<69;
return 0;
system("PAUSE"); }
return 0; Write a program which accept principle, rate and time from
} user and calculates the simple interest using the formula
//2. Program to add two integers input by user i=(p*r*t)/100
#include<iostream>
#include<iostream >
using namespace std;
using namespace std;
int main()
int main()
{
{
int a,b,c;
int p,r,t,i;
cout<< "\nEnter first number : ";
cout<<"Enter Principle : ";
cin>>a;
cin>>p;
cout<<"\nEnter second number : ";
cout<<"Enter Rate : ";
cin>>b;
cin>>r;
c=a+b;
cout<<"Enter Time : ";
cout<<"\nThe Sum is : "<<c;
cin>>t;
system(“PAUSE”);
i=(p*r*t)/100;
return 0;
cout<<"Simple interest is : "<<i;
}
system(“PAUSE”);
Write a program which accept temperature in Farenheit and
return 0;
print it in centigrade using C=5*(F-32)/9
}
#include<iostream.h> Write a program to swap the values of two variables
int main() #include<iostream>
{ using namespace std;

1
int main() Write a program to check whether the given number is
{ positive or negative (using ? : ternary operator )
int a,b,temp; #include<iostream>
cout<<"\nEnter two numbers : "; using namespace std;
cin>>a>>b; int main()
temp=a; {
a=b; int a;
b=temp; cout<<"Enter any non-zero Number : ";
cout<<"\nAfter swapping numbers are : "; cin>>a;
cout<<a<<" "<<b; (a>0)?cout<<"Number is positive":cout<<"Number is
negative";
system(“PAUSE”);
return 0; system(“PAUSE”);
} return 0;
}
Write a program to calculate area of circle.

#include<iostream> #include<iostream>
using namespace std; using namespace std;
int mynum(int a);
int main() int main()
{ {
float r,area; int a;
cout<< "\nEnter radius of circle : "; cout<<mynum(a);
cin>>r; system("PAUSE");
area = 3.14*r*r; return 0;
cout<<"Area of circle : "<<area; }
system(“PAUSE”); int mynum(int a)
return 0; {
} cout<<"Enter number :";
cin>>a;

2
(a>0)?cout<<"Number is positive":cout<<"Number is #include<iostream>
negative"; using namespace std;
int main()
} {
Write a program which input three numbers and display the int amt,R500,R100,R50,R20,R10,R5,R1;
largest number using ternary operator. cout<<"Enter amount : ";
cin>>amt;
#include <iostream> R500=amt/500;
using namespace std; amt=amt%500;
R100=amt/100;
int main() amt=amt%100;
{ R50=amt/50;
int a,b,c,greatest; amt=amt%50;
cout<<"Enter three numbers : "; R20=amt/20;
cin>>a>>b>>c; amt=amt%20;
greatest=(a>b&&a>c)?a:(b>c)?b : c; R10=amt/10;
cout<<"Greatest number is "<<greatest; amt=amt%10;
R5=amt/5;
system(“PAUSE”); amt=amt%5;
return 0; R1=amt;
} cout<<"Rs.500 : "<<R500<<"\nRs.100 : "<<R100<<"\
nRs. 50 : "<<R50<<
"\nRs. 20 : "<<R20<<"\nRs. 10 : "<<R10<<"\nRs.
5 : "<<R5<<"\nRe. 1 : "<<R1;

system(“PAUSE”);
return 0;
}
Write a program which accepts amount as integer and
Write a program which accepts a character and display its
display total number of Notes of Rs. 500, 100, 50, 20, 10, 5
next character.
and 1.
#include<iostream>

3
using namespace std; int t;
cout<<"Enter force of gravity :";
int main() cin>>g;
{ cout<<"Enter Velocity :";
char ch; cin>>v;
cout<< "\nEnter any character : "; t=2*v/g;
cin>>ch; {
ch++; cout<<"Time of Flight :";
cout<<"Next character is : "<<ch; cout<<t<<" ";
system(“PAUSE”); }
return 0; system("PAUSE");
} return (0);
}
#include <iostream>
using namespace std;
int main () Write the output of the following program :
{ #include <iostream.h>
int a,b,c; void X(int &A, int &B)
a=2; {
b=7; A = A + B;
c = (a>b) ? a : b; B = A - B;
cout << c; A=A-B;
system("PAUSE"); }
return 0; void main()
} {
#include <iostream> int a = 4, b =18;
using namespace std; X(a,b);
int main() cout<<a<<”,”<<b;
{
int v=0; }
int g=0; #include<iostream>

4
using namespace std; z= 5 + subtraction (x,y);
int main() cout << "The fourth result is " << z << '\n';
{ system("PAUSE");
float r,area, circum; return 0;
cout<< "\nEnter radius of circle : "; }
cin>>r;
area = 3.14*r*r; FUNCTIONS
circum=2*(3.14)*r;
cout<<"Area of circle : "<<area<<endl; Call by Value
cout<<"Circumference of circle : "<<circum; #include <iostream>
system("PAUSE"); using namespace std;
return (0);
// function declaration
}
void swap(int x, int y);

int main ()
{
#include <iostream> // local variable declaration:
using namespace std; int a = 100;
int subtraction (int a, int b) int b = 200;
{
int r; cout << "Before swap, value of a :" << a << endl;
r=a-b; cout << "Before swap, value of b :" << b << endl;
return (r);
// calling a function to swap the values.
}
swap(a, b);
int main ()
{ cout << "After swap, value of a :" << a << endl;
int x=30, y=10, z; cout << "After swap, value of b :" << b << endl;
z = subtraction (25,20);
cout << "The first result is " << z << '\n'; return 0;
cout << "The second result is " << subtraction (25,20) << '\n'; }
cout << "The third result is " << subtraction (x,y) << '\n'; // function definition to swap the values.
void swap(int x, int y)

5
{ total=a+b;
int temp; return total;
}
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into y */ Write a function to calculate the factorial value of any
integer as an argument. Call this function from main( ) and
return; print the results in main( ).
}
#include<iostream>
Write a C++ program using function which accept two using namespace std;
integers as an argument and return its sum. Call this function int factorial(int);
from main( ) and print the results in main( ). int main()
{
#include<iostream.h>
int x,f;
using namespace std;
cout<<"Enter number : ";
int sum(int, int);
cin>>x;
int main()
f=factorial(x);
{
cout<<"The factorial is :"<<f;
int x,y,s;
getch();
cout<<"Enter first number : ";
return 0;
cin>>x;
}
cout<<"Enter second number : ";
int factorial(int a)
cin>>y;
{
s=sum(x,y);
int fact=1;
cout<<"The sum is : "<<s;
while(a>=1)
{
getch();
fact=fact*a;
return 0;
a--;
}
}
int sum(int a, int b)
return fact;
{
}
int total;

6
# include <iostream> #include<iostream>
using namespace std; using namespace std;
void odd (int a); long int fact(int);
void even(int a); iint main()
int main () {
{ int x,n;
int i; cout<<"Enter an Integer\n";
do cin>>n;
{ x=fact(n);
cout << " Type a number (Type 0 to exit):"; cout<<"Value="<<n<<"factorial=";
cin >> i; cout<<x<<endl;
odd (i); system("PAUSE");
} return 0;
while (i!=0); }
return 0; long int fact(int n)
} {
void odd (int a) int value=1;
{ if (n==1)
if ((a%2) !=0) cout << "Number is odd.\n"; return(value);
else even(a); else
} {
void even (int a) for(int i=1;i<=n;i++)
{ value=value*i;
if ((a%2) == 0) cout << "Number is even.\n"; return(value);
}
else odd (a); }

7
cout<<"Enter number";
#include <iostream> cin>>x;
using namespace std; f=factorial(x);
void print(int i) cout<<"The factorial is :"<<f;
{ getch();
cout << " Here is int " << i << endl; return 0;
} }
void print(double f) int factorial(int a)
{ {
cout << " Here is float " << f << endl; int fact=1;
}
while(a>=1)
void print(char* c) {
{ fact=fact*a;
cout << " Here is char* " << c << endl; a--;
} }

int main() { return fact;


print(10); }
print(10.10); #include<iostream>
print("ten"); using namespace std;
system("PAUSE"); int multiply (int a, int b)
} {
int c;
c=a*b;
return(c);
#include<iostream.h> }
#include<conio.h> int main()
int factorial(int); {
int main() int c;
{ c=multiply(5,3);
int x,f;
8
cout<<"the result is"<<c; cin >> b;
system("PAUSE"); int c = sum(a, b);
return 0; cout << "sum = " << c << endl;
} system("PAUSE");
}
#include <iostream> int sum(int a, int b)
using namespace std; {
int sum(int a, int b); //declare the function return a + b;
int main() { }
int a, b;
cout << "Enter a number ";
cin >> a; Program to read two numbers from the keyboard and print
cout << "Enter another number "; the sum using a function
cin >> b;
int c = sum(a, b); //call the sum function #include <iostream>
cout << "sum = " << c << endl; using namespace std;
system("PAUSE");
} int sum(int a, int b); //declare the function
int sum(int a, int b)
{ int main() {
return a + b; int a = 0, b = 0;
} cout << "Enter a number ";
#include <iostream> cin >> a;
using namespace std;
int sum(int a, int b); cout << "Enter another number ";
int main() cin >> b;
{
int a, b; int c = sum(a, b); //call the sum function
cout << "Enter a number ";
cin >> a; cout << "sum = " << c << endl;
cout << "Enter another number ";
system("pause");

9
} y = add(c, d);

int sum(int a, int b){ cout << "Sum of floats: " << y << endl;
return a + b;
} return 0;
}

#include <iostream> long add(long x, long y)


{
using namespace std; long sum;

/* Function arguments are of different data type */ sum = x + y;

long add(long, long); return sum;


float add(float, float); }

int main() float add(float x, float y)


{ {
long a, b, x; float sum;
float c, d, y;
sum = x + y;
cout << "Enter two integers\n";
cin >> a >> b; return sum;
}
x = add(a, b);

cout << "Sum of integers: " << x << endl;

cout << "Enter two floating point numbers\n"; Program which uses a function to calculate hour rates
cin >> c >> d; #include <iostream>
using namespace std;

10
cout << "Before swap, value of a :" << a << endl;
int vacation(int d, int h) cout << "Before swap, value of b :" << b << endl;
{ /* calling a function to swap the values using variable
int r; reference.*/
r = d*h; swap(a, b);
return(r); cout << "After swap, value of a :" << a << endl;
cout<<"The user has "<<r<< "Hours"; cout << "After swap, value of b :" << b << endl;
cout<<"Enjoy!"; return 0;
} }
int main() // function definition to swap the values.
{ void swap(int &x, int &y)
int z, a,b; {
b=24; int temp;
cout<<"Enter Number Of Vacation Days"; temp = x; /* save the value at address x */
cin>>a; x = y; /* put y into x */
y = temp; /* put x into y */
z = vacation(a,b);
if (a>5) return;
cout<<"Enjoy!"; }
cout<<"Your Number of Hours are:"<<z;
system ("PAUSE"); #include<iostream>
} using namespace std;
#include <iostream> int sum_first_last(int first,int last)
using namespace std; {
// function declaration int result=0;
void swap(int &x, int &y); for(int a=first;a<=last;a++)
int main () {
{ result=a+result;
// local variable declaration: }
int a = 100; return result;
int b = 200; }

11
int main()
{ return fact;
int first,last; }
cout<<"enter first and last"<<endl; #include<iostream>
cin>>first>>last; using namespace std;
cout<<"sum first last range= long factorial(int);
"<<sum_first_last(first,last)<<endl; int main()
return 0; {
} int counter, n;
cout<<"Enter the Number :";
#include<iostream> cin>>n;
using namespace std; cout<<n<<" Factorial Value Is "<<factorial(n);
long factorial(int); system("PAUSE");
int main() return 0;
{ }
int counter, n; // Factorial recursion Function
cout<<"Enter the Number to calculate factorial :"; long factorial(int n)
cin>>n; {
cout<<n<<" Factorial Value Is "<<factorial(n); if (n == 0)
return 1;
system("PAUSE"); else
return 0; return(n * factorial(n-1));
} }
long factorial(int n)
{ #include<iostream>
int counter; using namespace std;
long fact = 1; int main()
for (int counter = 1; counter <= n; counter++) {
{ // Variable Declaration
fact = fact * counter; int counter, n;
} long last=1,next=0,sum;

12
// Get Input Value int iF0 = 0;
cout<<"Enter the Number :"; int iF1 = 1;
cin>>n; for (int i = 2; i <= iN; ++i) {
//Fibonacci Series Calculation iF1 += iF0;
while(next<n/2) iF0 = iF1 - iF0;
{ }
cout<<last <<" "; return iF1;
sum=next+last; }
next=last; int main()
last=sum; {
} for (int i = 0; i < 12; ++i) {
system("PAUSE"); std::cout << "n = " << i << " Fn = " << FibonacciRecur(i) <<
return 0; std::endl;
} std::cout << "n = " << i << " Fn = " << FibonacciIter(i) <<
#include <iostream> std::endl;
using namespace std; }
int FibonacciRecur(int iN) system("PAUSE");
{ return 0;
// Stopping condition }
if (iN < 3) {
if (iN < 1) {
return 0;
}
return 1; #include <iostream>
} using namespace std;
return FibonacciRecur(iN - 1) + FibonacciRecur(iN - 2); //program factorial using functions
} long int fact(int); //function prototype
int FibonacciIter(int iN) {
if (iN <= 0) { int main()
return 0; {
} int x, n;

13
cout << "Enter an integer number \n"; void main()
cin>>n; {
x=fact(n); int a=4, b=l8;
X(a,b);
cout<< "Value ="<<n<<"factorial="; cout<< a <<”,”<<b;
cout<<x<<endl; }
system("PAUSE");
return 0; #include <iostream>
} using namespace std;
long int fact(int n) void HowMany(int *numbers);
{ void CalculateFibonacci(int *numbers);
int main()
{
int value =1;
int numbers = 0;
if (n==1) HowMany(&numbers);
return(value); CalculateFibonacci(&numbers);
else system("PAUSE");
{ return 0;
for(int i=1; i<=n;++i) }
value = value*i; void HowMany(int *numbers)
return(value); {
} // use pointers as parameter, not references
} std::cout << "How many Fibonacci numbers would you like to
calculate? ";
std::cin >> *numbers;
Write the output of the following program:
if ((!std::cin.good()) || ( *numbers <= 1 || ( *numbers >= 48 )))
#include <iostream.h> {
printf("Invalid number entered ! I calculate only more than 0 or
void X(int A, int &B)
less then 48 Fibonacci numbers !! \n");
{
exit(1);
A = A+B; }
B = A-B; }
A = A-B; void CalculateFibonacci(int *numbers)
} {

14
int i = 0; // Declare and initialize an array of strings.
unsigned long a = 1; string strings[] =
unsigned long b = 0; {"Africa","Congo","Botwsana","Mozambique","Zimbabwe"};
unsigned long fibonacci_number = 0;
while(i < *numbers) { // Sort the array with STL sort.
b= fibonacci_number;
fibonacci_number = a + b; sort(strings, strings + 5, sort_strings);
std::cout << "Fibonacci number: " << i+1 << ". " << for(int i=0; i < sizeof(strings)/sizeof(string); i++)
fibonacci_number << "\n";
a = b; {
i++;
} cout << strings[i] << endl;
std::cout << std::endl;
} }
system("PAUSE");
return 0;
}
Program to show string manipulation

#include <iostream>
#include <string>
using namespace std;
STRINGS
int main ()
#include <string> {
#include <algorithm> string mystring = "This is a string";
#include <iostream> cout << mystring;
using namespace std; system("PAUSE");
bool sort_strings(const string& a, const string& b) return 0;
}
{
return a < b; #include <iostream>
} #include <string>
int main(int argc, char *argv[])
using namespace std;
{

15
string reverse (string str1) string str;
{ char temp;
string str; int i,len;
char temp; cout<<"Reserved string is ";
int i,len;
cout<<"Reserved string is "; str = str1;
len=str.length();
str = str1; for(i=0;i<str.length();i++)
len=str.length(); {
for(i=0;i<str.length();i++) str1[len-1-i]= str[i];
{ }
str1[len-1-i]= str[i]; return str1;
} }
return str1; int main()
} {
int main() string str;
{ do {
string str; cin >> str;
do { cout << reverse(str) << "\n";
cin >> str; } while (str != "no");
cout << reverse(str) << "\n"; system("PAUSE");
} while (str != "no"); return 0;
system("PAUSE"); }
return 0; #include <iostream>
} #include <string>
using namespace std;
#include <iostream>
#include <string> int main ()
using namespace std; {
string reverse (string str1) string mystr;
{ cout << "What's your name? ";

16
getline (cin, mystr); cout << " I like" << mystring <<" too \n";
cout << "Hello " << mystr << ".\n"; system ("PAUSE");
cout << "What is your favorite team? "; return 0;
getline (cin, mystr); }
cout << "I like " << mystr << " too!\n";
system("PAUSE"); #include <iostream>
return 0;
} using namespace std;
//program to find largest value in an array
#include <iostream>
#include <string> #define size 100
using namespace std; int main()
{
int main () int a[size];
{ int i, n, large;
string mystring = "This is a string"; cout << "Enter array size ";
cout << mystring; cin>>n;
system("PAUSE"); cout << "Enter the elements \n";
return 0; for (i=0; i<=n-1; ++i)
} {
# include <iostream> cin>>a[i];
# include <string> }
using namespace std; cout << "Contents of the array \n";
int main() for (i=0; i<=n-1; ++i)
{ {
string mystring; cout<<a[i]<<'\t';
cout<<"What is your name"; }
getline (cin, mystring); cout<<endl;
cout<<"Hello"<< mystring<<"\n"; large = a[0];
cout <<"Whats your Fvourite Team"; for (i=0; i<=n-1; ++i)
getline (cin, mystring); {

17
if (large < a[i]) double GetHours(string FullName);
(large = a[i]);
} FullName = GetName();
cout << "Largest element ="<<large; Hours = GetHours(FullName);
system("PAUSE");
return 0; cout << "\nEmployee's Name: " << FullName;
cout << "\nWeekly Hours: " << Hours << " hours\n\n";
system("PAUSE");
} return 0;
}
#include <iostream>
#include <string> double GetHours(string FullName)
using namespace std; {
double Mon, Tue, Wed, Thu, Fri, TotalHours;
string GetName()
{ cout << endl << FullName << "'s Weekly Hours\n";
string FirstName, LastName, FN; cout << "Monday: "; cin >> Mon;
cout << "Tuesday: "; cin >> Tue;
cout << "Employee's First Name: "; cout << "Wednesday: "; cin >> Wed;
cin >> FirstName; cout << "Thursday: "; cin >> Thu;
cout << "Employee's Last Name: "; cout << "Friday: "; cin >> Fri;
cin >> LastName;
TotalHours = Mon + Tue + Wed + Thu + Fri;
FN = FirstName + " " + LastName; return TotalHours;
return FN; }
}
#include <string>
int main() #include <iostream>
{ using namespace std;
string FullName; int main(int argc, char *argv[])
double Hours;
{

18
#include <iostream>
char text[] = "Hello there"; using namespace std;
// Display the 'H' int main()
{
cout << text[0] << endl;
// Display the null-terminator as a number cout << "Enter a number: ";
int nX;
cout << (int)text[11] << endl; cin >> nX;
system("PAUSE"); if (nX > 10)
return 0; cout << nX << "is greater than 10" << endl;
else if (nX < 5)
cout << nX << "is less than 5" << endl;
} else
cout << nX << "is between 5 and 10" << endl;
#include<iostream> system("PAUSE");
# define SIZE 100
#include<string> return 0;
using namespace std; }
int main() #include <iostream>
{ using namespace std;
int main()
char arr[SIZE];
{
cout<<"write a sentence"<<endl;
int age;
gets(arr); cout<<"Please input your age: ";
strrev(arr); cin>> age;
cout<<"the reversal is\t"<<arr<<endl;
system("PAUSE"); if ( age < 50 )
return 0; {
} cout<<"You are pretty young!\n";
}
else if ( age == 50 )
{
BRANCHING cout<<"You are old\n";
}

19
else using namespace std;
{ int main()
cout<<"You are really old\n"; { int n, c, first = 0, second = 1, next;
} cout << "Enter the number of terms of Fibonacci series you
want" << endl;
return 0;
cin >> n;
}
cout << "First " << n << " terms of Fibonacci series are :- " <<
endl;
for ( c = 0 ; c < n ; c++ )
Program to calculate factorial {
if ( c <= 1 )
#include <iostream> next = c;
using namespace std; else
long factorial (long a) {
{ next = first + second;
if (a > 1) first = second;
return (a * factorial (a-1)); second = next;
else }
return (1); cout << next << endl;
} }
int main () system("PAUSE");
{ long number; return 0;
cout << "Please type a number: "; }
cin >> number;
cout << number << "! = " << factorial (number);
system("PAUSE");
return 0; The marks obtained by a student in 5 different subjects are
} input by the user. The student gets a division as per the
following rules:
Program to calculate the FIbbonnacii series Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
#include<iostream> Percentage between 40 and 49 - Third division
20
Percentage less than 40 - Fail {
Write a program to calculate the division obtained by the float a,b,c,d,root1,root2;
student. cout<<"Enter value of a, b and c : ";
cin>>a>>b>>c;
#include<iostream> d=b*b-4*a*c;
using namespace std; if(d==0)
int main() {
{ root1=(-b)/(2*a);
int sub1,sub2,sub3,sub4,sub5,percentage; root2=root1;
cout<<"Enter marks of five subjects : "; cout<<"Roots are real & equal";
cin>>sub1>>sub2>>sub3>>sub4>>sub5; }
percentage=(sub1+sub2+sub3+sub4+sub5)/5; else if(d>0)
{
if(percentage>=60) root1=-(b+sqrt(d))/(2*a);
cout<<"Ist division"; root2=-(b-sqrt(d))/(2*a);
else if(percentage>=50) cout<<"Roots are real & distinct";
cout<<"IInd division"; }
else if(percentage>=40) else
cout<<"IIIrd division"; {
else root1=(-b)/(2*a);
cout<<"Fail" ; root2=sqrt(-d)/(2*a);
system(“PAUSE”); cout<<"Roots are imaginary";
return 0; }
} cout<<"\nRoot 1= "<<root1<<"\nRoot 2= "<<root2;
system(“PAUSE”);
Write a program to find the roots of a quadratic equation of return 0;
type ax2+bx+c where a is not equal to zero. }
#include<iostream>
#include<math.h> In a company an employee is paid as under:
using namespace std; If his basic salary is less than US$. 1500, then HA = 10% of
int main() basic salary

21
and TA = 90% of basic salary. Write a program to check whether a triangle is valid or not,
If his salary is either equal to or above US$. 1500, then HA = when the three angles of the triangle are entered by the
US$. 500 user. A triangle is valid if the sum of all the three angles is
and TA = 98% of basic salary. equal to 180 degrees.
If the employee's salary is input by the user write a program
to find his gross salary. #include<iostream>
using namespace std;
#include<iostream>
using namespace std; int main()
int main() {
{ int angle1,angle2,angle3;
float basic_salary, gross_salary, HRA, DA; cout<<"Enter the three angles of triangle:";
cout<<"Enter basic salary of Employee : "; cin>>angle1>>angle2>>angle3;
cin>>basic_salary;
if (basic_salary<1500) if (angle1+angle2+angle3==180)
{ cout<<"Triangle is valid";
HRA=0.1*basic_salary; else
DA=0.9*basic_salary; cout<<"Triangle is not valid";
}
else system(“PAUSE”);
{ return 0;
HRA=500; }
DA=0.98*basic_salary; Any year is input by the user. Write a program to determine
} whether the year is a leap year or not.

gross_salary=basic_salary+HRA+DA; #include<iostream.h>
cout<<"Gross salary is : "<<gross_salary; using namespace std;
int main()
system(“PAUSE”); {
return 0; int year;
} cout<<"Enter the year : ";
cin>>year;

22
if( (year%400==0 || year%100!=0) &&(year%4==0)) cout << "This is the month of March " ;
cout<<"It is a leap year"; break ;
else }
cout<<"It is not a leap year"; case 4:
system(“PAUSE”); {
return 0; cout << "This is the month of April " ;
} break ;
}
Program to show the switch case statement case 5:
{
#include<iostream> cout << "This is the month of May" ;
using namespace std; break ;
main() }
{ case 11:
int num; {
cout<<"Enter the Number of a Month: " ; cout << "This is the month of November " ;
cin>>num; break ;
cout<<endl; }
switch (num) case 12:
{ {
case 1: cout << "This is the month of December" ;
{ break ;
cout << "This is the month of January " ; }
break ; default:
} {
case 2: cout << "Your entered number is invalid" ;
{ break ;
cout << "This is the month of February " ; }
break ; }
} system("PAUSE");
case 3: return 0;
{

23
}
#include<iostream> break;
//#include<conio.h> default :
using namespace std; grade='U';
int main() }
{
int mark1,mark2, mark3, mark4, mark5, marks; cout<<"\n Your Grade is = "<<grade<<endl;
char grade; // getch();
cout<<"enter marks out of 100"<<endl; system("PAUSE");
cout<<"Enter Mark1"<<"Enter Mark2"<<"Enter return 0;
Mark3"<<"Enter Mark4"<<"Enter Mark5"<<endl;
cin>>mark1>>mark2>>mark3>>mark4>>mark5; }
marks=(mark1+ mark2+ mark3 + mark4 + mark5); Program to calculate Class average
switch(marks/5) #include <iostream>
{ using namespace std;
case 100 : int main()
grade='A'; {
break; int total,
case 70 : gradeCounter, grade, average;
grade='B'; total = 0;
break; gradeCounter = 1;
while ( gradeCounter <= 10 )
{
case 50 : cout << "Enter grade: ";
grade='C'; cin >> grade;
break; total = total + grade;
gradeCounter = gradeCounter + 1;
case 40 : }
grade='D'; average = total / 10;
cout << "Class average is " << average << endl;
case 30 : system("PAUSE");
grade='E'; return 0;
}

24
return 0;
#include<iostream> }
using namespace std;
int main() #include<iostream>
{ using namespace std;
double a,b; int main()
char operation; {
cout<<"enter two values a and b\n"; int n,c,first=0,second=1,next;
cout<<"a="; cout<<"enter number of terms of the series"<<endl;
cin>>a; cin>>n;
cout<<"b="; cout<<"terms of fibbonacci"<<endl;
cin>>b; for(c=0;c<n;c++)
cout<<"enter letter for operation\n"<<"'a'-add:a+b\n"<<"'d'- {
divison:a/b\n"<<"'m'-multiply:a*b\n"<< if(c<=1)
"'s'-subtract:a-b\n"; next=c;
cin>>operation; else
switch (operation) next=first+second;
{ first=second;
case 'a': second=next;
cout<<"a+b="<<a+b<<'\n'; cout<<next;
break; cout<<endl;
case 'd': }
cout<<"a/b="<<a/b<<'\n'; // system("PAUSE");
break; return 0;
case 'm': }
cout<<"a*b="<<a*b<<'\n'; }
break; #include <iostream>
case 's': #include<math.h>
cout<<"a-b="<<a-b<<'\n'; using namespace std;
break; double power(int num, int pow1)
default:cout<<"incorrect operation\a\a\a try again";
{
cout<<endl;
if (pow1==0)
}
//system ("PAUSE"); return 1;
else if
25
(pow1==1) and input the numbers. Furthermore, your program must
return num; consist of following functions:
else 1. Function showChoice: This function shows the options to
return (num*pow(num,pow1-1)); the user and explains how to enter data.
2. Function add: This function accepts two number as
} arguments and returns sum.
3. Function subtract: This function accepts two number as
int main() arguments and returns their difference.
{ 4. Function mulitiply: This function accepts two number as
int n,pw; arguments and returns product.
cout<<"enter your number"; 5. Function divide: This function accepts two number as
cin>>n; arguments and returns quotient.
cout<<endl<<"enter the power";
cin>>pw; #include <iostream>
cout<<endl; using namespace std;
cout<<"the result is"<<power(n,pw); void showChoices();
float add(float, float);
system("PAUSE"); float subtract(float, float);
float multiply(float, float);
return 0; float divide(float, float);

} int main()
{
float x, y;
int choice;
MENU DRIVEN FUNCTIONS do
{
showChoices();
cin >> choice;
3. Write a program that lets the user perform arithmetic switch (choice)
operations on two numbers. Your program must be menu {
driven, allowing the user to select the operation (+, -, *, or /) case 1:

26
cout << "Enter two numbers: ";
cin >> x >> y; void showChoices()
cout << "Sum " << add(x,y) <<endl; {
break; cout << "MENU" << endl;
case 2: cout << "1: Add " << endl;
cout << "Enter two numbers: "; cout << "2: Subtract" << endl;
cin >> x >> y; cout << "3: Multiply " << endl;
cout << "Difference " << subtract(x,y) <<endl; cout << "4: Modulas" << endl;
break; cout << "5: Divide " << endl;
case 3: cout << "Enter your choice :";
cout << "Enter two numbers: "; }
cin >> x >> y;
cout << "Product " << multiply(x,y) <<endl; float add(float a, float b)
break; {
case 4: return a+b;
cout << "Enter two numbers: "; }
cin >> x >> y; float subtract(float a, float b)
cout << "Quotient " << divide(x,y) <<endl; {
break; return a-b;
case 5: }
cout << "Enter two numbers: "; float multiply(float a, float b)
cin >> x >> y; {
cout << "DIVISION " << divide(x,y) <<endl; return a*b;
break; }
default: float divide(float a, float b)
cout << "Invalid input" << endl; {
} return a/b;
}while (choice != 5); }

return 0;
}

27
#include <iostream> cout << "Enter two numbers: ";
using namespace std; cin >> x >> y;
cout << "Product " << multiply(x,y)
void showChoices(); <<endl;
float add(float, float); break;
float subtract(float, float); case 4:
float multiply(float, float); cout << "Enter two numbers: ";
float divide(float, float); cin >> x >> y;
cout << "Quotient " << divide(x,y)
int main() <<endl;
{ break;
float x, y; case 5:
int choice; break;
do default:
{ cout << "Invalid input" << endl;
showChoices(); }
cin >> choice; }while (choice != 5);
switch (choice) system("PAUSE");
{
case 1: return 0;
cout << "Enter two numbers: "; }
cin >> x >> y;
cout << "Sum " << add(x,y) <<endl; void showChoices()
break; {
case 2: cout << "MENU" << endl;
cout << "Enter two numbers: "; cout << "1: Add " << endl;
cin >> x >> y; cout << "2: Subtract" << endl;
cout << "Difference " << subtract(x,y) cout << "3: Multiply " << endl;
<<endl; cout << "4: Divide " << endl;
break; cout << "5: Exit " << endl;
case 3: cout << "Enter your choice :";

28
} float x, y;
int choice;
float add(float a, float b) do
{ {
return a+b; showChoices();
} cin >> choice;
switch (choice)
float subtract(float a, float b) {
{ case 1:
return a-b; cout << "Enter two numbers: ";
} cin >> x >> y;
cout << "Sum " << add(x,y) <<endl;
float multiply(float a, float b) break;
{ case 2:
return a*b; cout << "Enter two numbers: ";
} cin >> x >> y;
cout << "Difference " <<
float divide(float a, float b) subtract(x,y)<<endl;
{ break;
return a/b; case 3:
} cout << "Enter two numbers: ";
#include <iostream> cin >> x >> y;
using namespace std; cout << "Product " <<
void showChoices(); multiply(x,y)<<endl;
float add(float, float); break;
float subtract(float, float); case 4:
float multiply(float, float); cout << "Enter two numbers: ";
float divide(float, float); cin >> x >> y;
cout << "Quotient " << divide(x,y)
int main() <<endl;
{ break;

29
case 5: float multiply(float a, float b)
break; {
default: return a*b;
cout << "Invalid input" << endl; }
}
}while (choice != 5); float divide(float a, float b)
{
return 0; return a/b;
} }
#include <iostream>
void showChoices() #include <cstdlib>
{ #include <cmath>
cout << "MENU" << endl; #include <iomanip>
cout << "1: Add " << endl;
cout << "2: Subtract" << endl; using namespace std;
cout << "3: Multiply " << endl;
cout << "4: Divide " << endl; // Function prototypes
cout << "5: Exit " << endl; void showMenu();
cout << "Enter your choice :"; void getUserData(int &, int &, double &);
} void doEstimate(int &, int &, double &, int &, double &, int &,
double &, double &);
float add(float a, float b) void showReport(int &, int &, double &, int &, double &, int &,
{ double &, double &);
return a+b;
} int main()
{
float subtract(float a, float b) int choice = 0;
{ int calcGallonsOfPaint = 0, rooms = 0, totalsqrtfeet = 0;
return a-b; double calcCostOfPaint = 0, costOfPaint = 0;
} int calcHoursOfLabor = 0;
double calcLaborCost = 0;

30
double calcPaintJobCost = 0; showReport(rooms, totalsqrtfeet, costOfPaint,
calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor,
// Set up numeric output formatting. calcLaborCost, calcPaintJobCost);
cout << fixed << showpoint << setprecision(2);
}
do } while (choice != 2);
{ return 0;
// Display the menu and get the user's choice. }
showMenu();
cin >> choice; //
***************************************************
// Validate the menu selection. **************
while (choice < 1 || choice > 2) // Definition of function showMenu which displays the menu.
{ *
cout << "Please enter 1 or 2: "; //
cin >> choice; ***************************************************
} **************

if (choice == 1) void showMenu()


{ {
cout << "\n\t\tPaint Job Estimator Menu\n\n";
//User enters information cout << "1. Get Paint Job Estimate\n";
getUserData(rooms, totalsqrtfeet, costOfPaint); cout << "2. Quit the Program\n\n";
cout << "Enter your choice: ";
//Information from getUserData is used to make }
calculations
doEstimate(rooms, totalsqrtfeet, costOfPaint, /*
calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, After the paint job estimate is displayed, the menu should be
calcLaborCost, calcPaintJobCost); displayed again.
The number of rooms must be at least 1, the price of the paint
//Report is generated from user input and calculations per gallon must be at least $15.00,

31
and the area for the wall space of each room must be greater &calcCostOfPaint, int &calcHoursOfLabor, double
than 10 square feet. &calcLaborCost, double &calcPaintJobCost)
All input validation must be performed with a loop. {
*/

void getUserData(int &rooms, int &totalsqrtfeet, double calcGallonsOfPaint = 1 * (totalsqrtfeet/110);


&costOfPaint) //Calculates the number of whole gallons of paint required.
{
int sqrtfeet; calcCostOfPaint = calcGallonsOfPaint * costOfPaint;
int count = 0; //Calculates the cost of the paint required.

cout << "Please enter the number of rooms to be painted: "; calcHoursOfLabor = calcGallonsOfPaint * 6;
cin >> rooms; //Calculates the number of whole hours of labor required.

cout << "Please enter square feet of wall space in room 1: "; calcLaborCost = calcHoursOfLabor * 15.00;
cin >> sqrtfeet; //Calculates the labor charges.

for (count = 2; count <= rooms; count++) //Calculates the cost of the paint job. This is the sum of the
{ labor charges and the cost of the paint required.
cout << "Please eneter square feet of wall space in calcPaintJobCost = calcLaborCost + calcCostOfPaint;
room " << count << ": ";
cin >> sqrtfeet;
totalsqrtfeet += sqrtfeet; }
}
void showReport(int &rooms, int &totalsqrtfeet, double
cout << "What is the cost of the paint: "; &costOfPaint, int &calcGallonsOfPaint, double
cin >> costOfPaint; &calcCostOfPaint, int &calcHoursOfLabor, double
} &calcLaborCost, double &calcPaintJobCost)
{
void doEstimate(int &rooms, int &totalsqrtfeet, double
&costOfPaint, int &calcGallonsOfPaint, double

32
cout << "The number of rooms to be painted: " << rooms <<
endl; system(“PAUSE”);
cout << "The number of whole gallons of paint required: " return 0;
<< calcGallonsOfPaint << endl; }
cout << "The hours of labor required: " << calcHoursOfLabor
<< endl; #include<iostream.h>
cout << "The cost of the paint: " << calcCostOfPaint << endl; #include<conio.h>
cout << "The labor charges: " << calcLaborCost << endl; int main()
cout << "The total cost of the paint job: " << {
calcPaintJobCost << endl; int i,j;
for(i=1;i<=5;i++)
system("pause"); {
system("cls"); for(j=1;j<=i;j++)
} cout<<'*';
cout<<endl;
}
system(“PAUSE”);
ITERATIONS return 0;
}
Write C++ program to print following pattern:
#include<iostream.h>
#include<iostream.h>
using namespace std;
using namespace std;
int main()
int main()
{
{
int i,j,k;
int i,j;
for(i=1;i<=5;i++)
for(i=1;i<=4;i++)
{
{
for(j=5;j>i;j--)
for(j=1;j<=10;j++)
cout<<' ';
cout<<'*';
for(k=1;k<=i;k++)
cout<<endl;
cout<<'*';
}

33
cout<<endl; {
} for(j=5;j>i;j--)
system(“PAUSE”); cout<<' ';
return 0; for(k=1;k<2*i;k++)
} cout<<i;
cout<<endl;
}
system(“PAUSE”);
#include<iostream.h> return 0;
using namespace std; }
int main() #include<iostream.h>
{ using namespace std;
int i,j,k;
for(i=1;i<=5;i++) int main()
{ {
for(j=5;j>i;j--) int i,j,k,l;
cout<<' '; for(i=1;i<=5;i++)
for(k=1;k<2*i;k++) {
cout<<'*'; for(j=5;j>i;j--)
cout<<endl; cout<<' ';
} for(k=i;k>=1;k--)
system(“PAUSE”); cout<<k;
return 0; for(l=2;l<=i;l++)
} cout<<l;
cout<<endl;
#include<iostream.h> }
using namespace std; system(“PAUSE”);
int main() return 0;
{ }
int i,j,k;
for(i=1;i<=5;i++)

34
i) ********** ii) * iii) * using namespace std;
********** ** ** using namespace std;
********** *** *** int main()
********** **** **** {
int counter, n, fact = 1;
***** *****
cout<<"Enter the Number to calculate factorial :";
iv) * v) 1 vi) 1
cin>>n;
*** 222 212 for (int counter = 1; counter <= n; counter++)
***** 33333 32123 {
******* 4444444 4321234 fact = fact * counter;
********* 555555555 543212345 }
cout<<n<<" Factorial Value Is "<<fact;
system("PAUSE");
return 0;
Program to add first n numbers }
#include<iostream> #include<iostream.h>
using namespace std; using namespace std;
int main()
int main() {
int i,j,k;
{ for(i=1;i<=5;i++)
{
int add=0; for(j=5;j>i;j--)
int i; cout<<' ';
for(k=1;k<=i;k++)
for (i=1; i<=10; i++)
cout<<'*';
{ cout<<endl;
add = add + i; }
} system ("PAUSE");
cout<<"the sum of n?"<<add; return 0;
system("PAUSE"); }
return 0;
}
#include<iostream>

35
In C, "sequence statements" are imperatives. The "selection" is the
"if then else" statement, and the iteration is satisfied by a number while ( x < 10 ) { // While x is less than 10
of statements, such as the "while," " do," and the "for," while the cout<< x <<endl;
case-type statement is satisfied by the "switch" statement. x++; // Update x so the condition can be met eventually
}
Program to calculate Sum of even numbers cin.get();
}
#include<iostream>
using namespace std; #include<iostream>
int main() using namespace std;
{ int main()
int sum = 0; {
for ( int number = 2; number <= 100; number += 2 ) int num=1;
sum += number; while (num<=13)
cout << "Sum is " << sum << endl; {
system("PAUSE"); cout<<num<<endl;
return 0; num =num+2;
} }
<=5) system("PAUSE");
{ return 0;
//int count=1; }
cout<<count<<"\n";
count++;
} #include<iostream>
system("PAUSE"); using namespace std;
return 0; int main()
} {
int num=5;
#include <iostream> do
{
using namespace std; // So we can see cout and endl if(num%2==0)
num=num/2;
int main() else
{ num=(num*3)+1;
int x = 0; // Don't forget to declare variables

36
cout<<num; cin>>n;
cout<<endl; sum+=n;
} cout<<"You entered "<<n<<"\n";
while(num!=1); cout<<"Total of enterd numbers"<<sum<<endl;
system("PAUSE"); }
return 0; while(n>0);
} system("PAUSE");
#include<iostream> return 0;
using namespace std; }
int main()
{
int i,j;

for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
cout<<i;
cout<<endl;
}
system("PAUSE");
return 0;

#include<iostream>
#include<iostream>
using namespace std;
using namespace std;
int main()
int main()
{
{
int n, sum=0;
int positive =0,num;
do
cout<<"enter positive value"<<endl;
{
cin>>num;
cout<<"enter value(zero to end)"<<endl;
while(num>0)

37
{

positive=positive+num; include <iostream>


using namespace std;
cout<<"enter positive value enter 0 to terminate"<<endl;
cin>>num;
int main ()
} {
cout<<"Total of enterd numbers"<<positive<<endl; // an array with 5 rows and 2 columns.
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
system("PAUSE");
return 0; // output each array element's value
} for ( int i = 0; i < 5; i++ )
for ( int j = 0; j < 2; j++ )
{
ARRAY EXAMPLES cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
#include <iostream> }
using namespace std;
return 0;
int foo [] = {5, 10, 15, 20, 30}; }
int n, result=0;
//Program to accept array values and display elements greater
int main () than a chosen number
{ #include<iostream>
for ( n=0 ; n<5 ; ++n ) using namespace std;
{ int main()
result += foo[n]; {
} int a[10];
cout << result; cout<<"Enter Array Elements"<<endl;
system("PAUSE"); for(int i=0;i<=10;i++)
return 0; cin>>a[i];
}

38
for(int i=0;i<10;i++)
if(a[i]>10)
cout<<"Array Element Greater than TEN\
t"<<a[i]<<endl;
return 0;
}

//Program to accept array values and display elements greater C++ Program to store temperature of two different cities for
than a chosen number a week and display it.
#include<iostream> #include <iostream>
using namespace std; using namespace std;
int main() const int CITY = 2;
{ const int WEEK = 7;
int a[10], limit;
cout<<"Enter limit to check"<<endl; int main() {
cin>>limit; int temperature[CITY][WEEK];
cout<<"Enter Array Elements"<<endl; cout<<"Enter all temperature for a week of first city and
for(int i=0;i<=10;i++) then second city. \n";
cin>>a[i]; for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
for(int i=0;i<10;i++) cout<<"City "<<i+1<<", Day "<<j+1<<" : ";
if(a[i]>limit) cin>>temperature[i][j];
cout<<"Array Element Greater than limit\ }
t"<<a[i]<<endl; }
return 0; cout<<"\n\nDisplaying Values:\n";
} for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
cout<<"City "<<i+1<<", Day "<<j+1<<" = "<<
temperature[i][j]<<endl;
}

39
}
return 0; return 0;
} }

#include <iostream>
using namespace std;

int main() {
#include <iostream> int a[1000]; // Declare an array of 1000 ints
using namespace std; int n = 0; // Number of values in a.

int main() { while (cin >> a[n]) {


int test[2][3][2]; // this array can store 12 elements n++;
cout<<"Enter 12 values: \n"; }
for(int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) { int sum = 0; // Start the total sum at 0.
for(int k = 0; k < 2; ++k ) { for (int i=0; i<n; i++) {
cin>>test[i][j][k]; sum = sum + a[i]; // Add the next element to the total
} }
}
} cout << sum << endl;
cout<<"\nDisplaying Value stored:"<<endl;
/* Displaying the values with proper index. */ return 0;
for(int i = 0; i < 2; ++i) { }
for (int j = 0; j < 3; ++j) { #include<iostream>
for(int k = 0; k < 2; ++k ) { using namespace std;
cout<< "test["<<i<<"]["<<j<<"]["<<k<<"] = "<< test[i]
[j][k]<<endl; main()
} {
} int MyArray1[20], MyArray2[20],n;
}

40
cout << "Enter the number of elements in the array "; b++;
cin >> n; }

cout << "Enter elements of first array " << endl; cout<<"the number of integers greater or equal to 10 is:
"<<b;
for ( int i = 0 ; i < n ; i++ ) getch();
cin >> MyArray1 [i]; }

cout << "Enter elements of second array " << endl; //C++ Program to store 5 numbers entered by user in an array
and display first and last number only.
for ( i = 0 ; i < n ; i++ ) #include <iostream>
cin >> MyArray2[i]; using namespace std;

cout << "Sum of elements of two arrays " << endl; int main()
{
for ( i = 0 ; i < n ; i++ ) int n[5];
cout << MyArray1 [i] + MyArray2 [i] << endl; cout<<"Enter 5 numbers: ";
/* Storing 5 number entered by user in an array using for
return 0; loop. */
} for (int i = 0; i < 5; ++i)
{
cin>>n[i];
#include <iostream> }
#include<conio.h>
void main() cout<<"First number: "<<n[0]<<endl; // first element of an
{ array is n[0]
int a[10],i,b=0; cout<<"Last number: "<<n[4]; // last element of an array
cout<<"enter the array\n"; is n[SIZE_OF_ARRAY - 1]
for(i=0;i<N;i++) return 0;
{ }
cin>>a[i];
if (a[i]>=10)

41
C++ Program to display all elements of an initialised two void display(int marks[5]);
dimensional array.
int main() {
#include <iostream> int marks[5] = {88, 76, 90, 61, 69};
using namespace std; display(marks);
return 0;
int main() { }
int test[3][2] = {
{2, -5}, void display(int m[5]) {
{4, 0}, cout<<"Displaying marks: "<<endl;
{9, 1} for (int i = 0; i <5; ++i) {
}; cout<<"Student "<<i+1<<": "<<m[i]<<endl;
for(int i = 0; i < 3; ++i) { }
for(int j = 0; j < 2; ++j) { }
cout<< "test["<< i << "][" << ;j << "] = " << test[i]
[j]<<endl; C++ Program to display the elements of two dimensional
} array by passing it to a function.
} #include <iostream>
system(“PAUSE”); using namespace std;
return 0; void display(int n[3][2]);
}
int main() {
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}
C++ Program to display marks of 5 students by passing one- };
dimensional array to a function. display(num);
return 0;
#include <iostream> }
using namespace std; void display(int n[3][2]) {

42
using namespace std;
cout<<"Displaying Values: "<<endl;
for(int i = 0; i < 3; ++ i) { int main()
for(int j = 0; j < 2; ++j) { {
cout<<n[i][j]<<" "; // 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) {
pass the arrays address to a function. if (numbers[i] < minimum)
#include<iostream> minimum = numbers[i];
using namespace std; }

void printfunc(int my_arg[], int i) // Announce the result


{ cout << "The lowest member value of the array is "
for (int n=0; n < i; n++) << minimum << "." << endl;
cout << my_arg[n] << '\n';
} return 0;
}
int main()
{
int my_array[] = {1, 2, 3, 4, 5};
printfunc(my_array,5); // Example of finding the maximum member of an array
system("PAUSE"); #include <iostream>
return 0; using namespace std;
}
int main()
{
// Example of finding the minimum member of an array // The members of the array
#include <iostream>

43
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; cout << "Enter elements of second array " << endl;
int maximum = numbers[0];
int a = 8; for ( c = 0 ; c < n ; c++ )
cin >> second[c];
// Compare the members
for (int i = 1; i < a; ++i) { cout << "Sum of elements of two arrays " << endl;
if (numbers[i] > maximum)
maximum = numbers[i]; for ( c = 0 ; c < n ; c++ )
} cout << first[c] + second[c] << endl;

// Announce the result return 0;


cout << "The highest member value of the array is " }
<< maximum << "." << endl;

return 0; C++ program to add two matrices.


}
#include<iostream> #include<iostream>
using namespace std;
using namespace std;
main()
{ main()
int first[20], second[20], c, n; {
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
cout << "Enter the number of elements in the array ";
cin >> n; cout << "Enter the number of rows and columns of matrix ";
cin >> m >> n;
cout << "Enter elements of first array " << endl; cout << "Enter the elements of first matrix\n";

for ( c = 0 ; c < n ; c++ ) for ( c = 0 ; c < m ; c++ )


cin >> first[c]; for ( d = 0 ; d < n ; d++ )
cin >> first[c][d];

44
cout << "Enter the elements of second matrix\n";

for ( c = 0 ; c < m ;c++ ) //array of structures


for ( d = 0 ; d < n ; d++ ) #include <iostream>
cin >> second[c][d]; #define Length 3
using namespace std;
for ( c = 0 ; c < m ; c++ ) struct Employee
for ( d = 0 ; d < n ; d++ ) {
sum[c][d] = first[c][d] + second[c][d]; char jobtitle [50];
int yearEmployed;
cout << "Sum of entered matrices:-\n"; } employee [Length];
void printemployee (Employee employee);
for ( c = 0 ; c < m ; c++ ) int main ()
{ {
for ( d = 0 ; d < n ; d++ ) char buffer [50];
cout << sum[c][d] << "\t"; for (int n=0; n<Length; n++)
{
cout << endl; cout << "Enter jobtitle: ";
} cin.getline (employee[n].jobtitle,50);
cout << "Enter yearEmployed: ";
return 0; cin.getline (buffer,50);
} employee[n].yearEmployed = atoi (buffer);
}
cout << "\nYou have entered these employees:\n";
for (int n=0; n<Length; n++)
printemployee (employee[n]);
system ("PAUSE");
return 0;
}

45
for(int i=0;i<n;i++)
{
cout<<"\n Enter the Bio-Data of the student no "<<i+1<<"
Syntax is :\n";
cout<<"\t Enter the Name = ";
struct inventory { cin>>(genius[i].name);
int part_no; cout<<"\t Enter the student number = ";
float cost; cin>>genius[i].studentNUM;
float price; cout<<"\t Enter the Section = ";
}; cin>>genius[i].section;
cout<<"\t Enter the term = ";
cin>>genius[i].term;
cout<<"\t Enter the Age = ";
struct inventory table[4]; cin>>genius[i].age;
}
//array of structure example for(int j=0;j<n;j++)
#include<iostream> {
using namespace std; cout<<"\n The Bio-Data of the student no "<<j+1<<" is :\
n";
struct student cout<<"\t Name = "<<genius[j].name<<endl;
{ cout<<"\t Roll No = "<<genius[j].studentNUM<<endl;
char name[25]; cout<<"\t Section = "<<genius[j].section<<endl;
char section[10]; cout<<"\t Semester = "<<genius[j].term<<endl;
int studentNUM; cout<<"\t Age = "<<genius[j].age<<endl;
int term; }
int age;
}; system("PAUSE");
return 0;
main( ) }
{
const int n=2; //array of structures
student genius[n];
46
#include <iostream> int main(){
#define Length 3 int arr[5]={1,3,5,7,9}; //initialize arr array
using namespace std; int i;
struct Employee for(i=0;i<5;i++) //output arr array
{ cout<<arr[i]*arr[i]<<"\t";
char jobtitle [50]; getch();
int yearEmployed; return 0;
} employee [Length]; }
void printemployee (Employee employee);
int main ()
{ #include<iostream>
char buffer [50]; #include<conio.h>
for (int n=0; n<Length; n++) using namespace std;
{ int main(){
cout << "Enter jobtitle: "; int arr[5]={1,3,5,7,9}; //initialize arr array
cin.getline (employee[n].jobtitle,50); int i;
cout << "Enter yearEmployed: "; for(i=4;i>=0;i--) //output arr array
cin.getline (buffer,50); cout<<arr[i]<<"\t";
employee[n].yearEmployed = atoi (buffer); getch();
} return 0;
cout << "\nYou have entered these employees:\n"; }
for (int n=0; n<Length; n++)
printemployee (employee[n]); 3.What would be printed from the following C++ program?
system ("PAUSE"); #include<iostream>
return 0; #include<conio.h>
} using namespace std;

would be printed from the following C++ program? int main(){


#include<iostream> int list1[5]={1,3,5,7,9}; //initialize list1 array
#include<conio.h> int list2[5];
using namespace std; int i;

47
for(i=0;i<5;i++) {
list2[i]=list1[i]+1; //assign values to list2 float array1[p];
for(i=0;i<5;i++) //output list2 int i,limit = 0, m =0;
cout<<list2[i]<<"\t"; cout << "Enter array limit : \n";
getch(); cin >> limit;
return 0; for (i=0; i <= p; i++)
} { //++m;
cout << "Enter elements of an array: " << i+1 << "\n";
4. What would be printed from the following C++ program? cin >> array1[i];
#include<iostream> m++;
#include<conio.h> if (i == (limit-1))
using namespace std; break;
int main(){
int list[10]={1,2,3,4,5,6,7,8,9,10}; //initialize list array //cout << m;
int i; }
for(i=0;i<5;i++) cout << "Total Elements entered are : " << m << endl;
{ //switching elements return(0);
int temp=list[i]; }
list[i]=list[9-i]; int main(int argc, char *argv[])
list[9-i]=temp; {
}
for(i=0;i<10;i++) //output list //float array2[20];
cout<<list[i]<<"\t"; int n = 10;
getch(); cout << sum(n) << endl;
return 0; system("PAUSE");
#include <cstdlib> return 0;
#include <iostream> //return EXIT_SUCCESS;
#include <string>
}
using namespace std; #include <iostream>
int sum (int p) using namespace std;

48
void printarray (int arg[], int length) {
for (int n=0; n<length; n++) #include <iostream>
cout << arg[n] << " ";
cout << "\n"; using namespace std;
} //program to find largest value in an array
int main () #define size 100
{ int main()
int MyarrayX[ ] = {5, 10, 15}; {
int MyarrayY[ ] = {2, 4, 6, 8, 10}; int a[size];
printarray (MyarrayX,3); int i, n, large;
printarray (MyarrayY,4); cout << "Enter array size ";
system("PAUSE"); cin>>n;
return 0; cout << "Enter the elements \n";
for (i=0; i<=n-1; ++i)
} {
cin>>a[i];
#include<iostream.h> }
//#include<conio.h> cout << "Contents of the array \n";
int main() for (i=0; i<=n-1; ++i)
{ {
int i,j; cout<<a[i]<<'\t';
for(i=1;i<=5;i++) }
{ cout<<endl;
for(j=1;j<=i;j++) large = a[0];
cout<<'*'; for (i=0; i<=n-1; ++i)
cout<<endl; {
} if (large < a[i])
// getch(); (large = a[i]);
system("PAUSE"); }
return 0; cout << "Largest element ="<<large;
} system("PAUSE");

49
return 0; return 0;
}
C++ Program to display all elements of an initialised two
} dimensional array.
Write a C++ program to reverse the element of an integer 1-
D array. #include <iostream>
using namespace std;
#include<iostream.h>
using namespace std; int main() {
int main() int test[3][2] = {
{ {2, -5},
int Arr[100],n,temp,i,j; {4, 0},
cout<<"Enter number of elements you want to insert "; {9, 1}
cin>>n; };
for(int i = 0; i < 3; ++i) {
for(i=0;i<n;i++) for(int j = 0; j < 2; ++j) {
{ cout<< "test["<< i << "][" << ;j << "] = " << test[i]
cout<<"Enter element "<<i+1<<":"; [j]<<endl;
cin>>Arr[i]; }
} }
for(i=0,j=n-1;i<n/2;i++,j--) system(“PAUSE”);
{ return 0;
temp=Arr[i]; }
Arr[i]=Arr[j];
Arr[j]=temp;
}
cout<<"\nReverse array"<<endl;

for(i=0;i<n;i++)
cout<<Arr[i]<<" "; C++ Program to display marks of 5 students by passing one-
dimensional array to a function.
getch();

50
#include <iostream> }
using namespace std; void display(int n[3][2]) {
void display(int marks[5]);
cout<<"Displaying Values: "<<endl;
int main() { for(int i = 0; i < 3; ++ i) {
int marks[5] = {88, 76, 90, 61, 69}; for(int j = 0; j < 2; ++j) {
display(marks); cout<<n[i][j]<<" ";
return 0; }
} }
}
void display(int m[5]) {
cout<<"Displaying marks: "<<endl;
for (int i = 0; i <5; ++i) {
cout<<"Student "<<i+1<<": "<<m[i]<<endl; pass the arrays address to a function.
} #include<iostream>
} using namespace std;

C++ Program to display the elements of two dimensional void printfunc(int my_arg[], int i)
array by passing it to a function. {
#include <iostream> for (int n=0; n < i; n++)
using namespace std; cout << my_arg[n] << '\n';
void display(int n[3][2]); }

int main() { int main()


int num[3][2] = { {
{3, 4}, int my_array[] = {1, 2, 3, 4, 5};
{9, 5}, printfunc(my_array,5);
{7, 1} system("PAUSE");
return 0;
}; }
display(num);
return 0;

51
// Example of finding the minimum member of an array {
#include <iostream> // The members of the array
using namespace std; int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int maximum = numbers[0];
int main() int a = 8;
{
// The members of the array // Compare the members
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; for (int i = 1; i < a; ++i) {
int minimum = numbers[0]; if (numbers[i] > maximum)
int a = 8; maximum = numbers[i];
}
// Compare the members
for (int i = 1; i < a; ++i) { // Announce the result
if (numbers[i] < minimum) cout << "The highest member value of the array is "
minimum = numbers[i]; << maximum << "." << endl;
}
return 0;
// Announce the result }
cout << "The lowest member value of the array is " #include<iostream>
<< minimum << "." << endl; using namespace std;

return 0; main()
} {
int first[20], second[20], c, n;

cout << "Enter the number of elements in the array ";


// Example of finding the maximum member of an array cin >> n;
#include <iostream>
using namespace std; cout << "Enter elements of first array " << endl;

int main() for ( c = 0 ; c < n ; c++ )

52
cin >> first[c]; for ( d = 0 ; d < n ; d++ )
cin >> first[c][d];
cout << "Enter elements of second array " << endl;
cout << "Enter the elements of second matrix\n";
for ( c = 0 ; c < n ; c++ )
cin >> second[c]; for ( c = 0 ; c < m ;c++ )
for ( d = 0 ; d < n ; d++ )
cout << "Sum of elements of two arrays " << endl; cin >> second[c][d];

for ( c = 0 ; c < n ; c++ ) for ( c = 0 ; c < m ; c++ )


cout << first[c] + second[c] << endl; for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d];
return 0;
} cout << "Sum of entered matrices:-\n";

for ( c = 0 ; c < m ; c++ )


C++ program to add two matrices. {
for ( d = 0 ; d < n ; d++ )
#include<iostream> cout << sum[c][d] << "\t";

using namespace std; cout << endl;


}
main()
{ return 0;
int m, n, c, d, first[10][10], second[10][10], sum[10][10]; }

cout << "Enter the number of rows and columns of matrix ";
cin >> m >> n;
cout << "Enter the elements of first matrix\n";

for ( c = 0 ; c < m ; c++ )

53
/ a simple sorting program that sort a list of n integer {
numbers, entered by the user (ascending) // These three lines swap the elements
#include <iostream> // list[i] and list[j].
using namespace std; temp = list[i];
list[i] = list[j];
#define maxsize 100 list[j] = temp;
}
int main(void) cout<<"\nSorted list, ascending: ";
{ for(i=0; i<n; i++)
int temp, i, j, n, list[maxsize]; cout<<" "<<list[i];
cout<<endl;
cout<<"\n--You are prompted to enter your list size.--"; return 0;
cout<<"\n--Then, for your list size, you are prompted to }
enter--";
cout<<"\n--the element (integers) of your list.--"; // a program will sort a list of a strings entered by the user
cout<<"\n--Finally your list will be sorted ascending!!!--\n"; #include <iostream>
// enter the list's size #include <cstdlib>
cout<<"\nEnter your list size: "; #include <cstring>
// read the list's size using namespace std;
cin>>n;
// prompting the data from user store in the list int main(void)
for(i=0; i<n; i++) {
{ // declare two arrays named tname with 1-Dimension and
cout<<"Enter list's element #"<<i<<"-->"; name with 2-Dimension
cin>>list[i]; char tname[20], name[20][20];
} // normal variables
int i, j, n;
// do the sorting...
for(i=0; i<n-1; i++) cout<<"Enter the number of names: ";
for(j=i+1; j<n; j++) cin>>n;
if(list[i] > list[j]) // outer loop for counter...

54
for(i=0; i<n; i++)
{ int main(void)
cout<<"\nEnter the name(one word) "<<(i+1)<<cin>>name[i]; {
} int i, j, k;
// inner for loop, read row by row set outer for loop...
for(i=0; i<n-1; i++) // first matrix
// innermost for loop, read column by column of the int x[m][c] = {{1,2},{3,4},{5,6}};
characters... // second matrix
for(j = i+1; j<n>0) int y[c][n] = {{7,8,9,10},{11,12,13,14}};
{ // for storing the matrix product result
// strcpy()/strcpy_s() - copy the strings... int z[m][n];
// compare and swap...
strcpy_s(tname, 20, name[i]); for(i=0; i<m; i++)
strcpy_s(name[i], 20, name[j]); for(j=0; j<n; j++)
strcpy_s(name[j], 20, tname); {
} z[i][j] = 0;
cout<<"\nSorted names:\n"; for(k=0; k<c; k++)
for (i =0; i<n; i++) // same as z[i][j] = z[i][j] + x[i][k] * y[k][j];
cout<<"\n"<<name[i]; z[i][j] += x[i][k] * y[k][j];
cout<<endl; }
return 0; cout<<"\nMultiply matrix x and matrix y,";
} cout<<"\nThen store the result in matrix z.";
cout<<"\nMatrix x is 3x2, and matrix y is 2x4,";
/ C++ multiplication of the matrix x and matrix y and stores the cout<<"\nso, the result, z should be matrix 3x4\n";
result in matrix z cout<<"\nThe matrix product is: \n";
#include <iostream> for (i=0; i<m; i++)
using namespace std; {
cout<<"\n";
#define m 3 for(j=0; j<n; j++)
#define c 2 // display the result...
#define n 4 cout<<" "<<z[i][j];

55
} total=total + q[i][j];
cout<<endl; }
// calculate the average, simple typecast from int to float
return 0; average = (float)total/(float) (m*n);
} cout<<"\nThis program will calculate the average of the";
cout<<"\n4 x 5 array, which means the sum of the";
cout<<"\narray's element, divide the number of the";
// using two-dimensional array to compute the average of all cout<<"\narray's element....";
the elements in array named x cout<<"\nProcessing.... PLEASE WAIT\n";
#include <iostream>
using namespace std; // display the average
cout<<"Average = "<<total<<"/"<<m*n<<endl;
#define m 4 cout<<"\nThe Average = "<<average<<endl;
#define n 5
return 0;
int main(void) }
{
int i, j, total = 0; // a program to find the smallest number in an array named
balance, a simple search function
// 4x5 or [4][5] array variable with initial values #include <iostream>
int q[m][n]={{4,5,6,2,12},{10,25,33,22,11},{21,32,43,54,65}, using namespace std;
{3,2,1,5,6}};
float average; #define n 10
// outer for loop, read row by row...
for(i=0; i<m; i++) int main(void)
// inner for loop, for every row, read column by column {
for(j=0; j<n; j++) int i;
// get the summation of the array elements. float small, balance[n]={100.00,40.00,-30.00,400.00,60.00,-
{ 25.00,-24.00,0.00, 3.24,0.50};
// display the array... small = balance[0];
cout<<"q["<<i<<"]["<<j<<"] = "<<q[i][j]<<endl;

56
// loop for displaying the array content total = total + y[i];
for(i=0; i<n; i++) }
cout<<balance[i]<<" ";
// another loop do the array element comparing, verify until // display the result...
condition i=n cout<<"\nSum of 7 numbers in an array is = "<<total<<endl;
for(i=1; i<n> balance[i])
small = balance[i]; return 0;
} }
cout<<"\nSearching..."<<endl;
// display the result...
cout<<"The smallest value in the given array is =
"<<small<<endl;
return 0; #include <iostream>
} using namespace std;

#include <iostream> // function prototypes


using namespace std; float minimum(float, float);
// (*ptr) is a pointer to function of type float
// replace every n occurrences with 7 float (*ptr)(float, float);
#define n 7
void main(void)
int main(void) {
{ float x1, x2, small;
int i, total = 0, y[n] = {6,9,2,4,5,23,12};
// assigning address of minimum() function to ptr
for (i=0; i<n; i++) ptr = minimum;
{ // prompt user for input
// display the array contents cout<<"\nEnter two numbers, separated by a space: ";
cout<<y[i]<<" "; // read and store
cin>>x1>>x2;
// do the summing up // call the function pointed by ptr small has the return value

57
small = (*ptr)(x1, x2); cin>>n[i];
cout<<"\nsmaller number is "<<small<<endl; }
}
cout<<"First number: "<<n[0]<<'\n';
// find the smaller integer cout<<"middle number: "<<n[m]<<'\n';
float minimum(float y1, float y2) cout<<"Last number: "<<n[l];
{ system("PAUSE"); // last element of an array is
if (y1 < y2) n[SIZE_OF_ARRAY - 1]
return y1; return 0;
else }
return y2;
}

#include <iostream>
# define listsize 100
using namespace std; #include<iostream>
using namespace std;
int main() int main()
{
{
int n[listsize],y,m,l;
int studentAge[]={15,18,20,30,17,23,26,29,35,38};
cout<<"enter array size"<<' ';
cin>>y; int range1=0, range2=0,range3=0;
m=y/2; for (int a=0;a<10;a++)
l=y-1; {
cout<<'\n'; if(studentAge[a]<=17)
//cout<<"Enter 8 numbers:\n " ; range1+=1;
/* Storing 5 number entered by user in an array using for
else if(studentAge[a]>20)
loop. */
for (int i = 0; i <y; i++) range2+=1;
{ else (studentAge[a]<22 , studentAge[a]<38);
cout<<'\a'; range3+=1;

58
} cout<<"\n--you are requested to enter size of array"<<endl;
cout<<"number of student less than cout<<"--you are requested to enter array
17"<<endl<<range1<<endl; elements"<<endl;;
cout<<"--your array will be sorted in ascending
cout<<"number of student at least 20"<<endl<<range2<<endl;
order"<<endl;
cout<<"number of student whos age between 22and
cout<<"\n Now enter array size"<<endl;
38"<<endl<<range3<<endl; cin>>n;
system("PAUSE"); for(i=0;i<n;i++)
return 0; {
} cout<<"enter list of elements in array"<<endl;
#include<algorithm> cin>>list[i];
}
#include<iostream>
for(i=0;i<n;i++)
int main() for(j=i+1;j<n;j++)
{ if (list[i]>list [j])
int array[]={23,9,15,64,87,10,19,22,-12,0}; {
int elements=sizeof(array)/sizeof(array[0]); temp=list[i];
std::sort(array,array+elements); list[i]=list [j];
for(int i=0;i<elements;i++) list[j]=temp;
}
std::cout<<array[i]<<' ';
cout<<"\n sorted array"<<endl;
system("PAUSE"); for(i=0;i<n;i++)
return 0; cout<<'\t'<<list[i];
} cout<<endl;
system ("PAUSE");
#include <iostream> return 0;
using namespace std; }
#define maxsize 100
int main()
{ EXERCISE 2
int temp,i,j,n,list[maxsize];

59
Write a program that asks the user to type 10 integers of an int arr[10], n,greaterIntergers = 0;
array. The program must compute and write how many
integers are greater than or equal to 10. for (n = 0; n < 10; n++) {
#include <iostream> cout << "Input an Interger ";
cin >> arr[n];
using namespace std;
if (arr[n] >= 10) {
const int SIZE=10; greaterIntergers++;
}
int main() }
{
int MyArray[10],i,count=0; cout << greaterIntergers << " intergers are greater than
or equals to 10" << endl;
for(i=0;i<SIZE;i++) system("PAUSE");
{ return 0;
cout << "Type an integer: "; }
cin >> MyArray[i];
count=count+(MyArray[i]>=10); // note that true converts
to 1, false to 0
} #include <iostream>
using namespace std;
cout << "the number of integers greater or equal to 10 is: " int main()
<< count <<endl; {
system("PAUSE"); const int limit = 10;
return 0; int list[10], count=0;
} cout<<"Enter 10 integers :"<<endl;
for(int i=0; i<limit; i++)
#include <iostream> {
using namespace std; cout<<"Enter Number "<<i+1<<" :";
int main()
{ cin>>list[i];

60
cin >> V;
(list[i]<10) ? : count++;
} for (i = 0; i < N; i++)
cout<<"Number of interger(s) greater than 10 = "<<count; {
system("PAUSE"); if (t[i] == V)
return 0; {
} cout << "V is in the array" << endl;
system("PAUSE");
EXERCISE 2 return 0;
Write a program that asks the user to type 10 integers of an }
array and an integer V. The program must search if V is in the }
array of 10 integers. The program writes "V is in the array" or
"V is not in the array". cout << "V is not in the array" << endl;
#include <iostream> system("PAUSE");
return 0;
using namespace std; }

const int N = 10; EXERCISE 3


Write a program that asks the user to type 10 integers of an
int main () array. The program must output the largest element in the
{ array, and the index at which that element was found.
int t[N], i=0, V;

#include <iostream>
for (i = 0; i < N; i++) using namespace std;
{
cout << "Type an integer: "; const int N=10;
cin >> t[i]; int main()
} {
int t[N],i,index;
cout << "Type the value of V: ";

61
for(i=0;i<N;i++) }
{ cout << index;
cout << "Type an integer"; return 0;
cin >> t[i]; }
}
index=0; #include <iostream>
for(i=1;i<N;i++) using namespace std;
if(t[index]<t[i]) int main()
index=i; {
int index = 0, nb = 0;
cout << "The greatest element of the array is: " int arr [10];
<< t[index] << " (index " << index << ")" << endl; for ( int i = 0; i < 10; i++)
return 0; {
} cout << "Type an integer ";
#include <iostream> cin >> arr[i];
using namespace std; if (arr[i] > nb)
{
int main() nb = arr[i];
{ index = i;
int index = 0, nb = 0; }
int arr [10]; }
cout <<"Large number is at index\t"<<index<<endl;
for ( int i = 0; i < 10; i++) cout<<"The largest number is\t"<<arr[index];
{ system("PAUSE");
cout << "Type an integer "; return 0;
cin >> arr[i]; }
if (arr[i] > nb)
{ #include <iostream>
nb = arr[i];
index = i; using namespace std;
} const int SZ = 10;

62
adding a zero at the end of the array. The program must then
int main() write the final array.
{
int arr[SZ]; #include <iostream>
int Largest = 0, index; using namespace std;
cout << "Please enter " << SZ << " integers:" << endl;
for (int i = 0; i < SZ; i++) const int N=10;
{
cin >> arr[i]; int main()
} {
int t[N],i,j,V;
for (int i = 0; i < SZ; i++) bool found;
{ for(i=0;i<N;i++)
if (arr[i] >= Largest) {
{ cout << "Type an integer: ";
Largest = arr[i]; cin >> t[i];
index = i; }
} cout << "Type the value of V: ";
} cin >> V;
cout << "Largest number = " << Largest << ", at index: " <<
index << endl; for (i=0;i<N;i++)
system("PAUSE"); if (t[i]==V)
return 0; {
} for (j=i;j<N-1;j++)
EXERCISE 4 t[j]=t[j+1];
t[N-1]=0;
Write a program that asks the user to type 10 integers of an break;
array and an integer value V. The program must search if the }
value V exists in the array and must remove the first
occurrence of V, shifting each following element left and for(i=0;i<N;i++)
cout << t[i] << endl;

63
for (int j = i; j < SZ-1; j++)
return 0; arr[j] = arr[j+1];
} arr[SZ-1] = 0;
}
}
for (auto i : arr)
cout << i << endl;

return 0;
}
#include <iostream>

using namespace std;


const int SZ = 10;

int main()
{
int arr[SZ];
int V; EXERCISE 5
cout << "Please enter 10 integers: " << endl;
for (int i = 0; i < SZ; i++) Write a program that asks the user to type 10 integers of an
{ array and an integer value V and an index value i between 0
cin >> arr[i]; and 9. The program must put the value V at the place i in the
} array, shifting each element right and dropping off the last
cout << "Enter V: "; element. The program must then write the final array.
cin >> V; #include <iostream>

for (int i = 0; i < SZ; i++) using namespace std;


{ const int SZ = 10;
if (V == arr[i])
{ int main()
{

64
int arr[SZ]; EXERCISE 6
int V, i;
cout << "Please enter 10 integers: " << endl; Write a program that asks the user to type 10 integers of an
for (int x = 0; x < SZ; x++) array. The program will then display either "the array is
{ growing", "the array is decreasing", "the array is constant", or
cin >> arr[x]; "the array is growing and decreasing."
} #include <iostream>
cout << "Enter value to insert in array: "; using namespace std;
cin >> V;
cout << "Enter Index (0-9) to place the value: "; const int N=10;
cin >> i;
while (i < 0 || i > 9) int main()
{ {
cout << "Index must be within range 0-9: "; int a[N],i;
cin >> i; bool found=false;
} bool up=false,down=false;
int z = SZ-1;
while (z != i) cout << "Please enter an integer: ";
{ cin >> a[0];
arr[z] = arr[z-1]; for(i=1;i<N;i++)
z--; {
} cout << "Please enter an integer: ";
arr[i] = V; cin >> a[i];
if(a[i-1]>a[i]) down=true;
for (auto y : arr) if(a[i-1]<a[i]) up=true;
cout << y << endl; }

return 0; cout << "the table is " << (up?


} (down?
"increasing and decreasing":
"increasing"):

65
(down? for (i=0;i<N-1;i++)
"decreasing": {
"constant")) << endl; imin=i;
return 0; min=a[i];
} for (j=i+1;j<<N;j++)
if (a[j]<min)
{
min=a[j];
imin=j;
}
EXERCISE 7
tmp=a[imin];
Write a program that asks the user to type 10 integers of an a[imin]=a[i];
array. The program will then sort the array in descending a[i]=tmp;
order and display it. }
cout << "The sorted array:" << endl;
for (i=0;i<N;i++)
#include <iostream> cout << "a[" << i << "] = " << a[i] << endl;
using namespace std;
return 0;
const int N=10; }
#include <iostream>
int main() using namespace std;
{
int a[N],i,j,min,imin,tmp; const int N=10;

for (i=0;i<N;i++) int main()


{ {
cout << "Please enter an integer: "; int a[N],i,nb,tmp;
cin >> a[i];
} for(i=0;i<N;i++)

66
{
cout << "Please enter an integer: "; const int N=10;
cin >> a[i];
} int main()
do { {
nb=0; int a[N],b[N],c[2*N],i;
for (i=0;i<N-1;i++)
if (a[i]>a[i+1]) cout << "Enter table a:" << endl;
{ for (i=0;i<N;i++)
tmp=a[i];a[i]=a[i+1];a[i+1]=tmp; {
nb++; cout << "Please enter an integer: ";
} cin >> a[i];
} while(nb!=0); }

cout << "The sorted array:" << endl; cout << "Enter table b:" << endl;
for (i=0;i<N;i++) for (i=0;i<N;i++)
cout << "a[" << i << "] = " << a[i] << endl; {
cout << "Please enter an integer: ";
return 0; cin >> b[i];
} }

for (i=0;i<N;i++) c[i]=a[i];


for (i=0;i<N;i++) c[i+N]=b[i];
EXERCISE 8
cout << "Table c:" << endl;
Write a program which takes 2 arrays of 10 integers each, a for (i=0;i<2*N;i++)
and b. c is an array with 20 integers. The program should put cout << c[i] << " ";
into c the appending of b to a, the first 10 integers of c from cout << endl;
array a, the latter 10 from b. Then the program should display return 0;
c. }
#include <iostream> #include <iostream>
using namespace std;
67
using namespace std; }

#define LENGTH 10
//C++ Program to store 5 numbers entered by user in an array
and display first and last number only.
int main()
#include <iostream>
{
using namespace std;
int a[LENGTH], b[LENGTH], c[LENGTH*2], i;
int main() {
cout << "type numbers into first array:\n";
int n[5];
for (i = 0; i < LENGTH; i++) {
cout<<"Enter 5 numbers: ";
cout << i << " = ";
/* Storing 5 number entered by user in an array using for
cin >> a[i];
loop. */
}
for (int i = 0; i < 5; ++i) {
cin>>n[i];
cout << "type numbers into second array:\n";
}
for (i = 0; i < LENGTH; i++) {
cout << i << " = ";
cout<<"First number: "<<n[0]<<endl; // first element of an
cin >> b[i];
array is n[0]
}
cout<<"Last number: "<<n[4]; // last element of an array
is n[SIZE_OF_ARRAY - 1]
for (i = 0; i < LENGTH * 2; i++) {
return 0;
if (i < LENGTH)
}
c[i] = a[i];
else
c[i] = b[i - LENGTH]; #include<iostream>
} using namespace std;
for (i = 0; i < LENGTH * 2; i++) int main()
cout << c[i] << " "; {
return 0; int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;

68
cout<<"Enter rows and columns of first matrix:"; cout<<"\nSorry!!!! Matrix multiplication can't be done";
cin>>m>>n; system("PAUSE");
cout<<"Enter rows and columns of second matrix:"; return 0;
cin>>p>>q;
}
if(n==p) #include<iostream.h>
{ #include<conio.h>
cout<<"\nEnter first matrix:\n";
for(i=0;i<m;++i) int main()
for(j=0;j<n;++j) {
cin>>a[i][j]; clrscr();
int a[10][10];
cout<<"\nEnter second matrix:\n"; int b[10][10];
for(i=0;i<p;++i) int x,y,i,j;
for(j=0;j<q;++j) cout<<"\nEnter the number of rows and columns :::\n\n";
cin>>b[i][j]; cin>>x>>y;
cout<<"\nThe new matrix is:\n"; cout<<"\n\nEnter elements for Matrix A :::\n\n";
for(i=0;i<x;i++)
for(i=0;i<m;++i) {
{ for(j=0;j<y;j++)
for(j=0;j<q;++j) {
{ cin>>a[i][j];
c[i][j]=0; }
for(k=0;k<n;++k) cout<<"\n";
c[i][j]=c[i][j]+(a[i][k]*b[k][j]); }
cout<<c[i][j]<<" "; cout<<"\n\nEnter elements for Matrix B :::\n\n";
} for(i=0;i<x;i++)
cout<<"\n"; {
} for(j=0;j<y;j++)
} {
else cin>>b[i][j];

69
}
cout<<"\n"; cout << "Enter the number of rows and columns of matrix ";
} cin >> m >> n;
cout<<"\n\nMatrix A :\n\n"; cout << "Enter the elements of first matrix\n";
for(i=0;i<x;i++)
{ for ( c = 0 ; c < m ; c++ )
for(j=0;j<y;j++) for ( d = 0 ; d < n ; d++ )
{ cin >> first[c][d];
cout<<"\t"<<a[i][j];
} cout << "Enter the elements of second matrix\n";
cout<<"\n\n";
} for ( c = 0 ; c < m ;c++ )
for ( d = 0 ; d < n ; d++ )
cout<<"\n\nMatrix B :\n\n"; cin >> second[c][d];

for(i=0;i<x;i++) for ( c = 0 ; c < m ; c++ )


{ for ( d = 0 ; d < n ; d++ )
for(j=0;j<y;j++) sum[c][d] = first[c][d] + second[c][d];
{
cout<<"\t"<<b[i][j]; cout << "Sum of entered matrices:-\n";
}
cout<<"\n\n"; for ( c = 0 ; c < m ; c++ )
} {
for ( d = 0 ; d < n ; d++ )
C++ program to add two matrices. cout << sum[c][d] << "\t";
#include<iostream>
cout << endl;
using namespace std; }

main() return 0;
{ }
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
70
int code;
cout<<"\n\nAddition of Matrix A and Matrix B :\n\n"; } mine, yours;

for(i=0;i<x;i++) void printsubject (student subject);


{
for(j=0;j<y;j++) int main ()
{ {
cout<<"\t"<<a[i][j]+b[i][j]; string mystr;
}
cout<<"\n\n"; mine.name = "Programming";
} mine.code = 300;

getch(); cout << "Enter Subject: ";


return 0; getline (cin,yours.name);
} cout << "Enter code: ";
getline (cin,mystr);
stringstream(mystr) >> yours.code;

cout << "My favorite subject is:\n ";


printsubject (mine);
cout << "And yours is:\n ";
printsubject (yours);
system("PAUSE");
STRUCTURES EXAMPLES return 0;
}
#include <iostream>
#include <string> void printsubject (student subject)
#include <sstream> {
using namespace std; cout << subject.name;
cout << " (" << subject.code << ")\n";
struct student { }
string name;

71
cout << " (" << team.yearFormed << ")\n";
#include <iostream> }
#include<iostream>
#include <string> #include<iostream>
#include <sstream> using namespace std;
using namespace std; int main()
struct teams { {
string name; int i, temp;
int yearFormed; int arr[10];
} mine, yours; cout<<"Enter 10 Numbers"<<endl;
void printteams (teams team); for(i=1;i<=10;i++)
int main () cin>>arr[i];
{ for(i=1;i<=9;i++)
string mystr; {
mine.name = "2001 A Space Odyssey"; if(arr[i]>arr[i+1])
mine.yearFormed = 1968; {
cout << "Enter title: "; temp=arr[i+1];
getline (cin,yours.name); arr[i+1]=arr[i];
cout << "Enter year: "; arr[i]=temp;
getline (cin,mystr); }
stringstream(mystr) >> yours.yearFormed; for(i=1;i<=10;i++)
cout << "My favorite movie is:\n "; cout<<arr[i];
printteams (mine); cout<<"The sorted array above"<<endl;
cout << "And yours is:\n "; system("PAUSE");
printteams (yours); return 0;
system("PAUSE");
return 0; }
} }
//void printteams (teams team); #include <iostream>
{ using namespace std;
cout << teams.name;

72
struct person { struct telephone
char name[50]; {
int age; char *name;
float salary; int number;
}; int age;
};
int main()
{ int main()
{
person p1; struct telephone index;

cout << "Enter Full name: "; index.name = "Jane Monroe";


cin.get(p1.name, 50); index.number = 12345;
cout << "Enter age: "; index.age = 38;
cin >> p1.age; cout << "Name: " << index.name << '\n';
cout << "Enter salary: "; cout << "Telephone number: " <<
cin >> p1.salary; index.number<<'\n';
cout << "Customer age: " << index.age<<'\n';
cout << "\nDisplaying Information." << endl; system("PAUSE");
cout << "Name: " << p1.name << endl; return 0;
cout <<"Age: " << p1.age << endl; }
cout << "Salary: " << p1.salary;
system("PAUSE");
return 0;
}

#include <iostream>
#include<iostream> #include <cstring>
using namespace std;
using namespace std;

73
struct Books cout << "Book 2 author : " << Book2.author <<endl;
{ cout << "Book 2 subject : " << Book2.subject <<endl;
char title[50]; cout << "Book 2 id : " << Book2.book_id <<endl;
char author[50];
char subject[100]; return 0;
int book_id; }
};
//Structure function
int main( ) #include <iostream>
{ #include <cstring>
struct Books Book1; // Declare Book1 of type Book
using namespace std;
struct Books Book2; // Declare Book2 of type Book
void printBook( struct Books book );
// book 1 specification
struct Books
strcpy( Book1.title, "Learn C++ Programming");
{
strcpy( Book1.author, "Chand Miyan");
char title[50];
strcpy( Book1.subject, "C++ Programming");
char author[50];
Book1.book_id = 6495407;
char subject[100];
// book 2 specification int book_id;
strcpy( Book2.title, "Telecom Billing"); };
strcpy( Book2.author, "Yakit Singha");
int main( )
strcpy( Book2.subject, "Telecom");
{
Book2.book_id = 6495700;
struct Books Book1; // Declare Book1 of type Book
// Print Book1 info struct Books Book2; // Declare Book2 of type Book
cout << "Book 1 title : " << Book1.title <<endl;
// book 1 specification
cout << "Book 1 author : " << Book1.author <<endl;
strcpy( Book1.title, "Learn C++ Programming");
cout << "Book 1 subject : " << Book1.subject <<endl;
strcpy( Book1.author, "Chand Miyan");
cout << "Book 1 id : " << Book1.book_id <<endl;
strcpy( Book1.subject, "C++ Programming");
// Print Book2 info Book1.book_id = 6495407;
cout << "Book 2 title : " << Book2.title <<endl;
74
// book 2 specification struct movies_t {
strcpy( Book2.title, "Telecom Billing"); string title;
strcpy( Book2.author, "Yakit Singha"); int year;
strcpy( Book2.subject, "Telecom"); } films [3];
Book2.book_id = 6495700;
void printmovie (movies_t movie);
// Print Book1 info
printBook( Book1 ); int main ()
{
// Print Book2 info string mystr;
printBook( Book2 ); int n;

return 0; for (n=0; n<3; n++)


} {
void printBook( struct Books book ) cout << "Enter title: ";
{ getline (cin,films[n].title);
cout << "Book title : " << book.title <<endl; cout << "Enter year: ";
cout << "Book author : " << book.author <<endl; getline (cin,mystr);
cout << "Book subject : " << book.subject <<endl; stringstream(mystr) >> films[n].year;
cout << "Book id : " << book.book_id <<endl; }
}
cout << "\nYou have entered these movies:\n";
for (n=0; n<3; n++)
printmovie (films[n]);
return 0;
}
// array of structures
#include <iostream> void printmovie (movies_t movie)
#include <string> {
#include <sstream> cout << movie.title;
using namespace std; cout << " (" << movie.year << ")\n";
}

75
main( )
Syntax {
const int n=2;
struct inventory { student genius[n];
int part_no; for(int i=0;i<n;i++)
float cost; {
float price; cout<<"\n Enter the Bio-Data of the student no "<<i+1<<"
}; is :\n";
cout<<"\t Enter the Name = ";
cin>>(genius[i].name);
cout<<"\t Enter the student number = ";
struct inventory table[4]; cin>>genius[i].studentNUM;
cout<<"\t Enter the Section = ";
cin>>genius[i].section;
cout<<"\t Enter the term = ";
cin>>genius[i].term;
cout<<"\t Enter the Age = ";
cin>>genius[i].age;
}
//array of structure example for(int j=0;j<n;j++)
#include<iostream> {
using namespace std; cout<<"\n The Bio-Data of the student no "<<j+1<<" is :\
n";
struct student cout<<"\t Name = "<<genius[j].name<<endl;
{ cout<<"\t Roll No = "<<genius[j].studentNUM<<endl;
char name[25]; cout<<"\t Section = "<<genius[j].section<<endl;
char section[10]; cout<<"\t Semester = "<<genius[j].term<<endl;
int studentNUM; cout<<"\t Age = "<<genius[j].age<<endl;
int term; }
int age;
};

76
system("PAUSE"); return 0;
return 0; }
}
void printemployee (Employee employee)
#include <iostream> {
#define Length 3 cout << employee.title;
using namespace std; cout << " (" << employee.year << ")\n";
struct Employee }
{
char title [50];
int year;
} NESTED STRUCTURE
employee [Length];
#include<iostream>
void printemployee (Employee employee); using namespace std;
struct DptDetails
int main () {
{ char name[25];
char mychar [50]; char Department[10];
} student1;
for (int n=0; n<Length; n++)
{ struct student
cout << "Enter title: "; {
cin.getline (employee[n].title,50); int studentno;
cout << "Enter year: "; int term;
cin.getline (mychar,50); int age;
DptDetails student1;
} };
cout << "\nYou have entered these employees:\n"; int main( )
for (int n=0; n<Length; n++) {
printemployee (employee[n]); student BestStudent;
cout<<"\n -------- Use of structure --------- \n"<<endl;

77
cout<<"\t Enter the Name = "; float inches;
gets(BestStudent.student1.name); };
cout<<"\t Enter the student number = "; struct Room
cin>>BestStudent.studentno; {
cout<<"\t Enter the Department = "; Distance length;
cin>>BestStudent.student1.Department; Distance width;
cout<<"\t Enter the term in figures = "; };
cin>>BestStudent.term; int main()
cout<<"\t Enter the Age = "; {
cin>>BestStudent.age; Room dining;
cout<<"enter length in feet and inch"<<endl;
cout<<"\n -------- Use of Nested Structure --------- \ cin>>dininglengthfeet>>dininglengthinch;
n"<<endl; cout<<"enter width in feet and inch"<<endl;
cout<<"\t Name = "<<BestStudent.student1.name<<endl; cin>>diningwidthfeet>>diningwidthinch;
cout<<"\t Roll No = "<<BestStudent.studentno<<endl; //dining.length.feet = 13;
cout<<"\t Section = //dining.length.inches = 6.5;
"<<BestStudent.student1.Department<<endl; //dining.width.feet = 10;
cout<<"\t Semester = "<<BestStudent.term<<endl; //dining.width.inches = 0.0;
cout<<"\t Age = "<<BestStudent.age<<endl;
float l = dining.length.feet + dining.length.inches/12;
system("PAUSE"); float w = dining.width.feet + dining.width.inches/12;
return 0;
} cout <<"Dining area is\t"<< l * w;
system("PAUSE");
#include <iostream> return 0;
using namespace std; }
int dininglengthfeet,diningwidthfeet,
dininglengthinch,diningwidthinch;
struct Distance
{
int feet; FILES EXAMPLES

78
Write a program which explains how to write Menu Driven switch (choice)
Program in C++. This Menu Driven Program explains how to {
take get data from user, how to append data, how to modify case 1 : {
record and how to display records. It explains complex file ofstream outfile;
concepts in Menu driven fashion. Program also demonstrate outfile.open("emp",ios::out);
File Operation such as How to add record to file, How to cout<<"\n\nPlease enter the details as per demanded\n";
append records to file, How to modify records of file and cout<<"\nEnter the name : ";
displaying all records from File. char name[20];
cin>>name;
#include <iostream> outfile<<name<<endl;
#include <fstream> cout<<"Enter Age : ";
#include <conio.h> int age;
using namespace std; cin>>age;
int size=80; outfile<<age<<endl;
int main() cout<<"Enter programming language known by him\her :
{ ";
int totrec=0; char lang[25];
{ cin>>lang;
int choice; outfile<<lang<<endl;
while(1) totrec= totrec + 1;
{ outfile.close();
}
cout<<"Choose your choice\nNOTE : one choice for one break;
record(except viewing data)\n"; case 2 : {
cout<<"1) Scanning intial records\n"; ofstream outfile;
cout<<"2) Appending records\n"; outfile.open("emp",ios::app);
cout<<"3) Modifying or append records\n"; cout<<"\n\nPlease enter the details as per demanded\n";
cout<<"4) Viewing records\n"; cout<<"\nEnter the name : ";
cout<<"5) Exit\n"; char name[20];
cout<<"Enter your choice : "; cin>>name;
cin>>choice; outfile<<name<<endl;

79
cout<<"Enter Age : "; char lang[25];
int age; cin>>lang;
cin>>age; outfile<<lang<<endl;
outfile<<age<<endl; totrec = totrec + 1;
cout<<"Enter programming language known by him : "; }
char lang[25]; outfile.close();
cin>>lang; }
outfile<<lang<<endl; break;
totrec = totrec + 1; case 4 : {
outfile.close(); ifstream infile;
} infile.open("emp",ios::in);
break; //constint size=80;
case 3 : { char line[size];
ofstream outfile; int counter=totrec;
outfile.open("emp",ios::ate); while(counter > 0)
cout<<"Are you interested in adding record\nenter y or {
n\n"; infile.getline(line,size);
char ans; cout<<"\n\nNAME : "<<line<<endl;
cin>>ans; infile.getline(line,size);
if(ans=='y' || ans=='Y') cout<<"AGE : "<<line<<endl;
{ infile.getline(line,size);
cout<<"\n\nPlease enter the details as per demanded\n"; cout<<"LANGUAGE : "<<line<<endl;
cout<<"\nEnter the name : "; counter--;
char name[20]; }
cin>>name; infile.close();
outfile<<name<<endl; }
cout<<"Enter Age : "; //getch();
int age; break;
cin>>age; case 5 :
outfile<<age<<endl;
cout<<"Enter programming language known by him : "; cout<<"gotoout";

80
cout << "Enter your age: ";
default : cout<<"\nInvalid Choice\nTRY AGAIN\n"; cin >> data;
} cin.ignore();
}
//out: // again write inputted data into the file.
} outfile << data << endl;
}
// close the opened file.
outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("afile.dat");
#include <fstream>
#include <iostream> cout << "Reading from the file" << endl;
using namespace std; infile >> data;

int main () // write the data at the screen.


{ cout << data << endl;

char data[100]; // again read the data from the file and display it.
infile >> data;
// open a file in write mode. cout << data << endl;
ofstream outfile;
outfile.open("afile.dat"); // close the opened file.
infile.close();
cout << "Writing to the file" << endl;
cout << "Enter your name: "; return 0;
cin.getline(data, 100); }

// write inputted data into the file.


outfile << data << endl;
#include<iostream>

81
#include<fstream> return(id+1);
include<conio.h> else
#include<iomanip> {
#include<string.h> fin.read((char*)&temp,sizeof(temp));
using namespace std; while(!fin.eof())
int menu(); {
class Book id=temp.bookid;
{ fin.read((char*)&temp,sizeof(temp));
private: }
int bookid; id++;
char title[20]; return(id);
float price; }
protected: }
int allotbookid();
void showheader();
public: void Book::showheader()
void getbook(); {
void showbook(); cout<<left;
void addbook(); cout<<"\n"<<setw(10)<<"BOOK
void viewbook(); ID"<<setw(10)<<"Price"<<setw(10)<<"Title\n";
void searchbook(); }
void deletebook(); void Book::getbook()
void modifybook(); {
}; cout<<"Enter Book Title: ";
int Book::allotbookid() fflush(stdin);
{ gets(title);
ifstream fin; cout<<"Price of Book: ";
Book temp; cin>>price;
int id=0; bookid=allotbookid();
fin.open("bookfile.txt",ios::in|ios::binary); }
if(!fin) void Book::showbook()

82
{ fin.close();
cout<<left; }
cout<<"\ void Book::searchbook()
n"<<setw(10)<<bookid<<setw(10)<<price<<setw(10)<<title; {
} ifstream fin;
void Book::addbook() char str[20];
{ fin.open("bookfile.txt",ios::in|ios::binary);
ofstream fout; cout<<"Enter the name of book to search:";
fout.open("bookfile.txt",ios::out|ios::app|ios::binary); fflush(stdin);
if(!fout) gets(str);
cout<<"File can not open"; if(!fin)
else cout<<"File not found";
fout.write((char*)this,sizeof(*this)); else
fout.close(); {
} fin.read((char*)this,sizeof(*this));
void Book::viewbook() while(!fin.eof())
{ {
ifstream fin;
fin.open("bookfile.txt",ios::in|ios::binary); if(!strcmp(this->title,str))
if(!fin) {
cout<<"File not found"; showheader();
else showbook();
{ break;
showheader(); }
fin.read((char*)this,sizeof(*this)); fin.read((char*)this,sizeof(*this));
while(!fin.eof()) }
{ if(fin.eof())
showbook(); cout<<"\nRecord not found";
fin.read((char*)this,sizeof(*this)); }
} fin.close();
} }

83
void Book:: modifybook() file.read((char*)this,sizeof(*this));
{ }
int id,r=0; if(file.eof())
fstream file; cout<<"Record not found";
file.open("bookfile.txt",ios::in|ios::out|ios::ate|ios::binary); }
cout<<"\nEnter record number to modify (bookid): "; file.close();
cin>>id; }
file.seekg(0); void Book:: deletebook()
if(!file) {
cout<<"File not found"; ifstream fin;
else ofstream fout;
{ int id;
file.read((char*)this,sizeof(*this)); char x;
fin.open("bookfile.txt",ios::in|ios::binary);
while(!file.eof()) fout.open("tempfile.txt",ios::out|ios::app|ios::binary);
{ cout<<"Enter bookid to delete record";
r++; cin>>id;
if(bookid==id) if(!fin)
{ cout<<"File not found";
showheader(); else
showbook(); {
cout<<"\nRe-enter book details:\n"; fin.read((char*)this,sizeof(*this));
cout<<"Enter book title:"; while(!fin.eof())
fflush(stdin); {
gets(title); if(this->bookid==id)
cout<<"Enter book price"; {
cin>>price; cout<<"Record you want to delete is:\n\n";
file.seekp((r-1)*sizeof(Book),ios::beg); showheader();
file.write((char*)this,sizeof(*this)); showbook();
break; cout<<"\nAre you sure you want to delete this
} record(y/n): ";

84
fflush(stdin); cout<<"\n\nEnter your choice";
cin>>x; int ch;
if(x=='n') cin>>ch;
fout.write((char*)this,sizeof(*this)); return(ch);
else }
cout<<"\nRecord is deleted"; int main()
} {
else Book b;
fout.write((char*)this,sizeof(*this)); int ch;
fin.read((char*)this,sizeof(*this)); while(1)
} {
fin.close(); ch=menu();
fout.close(); switch(ch)
{
case 1:
system("erase bookfile.txt"); b.getbook();
getch(); b.addbook();
system("rename tempfile.txt bookfile.txt"); break;
case 2:
b.viewbook();
} break;
} case 3:
int menu() b.searchbook();
{ break;
system("cls"); case 4:
cout<<"\n1. Add new book"; b.modifybook();
cout<<"\n2. View all books"; break;
cout<<"\n3. Search book"; case 5:
cout<<"\n4. modify book"; b.deletebook();
cout<<"\n5. delete book"; break;
cout<<"\n6. Exit"; case 6:

85
exit(0); ALGORITHM:
default: STEP 1: Start the program.
cout<<"Enter Valid choice";
} STEP 2: Declare the variables.
getch();
} STEP 3: Read the file name.
}
STEP 4: open the file to write the contents.
#include<iostream>
#include<conio.h> STEP 5: writing the file contents up to reach a particular
#include<fstream> condition.
using namespace std;
int main() STEP 6: Stop the program.
{
char c,fname[10];
#include<iostream>
ofstream out;
using namespace std;
cout<<"Enter File name:";
#include<fstream>
cin>>fname;
int main()
out.open(fname);
{
cout<<"Enter contents to store in file (Enter # at end):\
char c,fname[10];
n";
ofstream out;
while((c=getchar())!='#')
cout<<"Enter File name:";
{
cin>>fname;
out<<c;
out.open(fname);
}
cout<<"Enter contents to store in file (Enter # at end):\
out.close();
n";
getch();
while((c=getchar())!='#')
}
{
cout<<c;
}
out.close();

86
system("PAUSE"); // again write inputted data into the file.
return 0; outfile << data << endl;

} // close the opened file.


outfile.close();

// open a file in read mode.


#include <fstream> ifstream infile;
#include <iostream> infile.open("afile.dat");
using namespace std;
cout << "Reading from the file" << endl;
int main () infile >> data;
{
// write the data at the screen.
char data[100]; cout << data << endl;

// open a file in write mode. // again read the data from the file and display it.
ofstream outfile; infile >> data;
outfile.open("afile.dat"); cout << data << endl;

cout << "Writing to the file" << endl; // close the opened file.
cout << "Enter your name: "; infile.close();
cin.getline(data, 100);
return 0;
// write inputted data into the file. }
outfile << data << endl;

cout << "Enter your age: ";


cin >> data;
cin.ignore(); Question 1

87
Write a C++ program to write number 1 to 100 in a data file return 0;
NOTES.TXT. }

#include<fstream.h>
int main()
{ Question 3
ofstream fout;
fout.open("NOTES.TXT"); Write a user-defined function in C++ to read the content from
for(int i=1;i<=100;i++) a text file OUT.TXT, count and display the number of alphabets
fout<<i<<endl; present in it.
fout.close();
return 0; void alphabets()
} {
ifstream fin;
Question 2 fin.open("out.txt");
char ch;
Write a C++ program, which initializes a string variable to the int count=0;
content "Time is a great teacher but unfortunately it kills all its while(!fin.eof())
pupils. Berlioz" and outputs the string to the disk file OUT.TXT. {
fin.get(ch);
you have to include all the header files if required
if(isalpha(ch))
#include<fstream.h>
count++;
}
int main()
cout<<"Number of alphabets in file are "<<count;
{
fin.close();
ofstream fout;
}
fout.open("out.txt");
char str[300]="Time is a great teacher but
unfortunately it kills Question 4
all its pupils. Berlioz"; Write a function to count the number of blank present in a
fout<<str; text file named "OUT.TXT".
fout.close();
88
void blankspace() char word[30];
{ int count=0;
ifstream fin; while(!fin.eof())
fin.open("out.txt"); {
char ch; fin>>word;
int count=0; count++;
while(!fin.eof()) }
{ cout<<"Number of words in file are "<<count;
fin.get(ch); fin.close();
if(ch==' ') }
count++;
}
cout<<"Number of blank spaces in file are "<<count;
fin.close(); Question 6
}
Write a function in C++ to print the count of word the as an
independent word in a text file STORY.TXT.
for example, if the content of the file STORY.TXT is
There was a monkey in the zoo. The monkey was very
naughty. Then the ouput of the program should be 2
void countword()
{
Question 5 ifstream fin;
fin.open("STORY.TXT");
char word[30];
Write a function to count number of words in a text file
int count=0;
named "OUT.TXT". while(!fin.eof())
void countwords() {
{ fin>>word;
ifstream fin; if(strcmpi(word,"the")==0)
fin.open("out.txt"); count++;

89
} cout<<"Number of lines not starting with A are
cout<<"Number of the word in file are "<<count; "<<count;
fin.close(); fin.close();
} }

Question 7 Question 8

Write a function in C++ to count and display the number of Assuming that a text file named FIRST.TXT contains some text
lines not starting with alphabet 'A' present in a text file written into it, write a function named copyupper(), that reads
"STORY.TXT". the file FIRST.TXT and creates a new file named SECOND.TXT
Example: contains all words from the file FIRST.TXT in uppercase.
If the file "STORY.TXT" contains the following lines, Question 8
The rose is red. Assuming that a text file named FIRST.TXT contains some text
A girl is playing there.
written into it, write a function named vowelwords(), that
There is a playground.
reads the file FIRST.TXT and creates a new file named
An aeroplane is in the sky.
Numbers are not allowed in the password. SECOND.TXT, to contain only those words from the file
FIRST.TXT which start with a lowercase vowel (i.e., with 'a', 'e',
The function should display the output as 3. 'i', 'o', 'u').
void countlines() For example, if the file FIRST.TXT contains
{ Carry umbrella and overcoat when it rains
ifstream fin;
Then the file SECOND.TXT shall contain
fin.open("STORY.TXT");
char str[80]; umbrella and overcoat
int count=0;
while(!fin.eof()) void copyupper()
{ {
fin.getline(str,80); ifstream fin;
if(str[0]!='A')
count++; fin.open("FIRST.TXT");
} ofstream fout;
fout.open("SECOND.TXT");

90
char ch; {
while(!fin.eof()) fin>>word;
{ if(word[0]=='a'||word[0]=='e'||
fin.get(ch); word[0]=='i'||word[0]=='o'||word[0]=='u')
ch=toupper(ch); fout<<word<<" ";
fout<<ch; }
} fin.close();
fin.close(); fout.close();
fout.close(); }
}

Assuming that a text file named FIRST.TXT containssome text


written into it, write a function named vowelwords(), that #include <iostream>
reads the file FIRST.TXT and creates a new file named #include <conio.h>
#include <iomanip>
SECOND.TXT, to contain only those words from the file
#include <fstream>
FIRST.TXT which start with a lowercase vowel (i.e., with 'a', 'e',
'i', 'o', 'u'). using namespace std;
For example, if the file FIRST.TXT contains int main()
Carry umbrella and overcoat when it rains {
Then the file SECOND.TXT shall contain FILE *fp, *ft;//file decleration
char another, choice;
umbrella and overcoat it solution

void vowelwords() struct student // Structure to define variables in the Student


{ Records.
ifstream fin; {
fin.open("FIRST.TXT"); char first_name[50], last_name[50];// data for the Name
ofstream fout; of studnet.
fout.open("SECOND.TXT"); char Subject[100];
char word[30]; int ID_Number;
while(!fin.eof()) int Mark;

91
}; cout << "\n\n";
cout << "\t\t\t Select Your Choice :=> ";
struct student e;
char xfirst_name[50], xlast_name[50]; choice = getche();
int stID_Number; switch(choice)
long int recsize; {
case '1' :
fp=fopen("users.txt","rb+"); fseek(fp,0,SEEK_END);
another ='Y';
if (fp == NULL) while(another == 'Y' || another == 'y')
{ {
fp = fopen("users.txt","wb+"); cout << "\t\tADD RECORD \n";
cout << "Enter the Firt Name : ";
if (fp==NULL) cin >> e.first_name;
{ cout << "Enter the Last Name : ";
puts("Cannot open file"); cin >> e.last_name;
return 0; cout << "Enter the ID_Number : ";
} cin >> e.ID_Number;
} cout << "Enter the Subject : ";
recsize = sizeof(e); cin >> e.Subject;
cout << "Enter Mark : ";
while(1) cin >> e.Mark;
{
cout << "\t\t====== NC STUDENT RECORDS======"; fwrite(&e,recsize,1,fp);
cout <<"\n\n "; cout << "\n Add Another Record (Y/N) ";
cout << "\n\n"; fflush(stdin);
cout << "\n \t\t\t 1. Add Record"; another = getchar();
cout << "\n \t\t\t 2. Display Records"; }
cout << "\n \t\t\t 3. Update Record"; break;
cout << "\n \t\t\t 4. Delete Record"; case '2':
cout << "\n \t\t\t 5. Exit Program"; rewind(fp);

92
cout << "=== View the Records in the Database ==="; cout << "Enter new Mark : ";
cout << "\n"; cin >> e.Mark;
cout<< "ID NUMBER\t"<<"FIRST NAME\t"<<"LAST fseek(fp, - recsize, SEEK_CUR);
NAME\t"<<"SUBJECT\t"<<" MARKS"; fwrite(&e,recsize,1,fp);
while (fread(&e,recsize,1,fp) == 1) break;
{ }
cout << "\n"; else
cout <<"\n" <<e.ID_Number<<setw(18)<< e.first_name cout<<"record not found";
<<"\t\t"<< setw(10) }
<< e.last_name <<setw(10)<<e.Subject << setw(8) << cout << "\n Modify Another Record (Y/N) ";
e.Mark; fflush(stdin);
} another = getchar();
cout << "\n\n"; }
break; break;

case '3' :
another = 'Y'; case '4':
while (another == 'Y'|| another == 'y') another = 'Y';
{ while (another == 'Y'|| another == 'y')
cout << "\t\t TO UPDATE A RECORD; "; {
cout<< " "; cout << "\t\t TO DELETE A RECORD; ";
cout << "\n Enter the ID Number of the student : "; cout << "\n Enter the ID Number of the student to
cin >> stID_Number; delete : ";
cin >> stID_Number;
rewind(fp);
while (fread(&e,recsize,1,fp) == 1) ft = fopen("temp.dat", "wb");
{
if (stID_Number==e.ID_Number)// rewind(fp);
{ while (fread (&e, recsize,1,fp) == 1)
cout << "Enter new the Subject : ";
cin >> e.Subject; if (stID_Number==e.ID_Number)

93
{ string msy;
fwrite(&e,recsize,1,ft); ofstream omyfile("file.txt");
} cout<<" tell us about yourself \n";
fclose(fp); getline (cin,msy);
fclose(ft); omyfile << msy;
remove("users.txt"); omyfile.close ();
rename("temp.dat","users.txt"); }

fp=fopen("users.txt","rb+"); #include <fstream>


#include <iostream>
cout << "\n Delete Another Record (Y/N) "; using namespace std;
fflush(stdin);
another = getchar(); int main ()
} {
break;
case '5': char data[100];
fclose(fp);
cout << "\n\n"; // open a file in write mode.
cout << "\t\t THANK YOU FOR USING THIS ofstream outfile;
SOFTWARE"; outfile.open("afile.dat");
cout << "\n\n";
return 0; cout << "Writing to the file" << endl;
} cout << "Enter your name: ";
} cin.getline(data, 100);
}
#include <iostream> // write inputted data into the file.
#include <fstream> outfile << data << endl;
#include <string.h>
using namespace std; cout << "Enter your age: ";
int main () cin >> data;
{ cin.ignore();

94
// again write inputted data into the file. UNDER CONSTRUCTION
outfile << data << endl;
#include <stdio.h>
// close the opened file.
outfile.close(); /* structure A declared */
typedef struct A {
// open a file in read mode. int a;
ifstream infile; float b;
infile.open("afile.dat"); }New_a;

cout << "Reading from the file" << endl; /* structure B declared */
infile >> data; typedef struct B {
int c;
// write the data at the screen. float d;
cout << data << endl; struct A e; /* member 'e' is itself a structure */
}New_b;
// again read the data from the file and display it.
infile >> data; int main(void)
cout << data << endl; {
/* Let's declare variables of New_a and New_b */
// close the opened file. New_a bread;
infile.close(); New_b butter; /* 'butter' is a nested structure */
system("PAUSE");
return 0; /* Let's access bread using dot operator */
} bread.a = 10; /* assigned member a value 10 */
bread.b = 25.50;

/* Let's access butter using dot operator */


butter.c = 10;
butter.d = 50.00;

95
cout<<" Name:”;
/* Let's access member 'e' which is a nested structure */ cin>>emp[i]name;
butter.e.a = 20; cout<<" Salary:";
butter.e.b = 20.00; cin>>emp[i] .salary;
cout<<"\n" ;
/* Display values of members of 'butter.e' structure */ for(int i=0;i<size;i++) //displaying data of emp
printf("butter.e.a is %4d\n", butter.e.a); {
printf("butter.e.b is %.2f\n", butter.e.b); Cout<<"Details of employee #"<<(i+1)<<" are:\n";
Cout<<" Code: "<<emp[i] .emp_no<<"\n" ;
return 0; Cout<<" Name: "<<emp[i] .name<<"\n";
} Cout<<" Salary: "<<emp[i] .salary<<"\n";
}
return 0;
}
#include<iostream>
using namespace std; EVEN OR ODD
const int size=2; //size of array #include <iostream>
using namespace std;
struct employee //structure definition
{ int main() {
int emp_no; int n;
cout << "Enter an integer: ";
char name [10];
cin >> n;
float salary; if ( n%2 == 0) {
}; cout << n << " is even.";
int main () }
else {
{ cout << n << " is odd.";
//array within structure
employee emp[size]; //declaring array of structures emp }
return 0;
for(int i=0;i<size;i++) //reading data into emp }
cout<<"Enter' details for employee #"<< (i+l)<<": \n";
cout<<" Code: ";
cin>>emp[i].emp_no; //accessing members

96
#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter an integer: ";
cin >> n;

(n%2 == 0) ? cout << n << " is even." : cout


<< n << " is odd.";

return 0;
}

97

You might also like