Header Ads Widget

BCA Information

CPP Program

 

Lab 1:

 

C++ Program Introduction Examples

 


1)          W.A.P. to print sentence.

Source Code

/* C++ Program to print a sentence. */

#include <iostream.h>

#include<conio.h>

int main()

{

   Cout<<"C++ Programming"; /* cout<< prints the content inside quotation */

return 0;

}

Output

C++ Programming

 

Explanation

Every C++ program starts executing code from main( ) function. Inside main( ), there is a cout<< function which prints the content inside the quotation mark which is "C++ Programming" in this case.

 

 

 

2) W.A.P. For Calculating Average Of Marks Of Three Subjects and Print it.

/ * Program For Calculate Average of Marks of Three Subjects*/

 

#include<iostream.h>

 

Void main()

{

 clrscr();

  //variable Declaration

  int a,b,c;

  float avg;

 cout<<"Enter Three subjects marks";

 cin>>a>>b>>c;

 

 //calculate average

 avg=(a+b+c)/3;

 

 cout<<"\nAverage="<<avg;

 getch();

 

 }

 


 Output

Enter three subjects’ marks 70 80 60

            Average=70

 

Explanation

In this program, user is asked to enter three subjects marks. The Three subjects marks entered by user will be stored in variables a, variables b and c respectively. This is done using cin>> function. Then, + operator is used for adding variables a, b and c and / operator is used for dividing this addition value by 3 is assigned to variable avg

Finally, the Average is displayed and program is terminated


3) W.A.P. For Swapping Of Two Numbers By Using Three Variables.(2)

/*program for swapping of two number by using third variable*/

#include<iostream.h>

#include<conio.h>

 

Void main ()

{

 clrscr ();

 int a,b,temp;

 cout<<"\n Enter Two Numbers=";

 cin>>a>>b;

 cout<<"\n Numbers Before Swapping="<<"a="<<a<<"\tb="<<b;

 

 temp=a;

 a=b;

 b=temp;

 cout<<"\n Numbers After Swapping="<<"a="<<a<<"\tb="<<b;

      getch();

 }

 


Output

Enter Two Numbers= 20   30

Numbers Before Swapping=20 30

            Numbers After Swapping=30   20

 

Explanation

In this program, user is asked to enter Two Numbers. The Two Numbers entered by user will be stored in variables a, variables b  respectively. This is done using cin>> function. Then, temp Third variable is used for storing value of variables a, then value of b is assign to a and temp variable value is assign to b,so value of a become value of variable b and value of b is become value of variable a, Finally, the values of before swapping and After swapping are displayed and program is terminated.


4) W.A.P. For Swapping Of Two Numbers Without Using Third Variables.

  /*program for swapping of two number without using third variable*/

#include<iostream.h>

#include<stdio.h>

void main()

{

 

 int a,b;

 cout<<"\n Enter Two Numbers=";

 cin>>a>>b;

 cout<<"\n Number Before Swapping="<<"a="<<a<<"\tb="<<b;

 

 a=a+b;

 b=a-b;

 a=a-b;

 

 cout<<"\n number After Swapping="<<"a="<<a<<"\tb="<<b;

 

 }

 

Output

Enter Two Numbers= 20   30

Numbers Before Swapping=20 30

            Numbers After Swapping=30   20

Explanation

In this program, user is asked to enter Two Numbers. The Two Numbers entered by user will be stored in variables a, variables b respectively. This is done using cin>> function. Then, in variable a store addition of a and b variable, so value of b is get by a-b operation, and then value of variable get by a=a-b, so value of a become value of variable b and value of b is become value of variable a, Finally, the values of before swapping and After swapping are displayed and program is terminated

 

              5) W.A.P.  To Calculate Area Of Triangle.(21)

/*Programm For Area of Triangle*/

 

#include<iostream.h>

#include<conio.h>

 

void main()

{

clrscr();

 int b,h;

 float area;

 

 cout<<"\nEnter Base and Height of Triangle";

 cin>>b>>h;

 area=0.5*b*h;

  cout<<"\n Area of Triangle is="<<area;

  getch();

 

}

 


Output

Enter Base and Height of Triangle = 10   20

Area of Triangle is =100

        Explanation

In this program, user is asked to enter Base and Height of Triangle. The Base is stored in Variable b and Height is stored in variable h, this is done using cin>> function. Then, in variable area store area of triangle, by using formula of triangle finally, the area of triangle displayed and program is terminated

 

 

 

          6) W.A.P.  To Calculate Area Of Rectangle.

/*Programm For Area of Rectangle*/

 

#include<iostream.h>

#include<conio.h>

 

void main()

{

clrscr ();

 int l,b,area;

 

 cout<<"\nEnter lenght and breath ;

 cin>>l,b;

 area=l*b;

  cout<<"\n Area of Rectangle is="<<area;

  getch();

}

 

Output

Enter length and breath = 10    5

Area of Rectangle is=50

  Explanation

In this program, user is asked to enter length and breadth of Rectangle. The length is stored in Variable l and breath is stored in variable b, this is done using cin>> function. Then, in variable area store area of rectangle, by using formula of Rectangle. Finally, the area of Rectangle is displayed and program is terminated

 

 

   7) W.A.P. To Covert Temperature Fahrenheit to centigrade.

/*program for temperature conversion*/

#include<iostream.h>

#include<conio.h>

 

void main()

{

 clrscr();

 float    f, c;

 cout<<"\Enter temperature in Fahrenheit=";

 cin>>f;

 c=((5.0/9.0)*(f-32.0));

 cout<<"\n Temperature in centigrade="<<c;

 getch();

 

}

 


Output

Enter temperature in Fahrenheit = 10    5

Temperature in centigrade =50

  Explanation

In this program, user is asked to enter temperature in Fahrenheit. The temperature in Fahrenheit is stored in Variable f , this is done using cin>> function. Then, in variable c store temperature in centigrade, by using formula of conversion. Finally, the temperature in centigrade is displayed and program is terminated

 

 


Lab 2:

C++ Program Decision Making, loop control Examples

 


1.     W.A.P. To find given number is Even or Odd.

/*program to check given number even or odd*/

#include<iostream.h>

#include<conio.h>

 

void main()

{

  clrscr ();

  int n;

                         cout<<"\nEnter number=";

  cin>>n;

 if(n%2==0)

   {

     cout<<"\nGiven Number\t "<<n<<"is even";

   }

   else

   {

     cout<<"Given Number"<<n<<"is Odd";

   }

 getch();

}

 


Output

Enter number=750

           Given Number 750 is even

 

       2) W.A.P. For Printing Maximum From Three Numbers.

In this program, user is asked to enter three numbers and this program will find the maximum number among three numbers entered by user.

        /*program for find maximum from three numbers*/

                      #include<iostream.h>

#include<conio.h>

                     void main()

{

  clrscr();

  int a,b,c,max;

  cout<<"Enter three numbers=";

  cin>>a>>b>>c;

                        if(a>b && b>c)

  {

    max=a;

  }

  else if(b>c && c>a)

  {

   max=b;

  }

  else

  {

   max=c;

  }

                      cout<<"Maximum number ="<<max;

getch();

}

 


Output

Enter three numbers= 10    80   50

Maximum number =80

 

 

            C++ While Loops Examples

1)    W.A.P. To Calculate Factorial of Given Number.

This program takes an integer number from user and Calculate factorial of that number.

 

/*Program for Factorial Of number*/

                      #include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

 int n,i,f;

 f=1;

 i=1;

 cout<<"\nEnter Number";

 cin>>n;

   while(i<=n)

   {

    f=f*i;

    i++;

   }//end of while

  cout<<"\n Factorial Of Number is="<<f;

  getch();

 

}

 


Output

          Enter Number = 4

          Factorial of Number is=24

 

 

 

         2). W.A.P. To Calculate Power of Given Number.

   This program below takes two integers from user, a base number and an     exponent. For example: In case of 23, 2 is the base number and 3 is the exponent of that number. And this program calculates the value of baseexponent

/*Program For Calculate Power Of given Number*/

#include<iostream.h>

#include<conio.h>

 

Void main ()

{

Clrscr ();

 int ans,i,p,b;

 cout<<"\nEnter base and power";

 cin>>b>>p;

 i=1;

 ans=1;

 while(i<=p)

 {

  ans=ans*b;

  i++;

 }

 

 cout<<"\npower of given number="<<ans;

 

 getch();

}

 


Output

          Enter base and power 4 3

          Power of given number=64

 

 

              3). W.A.P. For Fibonacci Series.              

The Fibonacci sequence is the series of numbers:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The next number is found by adding up the two numbers before it.

  • The 2 is found by adding the two numbers before it (1+1)
  • Similarly, the 3 is found by adding the two numbers before it (1+2),
  • And the 5 is (2+3), and so on!

Example: the next number in the sequence above would be 21+34 = 55

#include<iostream.h>

#include<conio.h>

                                void main()

{

  clrscr();

  int n,a,b,c;

  cout<<"Enter range=";

  cin>>n;

  a=0;

  b=1;

  n=n-2;

  cout<<"Fibonnaci series="<<a<<" "<<b<<" ";

   while(n>0)

   {

     c=a+b;

     cout<<c<<" ";

     a=b;

     b=c;

     n--;

   }

 getch();

}

 


Output

Enter range= 10

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

 

4). W.A.P. For Print Reverse Of Given Number

This program takes an integer number from user and reverses that number.

/*Program for print reverse of given number*/

 

#include<iostream.h>

#include<conio.h>

 

void main()

{

 clrscr();

 int n,r,rev,tem;

 cout<<"\enter number=";

 cin>>n;

 tem=n;

            rev=0;

 while(n>0)

 {

   r=n%10;

   rev=(rev*10)+r;

   n=n/10;

 }

            cout<<"reverse of"<<tem<<"="<<rev;

            getch();

 

}

 


Output

enter number=2546

reverse of 2546=6452

 

C++ For Loops Examples

1). W.A.P. To Print Even Number between 1 to 50.(25)

This program generates list of all even numbers from 1 to  50 The source code below will perform this task.

/*Program for printing even number bten 1 to 50*/

#include<iostream.h>

#include<conio.h>

 

void main()

{

 clrscr();

 int i=1;

  cout<<"Even numbers between 1 to 50 =\n";

 while(i<=50)

 {

   if(i%2==0)

   {

     cout<<i<<" ";

   }

   i++;

 }

 

  getch();

}

 


Output

Even numbers between 1 to 50 =2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50

 

 

 

2). Write program to print following output using for loop .

1                                            *****                                                    abcde

22                                         ****                                                      abcd

333                                         ***                                                       abc

4444                                        **                                                        ab

55555                                      *                                                         a

 

/*program for to print following

1

22

333

4444

55555*/

 

#include<iostream.h>

#include<conio.h>

void main()

{

  clrscr();

  int i,j;

  for(i=1;i<=5;i++)

  {

   for(j=1;j<=i;j++)

   {

     cout<<i;

   }

    cout<<"\n";

  }

  getch();

 

 

}

 

 

 

 

3) Write a C program to display reverse pyramid.

* * * * * * * * *

  * * * * * * *

    * * * * *

      * * *

        *

#include<iostream.h>

#include<conio.h>

void main()

{

Clrscr();

int rows,i,j,space;

 cout<<"Enter number of rows: ";

    cin>>rows;

    for(i=rows;i>=1;--i)

    {

  for(space=0;space<rows-i;++space)

           cout<<” “;

        for(j=i;j<=2*i-1;++j)

          cout<<”* “;

        for(j=0;j<i-1;++j)

            cout<<”* ";

      cout<<"\n";

    }

    }

 

 

 

 

 

Lab 3:

C++ Function Examples

 


1)    W.A.P.  Create a Function Add(), which Add two Numbers.(Function Topic)

This program call add()user define function which perform addition of two numbers

/*Program to add two number using Add()*/

 

#include<iostream.h>

#include<conio.h>

                      void Add(int a,int b); //function prototype

 void main()

 {

   clrscr();

 

   int x,y;

   cout<<"\nEnter two numbers=";

   cin>>x>>y;

   Add(x,y);

   getch();

 }

 

 //function Defination

  void Add(int a,int b)

  {

    int sum;

    sum=a+b;

    cout<<"Addition of two numbers="<<sum;

 

  }

Output

Enter two numbers=300 200

Addition of two numbers=500

2)    W.A.P.  To Calculate Square of Number by using Macro.

/*Program to calculate square of number by using Macro*/

#include<iostream.h>

#include<conio.h>

//macro

#define SQUARE(x) x*x

 

void main()

{

  clrscr();

  cout<<"Square of number="<<SQUARE(10);

  getch();

}

         This program use concepts of macro is preprocessor directives, macro      calculate the square of number.

 

 

 


                  Output

             Square of number=100

 

 

3)    W.A.P.  Calculate Square Of Number using inline Function.

/*Program to calculate square of number by using inline function*/

#include<iostream.h>

#include<conio.h>

 

//inline function

inline int square (int n)

{

  return n*n;

}

 

void main()

{

  clrscr();

  cout<<"Square of number="<<square(10);

  getch();

}

         This program use concepts of inline function, inline functionsuggest to the compiler that the code generated by the function body be inserted at each point the function is called, instead of being invoked with a regular function call.

                     Output

                 Square of number=100

 

 

4)    W.A.P.  To calculate multiplication of two numbers using inline function.

    /*Program to calculate Multiplication of two number by using inline function*/

#include<iostream.h>

#include<conio.h>

 

//inline function

 

inline int mul(int a,int b)

{

  return a*b;

}

 

void main()

{

  clrscr();

  cout<<"Multiplication of numbers="<<mul(10,20);

  getch();

}

Explanation

 This program use concepts of inline function, inline function suggest to the compiler that the code generated by the function body be inserted at each point the function is called, instead of being invoked with a regular function call.

                     Output

              Multiplication of numbers =200

 

5)    W.A.P. For Swapping Of Two Numbers. (Call By Reference).

/*program for swapping of two number by using third variable call by refreance*/

#include<iostream.h>

#include<conio.h>

 

void swap(int*,int*);

void main()

{

 clrscr();

 int a,b,temp;

 cout<<"\n Enter Two Numbers=";

 cin>>a>>b;

 cout<<"\n Number Before Swapping="<<"a="<<a<<"\tb="<<b;

 swap(&a,&b);

 cout<<"\n number After Swapping="<<"a="<<a<<"\tb="<<b;

 

 getch();

}

void swap(int *i,int *j)

{

int temp;

temp=*i;

*i=*j;

*j=temp;

}

      Explanation

     This program has swap function, inline function suggest to the compiler that the code generated by the function body be inserted at each point the function is called, instead of being invoked with a regular function call.

                         Enter Two Numbers=20 30

                          Number Before Swapping=20 30

                         Number Before Swapping=30 20

 

6)    W.A.P. To Check Given Number is Prime or Not.

           #include<iostream.h>

#include<conio.h>

 

void main()

{

  clrscr();

  int n,i;

  int j=1;

  i=2;

  cout<<"\nEnter number=";

  cin>>n;

 

  while(i<n)

  {

   if(n%i==0)

   {

     j++;

   }

 

   i++;

   }

       if(j==2)

       {

          cout<<"\n The Number is prime";

       }

       else

       {

          cout<<"The number is not prime";

       }

 

       getch();

 

}

 


Output

                                    Enter number=73

                             The Number is prime

 

Explanation

This program use concepts of looping, decision statements

Prime number is number which is divisible by 1 and it self.

So number is divide by from 1 to number if number is divide counter is incremented, then checked counter is equal to 2 if yes then number is prime.

 

                                   

7)    W.A.P.  To Check Given Number Is Perfect Number Or Not.

 

/*program  to check number is perfect or not*/

#include<iostream.h>

#include<conio.h>

 

void main()

{

 clrscr();

 int n,i,j,sum,tem;

 cout<<"\nEnter number=";

 cin>>n;

// tem=n;

 i=1;

 sum=0;

   while(i<n)

   {

    if(n%i==0)

    {

    sum=sum+i;

    }

    i++;

   }

   if(sum==n)

   {

     cout<<"\n Number is perfect number";

   }

   else

   {

    cout<<"\n Number is not perfect number";

   }

 getch();

 

}

 


Output

Enter number=28

Number is perfect number

 

Explanation

This program use concepts of looping, decision statements

Perfect number is the sum of its entire factor is equal to number then it is perfect.

 

 

8)    W.A.P. To Check Given Number Is Armstrong Number Or Not.

 

/*Program to check number is Amstrong or not*/

#include<iostream.h>

#include<conio.h>

 

void main()

{

  clrscr();

  int n,r,cub,sum,tem;

  cout<<"\n Enter number=";

  cin>>n;

  tem=n;

  sum=0;

  while(n>0)

  {

    r=n%10;

    cub=r*r*r;

    sum=sum+cub;

    n=n/10;

 

  }

  if(sum==tem)

  {

   cout<<"Number is Amstrong Number";

  }

  else

  {

   cout<<"Number is not Amstrong Number" ;

  }

 

getch();

}

 


Output

Enter number=153

                        Number is Armstrong Number.

 

 

Explanation

This program use concepts of looping, decision statements

Armstrong number is the sum of cube of all its digits is equal to number then it is Armstrong.

 

 

9)    W.A.P.  To Check Given Number Is Lucky Number Or Not.

 

/*program to check number is lucky number or not*/

#include<iostream.h>

#include<conio.h>

 

int calsum(int);

void main()

{

 clrscr();

 int n,sum,r;

 

 cout<<"\nEnter number=";

 cin>>n;

   sum=calsum(n);

 

 cout<<"sum="<<sum;

 if(sum==1)

 {

  cout<<"\nThe number is Lucky number";

 }

 else

 {

 cout<<"\nThe Number is not Lucky Number";

  }

 getch();

 

}

 

//calsum()

 

int calsum(int n)

{

int r,sum;

sum=0;

  while(n>0)

 {

 

  r=n%10;

  sum=sum+r;

  n=n/10;

 }

 if(sum>9)

 {

   n=sum;

  sum=calsum(n);

 }

 else

 {

 return sum;

 }

               }

 

Output

 Enter number=631

                       The Number is Lucky Number

Explanation

                   This program use concepts of looping, decision statements

                   Lucky number is if sum of all its digits is equal to 1 then it is Lucky.

                    In the program use calsum() function to calculate sum of digits up to 

                    single digits

 

 

 

 

10)  W.A.P.  To Check Given Number Is Palindrome Or Not.

/*Program to check given number is palindrome or not */

#include<iostream.h>

#include<conio.h>

 

void main()

{

 clrscr();

 int n,r,rev,tem;

 cout<<"\Enter number=";

 cin>>n;

 tem=n;

            rev=0;

 while(n>0)

 {

   r=n%10;

   rev=(rev*10)+r;

   n=n/10;

 }

  if(tem==rev)

  {

    cout<<"The number "<<tem<<" is palindrome";

  }

  else

  {

   cout<<"The number "<<tem<<" is not palindrome";

  }

            getch();

}

 


Output

Enter number=121

The number 121 is palindrome

 

               Explanation

                 This program use concepts of looping, decision statements

 Palindrome number is if reverse of the number is equal to number then  it is palindrome number. In the program use reverse the number and store in rev variable if rev is equal to number then it is palindrome

 

11)           W.A.P.  To Check Given Number Is Strong Or Not.

/*program to check given number is strong or not*/

#include<iostream.h>

#include<conio.h>

int fact(int a);//prototype

 

void main()

{

 

  clrscr();

  int n,r,f,i,sum,tem;

  sum=0;

  cout<<"Enter the number=";

  cin>>n;

  tem=n;

 

   while(n>0)

   {

    r=n%10;

    f=fact(r);

    sum=sum+f;

    n=n/10;

   }

 

    if(sum==tem)

    {

     cout<<"\nNumber is strong number";

    }

    else

    {

     cout<<"\nNumber is not strong number";

    }

 

   getch();

 }

 

  int fact(int a)

  {

   int  facto=1,i;

   i=1;

   while(i<=a)

   {

    facto=facto*i;

    i++;

   }

    return facto;

  }

 


Output

Enter the number=145

Number is strong number

 

               Explanation

                 This program use concepts of looping, decision statements

Strong number is if sum of factorial of each digits is equal to number then it is strong.in program rem use for storing  reminder means each digits then rem pass to fact() and calculate factorial of the number if sun of factorial of each digits is equal to number then it is strong number.

 

 

 

 

 

 

Lab 4:

C++ Class and Its Implementation

 


1)    W.A.P. For creating employee structure and print details of the employee.

/*employee structure*/

#include<iostream.h>

#include<conio.h>

 

  struct employee

{

  int no;

  char name[20];

  int age;

  float sal;

};

 

void main()

{

 clrscr();

 employee e;

 cout<<"enter employee details=";

 cin>>e.no>>e.name>>e.age>>e.sal;

 cout<<"\n Employee Record=";

 cout<<"\n EMP No.\t Name\t Age\tSalary";

 cout<<"\n"<<e.no<<"\t"<<e.name<<"\t"<<e.age<<"\t"<<e.sal;

 getch();

}

Explanation

  This program use concepts Structure, Structure is collection of different    data types, in above program employee structure where employee 

Name, age, salary in employee structure and it can get and display employee record by using structure variable.

 

 

Output

 

2)    W.A.P. To create class person, which has name, age private attributes and Address public, getdata (), display () function for display details of person.(26)

 

#include<iostream.h>

#include<conio.h>

class person

{

 char name[30];

 int age;

 public:

  char add[30];

 

  void getdata()

  {

    cout<<"\n---------------------------------------------- ";

   cout<<" \nEnter information of person=";

   cout<<"\nEnter name of person=";

   cin>>name;

   cout<<"\nEnter age of person=";

   cin>>age;

   cout<<"\nEnter Address of person=";

   cin>>add;

  }

     //------------------------------------------------------------------

      void display()

      {

      cout<<"--------------------------------------------------------";

      cout<<"\nName\tAge\tAddress\n";

      cout<<name<<"\t"<<age<<"\t"<<add;

      cout<<"\n--------------------------------------------------------";

                       }

 //--------------------------------------------------------------------

      };//end of the class

          void main()

  {

   clrscr();

   person p;

   p.getdata();

   p.display();

   getch();

  }

Output

Explanation

  This program use concepts class, class is single unit where  different    data types member and functions bind together, in above program person is class, person having name,age,salary as its data member and getdata()for enter value, display()for display person record are two member function.

 

3)Create Class Rectangle ,having length and breadth two parameters  and Three Functions getdata(),displaydata() and area_peri(),getdata() Function take value, displaydata() display results and aera_peri() calculate perimeter of a rectangle.(36)

/*program for class*/

 

#include<iostream.h>

#include<conio.h>

class Rectangle

{

 int l,b,arear;

 public:

 void getdata();

 void display();

 int area_peri();

 

};

 void Rectangle::getdata()

 {

   cout<<"\nEnter length and breadth=";

   cin>>l>>b;

 }

 //display() Function defination outside of the class

 void Rectangle::display()

 {

   cout<<"Perimeter ="<<arear;

 }

 //area_peri() function defination outside of the class

 int Rectangle::area_peri()

 {

  arear=((2*l)+(2*b));

  return arear;

 }

 

 void main()

 {

  clrscr();

  Rectangle r;

  r.getdata();

  r.area_peri();

  r.display();

  getch();

 

 }

Output

                     Enter length and breadth= 8   9

                      Perimeter =34

 

Explanation

  This program use concepts class, class is single unit where  different    data types member and functions bind together, in above program Rectangle is class, Rectangle has length l and breadth b two data members and getdata() for accepting values,area_peri() calculating perimeter of rectangle and display() for display result are the Member functions.                                 

 

 

4)W.A.P. For Creating Class Person ,Take Name, Age, Address As Input In GetData()Function, And Print Persons Details By Using PutData () Function.

     /*program for create class person and display details of that person*/

#include<iostream.h>

#include<conio.h>

 

class person

{

 public:

  char name[20],Address[20];

  int age;

  void getdata()

 {

    cout<<"\nEnter name of person=";

    cin>>name;

    cout<<"\nEnterAge of person=";

    cin>>age;

    cout<<"\nEnter Address of person=";

    cin>>Address;

 

  }

       //putdata ()

  Void putdata ()

  {

  cout<<"\nDetails=";

  cout<<"\nName\t\tAge\t\tAddress";

  cout<<"\n"<<name<<"\t\t"<<age<<"\t\t"<<Address;

  }

 

             } ;

           void main()

{

 clrscr();

 person p;

 p.getdata();

 p.putdata();

 getch();

}

Output

Explanation

 This program use concepts class, class is single unit where  different    data types member and functions bind together, in above program person is class, person having name,age,salary as its data member and getdata()for enter value, display()for display person record are two member function.

 

 

5) WAP to create class Student and display information 5 student name, roll no, age, percentage by using multiple object

/*program to create array of objects and display information of 5 students*/

 

#include<iostream.h>

#include<conio.h>

 

class student

{

  //data members

  int roll_no,age;

  char name[30];

  float per;

 public:

 

  void getdata()

  {

   cout<<"\n enter roll number-";

   cin>>roll_no;

   cout<<"\nEnter name of student-";

   cin>>name;

   cout<<"\nEnter age of student-";

   cin>>age;

   cout<<"\nEnter percentage of student-";

   cin>>per;

  }

 

 //-------------------------------------------------------

 void display()

 {

  cout<<"\n---------------------------------------";

  cout<<"\nRoll Number\t\tName\tAge\t\tPercentage";

  cout<<"\n"<<roll_no<<"\t"<<name<<"\t"<<age<<"\t"<<per;

  cout<<"\n-----------------------------------------";

 }

};//end of class

          void main()

{

 clrscr();

 student stud[5];

 

 for (int i=0;i<5;i++)

 {

                  stud[i].getdata ();

 }

   cout<<"\n ---------------Student Detials-----------------------";

 for (i=0;i<5;i++)

 {

   stud[i].display ();

 }

 getch ();

}

 

Output

 

Explanation

 This program use concepts class, class is single unit where  different    data types member and functions bind together, in above program Student is class, person having Roll_no, name,age,percentage as its data member and getdata()for enter value, display()for display student record are two member function. Here array of object are created so record of number of students display.

                  Object as arguments

6) W.A.P. To create class Time, which has member function gettime () it take time in hours and minutes, sum () it takes objects function arguments and it perform addition of time, puttime () it display result.(28)

/*Program to  create class Time ,it has data member time in hours and in minute and add two times and display it in puttime()

*/

 

#include<iostream.h>

#include<conio.h>

 class Time

{

Public:

 int hr, min;

 

   Void gettime ()

   {

    cout<<"\nEnter hours";

    Cin>>hr;

    cout<<"\nEnter Minute";

    Cin>>min;

   }

 Time caltime (Time, Time);

   Void puttime ();

 

}; //end of the class

//------------------------------------------------

Void Time::puttime ()

{

 Cout<<"Time="<<hr<<":"<< min;

}

//------------------------------------------------

 // function to calculate time

 

 Time caltime (Time t1, Time t2)

 {

  Time t3;

  int temp;

  t3.min=t1.min+t2.min;

   temp=t3.min/60;

   t3.min=t3.min%60;

   t3.hr=t1.hr+t2.hr+temp;

   return t3;

                   }

        //------------------------------------------------

 Void main ()

 {

 Clrscr ();

 Time t1, t2,t3;

 t1.gettime ();

 t2.gettime ();

 t3=caltime (t1, t2);

 t3.puttime ();

 getch ();

             }

Explanation

 This program use concepts class, class is single unit where different    data types member and functions bind together, in above program Student is class, Time having hours, minute as its data member and gettime () for enter value, putime()for display time and caltime for addition of two time,for clatime pass object of class time as arguments so addition of two times .

 

Output

 

 

7)W.A.P.To create class Matrix which store a matrix of integer of given size, write a necessary function to following  Addition of two matrices.(84)

8) W.A.P.  which has function power() to raise number m to power n. the function takes a double value for m and int value for n ,and return result correctly. Use a default value 2 for n to make function to calculate square when this argument is omitted. Write main that gets the values of m and n from user to test function.(33)

 /*program for write function power () that uses double value for m and interger value for n, take default value n=2 when argument is omitted*/

 

#include<iostream.h>

#include<conio.h>

                double power (double m, int n=2);

                 void main()

{

                  clrscr();

 int n;

 double m,po;

 cout<<"\n Enter base and power for calculation=";

 cin>>m>>n;

po=power(m,n);

cout<<"\npower="<<po;

po=power(m);

cout<<"\npower="<<po;

 getch();

 }

               double power(double m,int n)

 {

      int i=1;

  double po;

  while(i<=n)

  {

  po=m*m;

  i++;

  }

  return po;

//  cout<<"\n power="<<po;

 }

Output

 

Explanation

 This program use concepts class, class is single unit where different    data types member and functions bind together, in above program Demo is classDemo having base m, power n as its data member and power () for calculate power of numbers, here power()function has default arguments if we not pass value of n then power()take default value n=2 and calculate power.

 

9)W.A.P. To define class to represent bank account, Include following      members:

Name of depositor, accountnumber, type of account balance in account are data members, andMember Functions-1.To assign initial value 2.To deposit an account.3.To Withdraw amount after checking the balace,4. To display name and balance

             /*program to create class bank account ,it has data member Name of customer,accont number,type of account,balance in acount,member functions are 1)initialise account

2)deposite an account 3)withdrowal of account 4)display name and balance in account*/

 

#include<iostream.h>

#include<conio.h>

#include<stdio.h>

    class bank

{

 char name[30],type[30];

 long int accno;

 float bal;

 public:

 bank()

 {

 //name=0;

 //type=0;

// accno=0;

// bal=00000.00;

 }

 void getvalue()

 {

  cout<<"\n Enter name of depositor=";

  cin>>name;

  cout<<"\nEnter account number=";

  cin>>accno;

  cout<<"\nEnterType of account=";

  cin>>type;

  cout<<"\nEnter balance in account";

  cin>>bal;

 }

 //------------------------------------------------

 void deposite()

 {

  float amt;

  cout<<"\nEnter amount to be deposite=";

  cin>>amt;

  bal=bal+amt;

  cout<<"\nThe Amount "<<amt<<" is deposited in your account \n";

 }

 

//-------------------------------------------------

           void withdraw()

{

 float amt;

 cout<<"Enter amount to withdraw=";

 cin>>amt;

  if(bal>500)

   {

     if(bal-amt>500)

     {

      bal=bal-amt;

      cout<<"\nAmount "<<amt<<" is withdraw from account\n";

     }

    else

     cout<<"\nCant withdraw amount";

   }

   else

    {

     cout<<"\nYou can not withdraw amount\n";

    }

 }

 

 //--------------------------------------------------

  void display()

    {

     cout<<"-----------------------------------------------------------------\n";

     cout<<"-----------------Account Information------------------------------\n";

     cout<<"\nName\tAccount No\t Account Type\tBalance\n\n";

     cout<<name<<"\t"<<accno<<"\t\t"<<type<<"\t\t"<<bal<<"\n";

    }

 

 //------------------------------------------------

};

 

  void main()

  {

    clrscr();

 

    bank b;

    int ch;

  do

   {

    cout<<"-------------------------------------------------------\n"

      <<"1.Initailise value\n"<<"2.Display"<<"\n3.Deposite"<<"\n4.Withdraw";

 

    cout<<"\nEnter your choice=";

    cin>>ch;

    switch (ch)

    {

     case 1:

         b.getvalue();

         break;

     case 2:

 

        b.display();

        break;

     case 3:

 

       b.deposite();

       break;

     case 4:

 

       b.withdraw();

       break;

    // case 5:

     //          exit(0);

 

    default:

       cout<<"wrong choice";

    }//switch

 

 }while(ch);

 getch();

}

 

OUTPUT

 

 

 

 

Lab 5:

C++ Exception Handling

 

 


1)    W.A.P.  To create class demo which has member function Add () perform addition, mul () –multiplication, division ()-Division operation. Write try and catch block ,if any exception occur it catch by catch block(54)

#include<iostream.h>

#include<conio.h>

#include<stdio.h>

    class demo

{

 int a,b,result;

 float ans;

 public:

  void add(int x,int y)

  {

     a=x;

     b=y;

     result=a+b;

     cout<<"\nAddition="<<result;

  }

  //----------------------------------------

   void mul(int x,int y)

   {

     a=x;

     b=y;

     result=a*b;

     cout<<"\nMultiplication="<<result;

   }

                         //-----------------------------------------

                      void divide(int x,int y)

   {

    a=x;

    b=y;

 

    if(b!=0)

    {

    ans=a/b;

    cout<<"\nanswer="<<ans;

    }

    else

    {

    throw b;

    }

   }//divide

};

void main()

{

clrscr();

demo d;

try

{

d.add(10,20);

d.mul(10,20);

d.divide(20,10);

d.divide(20,0);

}  //try

 catch(int i)

{

 cout<<"Caught exception\n";

}

getch();

}

OUTPUT

Addition=30

Multiplication=200

answer=2

Caught exception

 

Explanation

 This program use concepts Exception Handling, Where in program if any error occur during compile time it can be handle, in above program Demo is class, Demo having result, a ,b as its data member and add() for addition of two numbers,mul() for multiplication of two numbers and divide for dividation of numbers are the member functions of the class. If any error occur suppose divide number by zero so it is catch, for that try and catch block used.

2)    W.A.P.  For :

 a)A function to read two double type numbers from keyboard

b) A try block to throw an exception when a wrong type data keyed in.

c) Appropriate catch block to handle the exception thrown.(55)

 

3)    WAP which show the use of multiple catch block.(56)

#include<iostream.h>

#include<conio.h>

      //void test(int);

       class demo

{

public:

void test(int x)

{

 try

 {

  if(x==1)

  throw x;

  else

    if(x==0)

    throw 'x';

    else

     if(x==-1)

     throw 1.0;

 }  //try end

                       catch(char c)

 {

  cout<<"Caught a character\n";

                      }//catch1

 catch(int m)

 {

  cout<<"\nCatch an integer";

 }   //catch 2

 catch(double d)

 {

  cout<<"\ncaught double";

                        }//catch 3

}

};

                     Void main ()

 {

 Clrscr ();

 cout<<"\n Testing of multiple catches";

  demo d;

 cout<<"\nx==1";

 d.test(1);

 cout<<"\nx==0";

 d.test(0);

 cout<<"\nx==-1";

d.test(-1);

// return 0;

 getch();

 }


OUTP
UT     

Testing of multiple catches

x==1 Catch an integer

x==0 Caught a character

x==-1 caught double

 

Explanation  This program use concepts Exception Handling, Where in program if any error occur during compile time it can be handle, in above program Demo is class, Demo having try block if any error occur it has caught.in the program multiple catch blocks are used to catch an exception.

 

 

 Lab 6:

C++ Operator Overloading

 

1)    W.A.P.  For Operator Overloading, Which overload Binary + Operator Using Friend Function,(42)

/*program for overloading binary + operator using friend function*/

#include<iostream.h>

#include<conio.h>

Addition operator+(Addition,Addition);

 

class Addition

{

int x,y,z;

public:

 Addition();

 Addition(int,int);

 

 friend Addition operator+(Addition,Addition);

 void display();

               };   //end of class

          Addition:: Addition(int a,int b)

 {

  x=a;

  y=b;

 }

       void Addition:: display()

{

 cout<<"Addition="<<x<<y;

}

 

       Addition operator+(Addition a,Addition b)

{

    Addition adt;

adt.x=a.x+b.x;

adt.y=a.y+ b.y;

 return adt;

}

 

             void main()

{

clrscr();

Addition A1,A2,A3;

A1=Addition(200,300);

A2=Addition(300,200);

//A3=A1+A2;

A3=operator+(A1,A2);

              //   A1.display();

//A2.display();

A3.display();

                getch();

}

 


OUTPUT

Addition=500 500

 

2)    W.A.P. For Operator Overloading Which Overload Unary – Operator.

/*program to overload unary - operator*/

#include<iostream.h>

#include<conio.h>

class space

{

 int x,y,z;

 public:

  void getdata(int a,int b,int c)

  {

   x=a;

   y=b;

   z=c;

  }

                   void display();

             void operator-();

 };

                  void space ::display()

 {

  cout<<"\nX="<<x;

  cout<<"\nY="<<y;

  cout<<"\nZ="<<z;

 }

            void space::operator-()

 {

  x=-x;

  y=-y;

  z=-z;

}

void main()

{

 clrscr();

space s;

s.getdata(10,-20,30);

s.display();

-s;

cout<<"\nAfter -";

s.display();

getch();

}

  OUTPUT

 

3)    W.A.P. for Overloading   >>Operator and << Operator.(44)

4)    W.A.P. To overload = Assignment.(77)

5)    W.A.P. To create class employee ,it has data member name,age,salary,parametrised constructor to initialize value ,friend function to over load <<operator, create class template for linklist,where link list append(),add beginning ,delete from beginning ,display content of link list operation are perform.(64)

6)    W.A.P.To create class Matrix which store a matrix of integer of given size, write a necessary function to overload following

+ Add two matrices and store in third matrix

== Returns 1 if two matrices are same otherwise return 0. (Use dynamic memory allocation)(45)

7)    W.A.P. for overloading area function if one argument pass then it calculate area of square and if two arguments pass it calculate area of rectangle.

8)    W.A.P. for overloading add function if intger arguments are pass then it calculate addition of two integer ,if float arguments are pass then it calculate addition of two floats and if string arguments pass it concat two string.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Lab 7:

 

 

C++ Inheritance Examples

 


1)      W.A.P. to create class demobase it contains one private data member, one public data and three public member functions. The class demoderive contains one private data member. (single inheritance)(46)

 

 /*Program for create class demobase having one private datamember and public member function drive class demo derive*/

#include<conio.h>

#include<iostream.h>

 

class Demobase

{

 int a;

 public:

 

  int b;

  void get_Number()

  {

   cout<<"\nEnter values=";

   cin>>a>>b;

  }

 

  //get value of private data member

 

  int get_a()

  {

   return a;

  }

 

};

                       //-----------------------------------------------------

class demoderive :public Demobase

{

 

 int ans;

 public:

 

  void mul()

  {

   ans=b*get_a();

  }

 

  void display()

  {

   cout<<"a="<<get_a()<< "\n";

   cout<<"b="<<b<<"\n";

   cout<<"Multiplication="<<ans;

  }

};

 

//----------------------------------

 

 void main()

 {

  clrscr();

  demoderive d;

  d.get_Number();

  d.mul();

  d.display();

  getch();

                       }

    OUTPUT

2) W.A.P. to create class demobase it contains contains one private data member, one public data and three public member functions. The class demoderive contains one private data member.(single inheritance private )(47)

  /*Program for create class demobase having one private datamember and public member function drive class demoderive

which privately inherite class demobase*/

                  #include<conio.h>

                   #include<iostream.h>

                    class Demobase

{

 int a;

 public:

                                 int b;

  void get_Number()

  {

   cout<<"\nEnter values=";

   cin>>a>>b;

  }

                      //get value of private data member

                       int get_a()

  {

   return a;

  }

                     };

               //-----------------------------------------------------

class demoderive :private Demobase

{

                         int ans;

 public:

                      void mul()

  {

   get_Number();

   ans=b*get_a();

  }

                      void display()

  {

   cout<<"a="<<get_a()<< "\n";

   cout<<"b="<<b<<"\n";

   cout<<"Multiplication="<<ans;

  }

};

                      //----------------------------------

                      void main()

 {

  clrscr();

  demoderive d;

 // d.get_Number(); we privately inherits class Demobase so d.get_Number() not work

  d.mul();

  d.display();

  getch();

                     }

 

OUTPUT

 

3)W.A.P. to create class student which has roll number  data member and member functions-getnumber(),putnumber().create  derive class test which inherit class student ,it has data member mark1,mark2and member function get_mark(),putmark(), Create Derive class result which inherits class test, having data member total, and member function display which display all details (roll number, marks, total of mark student)[multilevel]l.(48)

/*Program for Multilevel Inheritance*/

#include<iostream.h>

#include<conio.h>

                  //student class

 

class student

{

                          protected :

     int Rollno;

   public:

   void get_Number()

   {

    cout<<"\nEnter Roll Number=";

    cin>>Rollno;

   }

 void put_Number();

                      };

    // function defination outside of the class

 void student::put_Number()

 {

   cout<<"------------------------------\nRoll Number=\t"<<Rollno<<"\n";

 }

//------------------------------------------------------------

 

                    class test:public student

 {

   protected:

       float mark1,mark2;

    public :

 

    //get_mark function

      void get_marks(float x,float y)

      {

       mark1=x;

       mark2=y;

                              }

    //put_mark function

    void put_marks()

    {

     cout<<"Marks obtain= mark1\tmark2";

     cout<<"\n\t\t"<<mark1<<"\t"<<mark2;

    }

 

  };//end of test class

 //--------------------------------------------------------------------

                      class result :public test

  {

                           float total;

    public:

 

     void display()

     {

       total=mark1+mark2;

 

       put_Number();

       put_marks();

                              cout<<"\nTotal score="<<total<<"\n-------------------------------";

     }

                       };

                //-----------------------------------------------------------

     void  main()

    {

     clrscr();

       result r1;

       r1.get_Number();

       r1.get_marks(70.00,88.56);

       r1.display();

       getch();

    }

OUTPUT

 

 

 

5) W.A.P. to create class demobase it contains one protected data member, and getbase1 () public member function. Create another class demobase2 it contains one protected data member, and getbase2 () public member function. The class demoderive inherits from demobase1 and demobase2, and contains one member function display (). (Multiple inheritance)(49)

 

       /*Program for create class demobase1 having one protected datamember and public member function,class demobase2 having one protected datamember and public member function, drive class demo

 derive it inherits class demobase1 and demobase2*/

#include<conio.h>

#include<iostream.h>

 

class Demobase1

{

 protected :

            int a;

 public:

 

 

  void get_Number1()

  {

   cout<<"\nEnter Frist Number=";

   cin>>a;

   }

};

 

//-----------------------------------------------------

class Demobase2

{

 protected :

      int  b;

 public:

            void get_Number2()

            {

             cout<<"\nEnter second number=";

             cin>>b;

            }

 

 };

//----------------------------------------------------

 

class Demoderive :public Demobase1, public Demobase2

{

   public:

 

     void display()

     {

      cout<<"\nNumber1="<<a;

      cout<<"\nNumber2="<<b;

      cout<<"\n Multiplication="<<a*b;

     }

 

};

                  //--------------------------------------------------

 

void main()

{

   clrscr();

 

  Demoderive d;

  d.get_Number1();

  d.get_Number2();

  d.display();

  getch();

}

OUTPUT

 

 

6) W.A.P. to create class student which has roll number  data member and member functions-getnumber(),putnumber().create  derive class test which inherit class student ,it has data member mark1,mark2and member function get_mark(),putmark(),create another class sport having data member score, member function get_score()and put_score().(51)

/*Program for Virtual Base class Inheritance*/

#include<iostream.h>

#include<conio.h>

        //student class

                   class student

{

 

  protected :

     int Rollno;

  public:

   void get_Number()

   {

    cout<<"\nEnter Roll Number=";

    cin>>Rollno;

   }

 void put_Number();

 

};

    // function defination outside of the class

 void student::put_Number()

 {

   cout<<"------------------------------\nRoll Number=\t"<<Rollno<<"\n";

 }

//------------------------------------------------------------

 

                     class test: virtual public student

 {

   protected:

       float mark1,mark2;

    public :

 

    //get_mark function

      void get_marks(float x,float y)

      {

       mark1=x;

       mark2=y;

 

      }

    //put_mark function

    void put_marks()

    {

     cout<<"Marks obtain= mark1\tmark2";

     cout<<"\n\t\t"<<mark1<<"\t"<<mark2;

    }

 

  };//end of test class

 //--------------------------------------------------------------------

 

 class sports :public virtual student

 {

  protected :

    float score;

   public:

 

   void get_score(float s)

   {

    score=s;

 

   }

   //putscore function

 

   void put_score()

   {

    cout<<"\nScore=\t"<<score;

   }

  };

           //----------------------------------------------------------------

 

  class result :public test,public sports

  {

 

     float total;

    public:

 

     void display()

     {

       total=mark1+mark2+score;

 

       put_Number();

       put_marks();

       put_score();

       cout<<"\nTotal score="<<total<<"\n-------------------------------";

     }

 

   };

            //-----------------------------------------------------------

     void  main()

    {

     clrscr();

       result r1;

       r1.get_Number();

       r1.get_marks(70.00,88.56);

       r1.get_score(8.0);

       r1.display();

       getch();

    }

 

      OUTPUT

 

7) Create Derive class result which inherits class test and sport, having data member total, and member function display which display all details (roll number, marks, total of mark student) [hybrid inheritance]. (50)

  /*Program for Hybride Inheritance*/

#include<iostream.h>

#include<conio.h>

 

//student class

 

class student

{

 

  protected :

     int Rollno;

  public:

   void get_Number()

   {

    cout<<"\nEnter Roll Number=";

    cin>>Rollno;

   }

 void put_Number();

 

};

    // function defination outside of the class

 void student::put_Number()

 {

   cout<<"------------------------------\nRoll Number=\t"<<Rollno<<"\n";

 }

//------------------------------------------------------------

 

 

 class test:public student

 {

   protected:

       float mark1,mark2;

    public :

 

    //get_mark function

      void get_marks(float x,float y)

      {

       mark1=x;

       mark2=y;

 

      }

    //put_mark function

    void put_marks()

    {

     cout<<"Marks obtain= mark1\tmark2";

     cout<<"\n\t\t"<<mark1<<"\t"<<mark2;

    }

 

  };//end of test class

 //--------------------------------------------------------------------

                       class sports

 {

  protected :

    float score;

   public:

 

   void get_score(float s)

   {

    score=s;

 

   }

   //putscore function

 

   void put_score()

   {

    cout<<"\nScore=\t"<<score;

   }

  };

 

  //----------------------------------------------------------------

 

  class result :public test,public sports

  {

 

     float total;

    public:

 

     void display()

     {

       total=mark1+mark2+score;

 

       put_Number();

       put_marks();

       put_score();

       cout<<"\nTotal score="<<total<<"\n-------------------------------";

     }

 

   };

 

  //-----------------------------------------------------------

     void  main()

    {

     clrscr();

       result r1;

       r1.get_Number();

       r1.get_marks(70.00,88.56);

       r1.get_score(8.0);

       r1.display();

       getch();

    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Lab 8:

C++ Virtual Function Examples

 


1)      W.A.P. to create class student which has roll number  data member and member functions-getnumber(),putnumber().create  derive class test which inherit class student(virtual base class) ,it has data member mark1,mark2and member function get_mark(),putmark(),create another  derive class sport which inherits class student( virtual base class),and  having data member score, member function get_score()and put_score().

Create Derive class result which inherits class test and sport, having data member total, and member function display which display all details (roll number, marks, total of mark student) [Virtual base class].(51)

 

     /*Program for Virtual Base class Inheritance*/

#include<iostream.h>

#include<conio.h>

//student class

 

class student

{

  protected :

     int Rollno;

  public:

   void get_Number()

   {

    cout<<"\nEnter Roll Number=";

    cin>>Rollno;

   }

 void put_Number();

 

};

    // function defination outside of the class

 void student::put_Number()

 {

   cout<<"------------------------------\nRoll Number=\t"<<Rollno<<"\n";

 }

//------------------------------------------------------------

 

                     class test: virtual public student

 {

   protected:

       float mark1,mark2;

    public :

 

    //get_mark function

      void get_marks(float x,float y)

      {

       mark1=x;

       mark2=y;

 

      }

    //put_mark function

    void put_marks()

    {

     cout<<"Marks obtain= mark1\tmark2";

     cout<<"\n\t\t"<<mark1<<"\t"<<mark2;

    }

 

  };//end of test class

 //--------------------------------------------------------------------

                    class sports :public virtual student

 {

  protected :

    float score;

   public:

 

   void get_score(float s)

   {

    score=s;

 

   }

   //putscore function

 

   void put_score()

   {

    cout<<"\nScore=\t"<<score;

   }

  };

 

  //----------------------------------------------------------------

 

  class result :public test,public sports

  {

                                float total;

    public:

 

     void display()

     {

       total=mark1+mark2+score;

 

       put_Number();

       put_marks();

       put_score();

       cout<<"\nTotal score="<<total<<"\n-------------------------------";

     }

 

   };

                      //-----------------------------------------------------------

     void  main()

    {

     clrscr();

       result r1;

       r1.get_Number();

       r1.get_marks(70.00,88.56);

       r1.get_score(8.0);

       r1.display();

       getch();

    }

 

OUTPUT

 

 

 

 

W.A.P. to create class shape. This class is used to store two double type values that could be used to compute area of figures. Derive two specific classes called triangle and rectangle from shape. Add two base class member function get_data () to initialize data member and another function to display_area () to compute and display area figures. Make display_area() as virtual function and redefine this function in derive classes .

/*program to create class shape is base class,create two derive class which

inherites getdata(),display() functions of shape class*/

 

#include<iostream.h>

#include<conio.h>

                       class shape

{

 double a,b;

 public:

                      void getdata()

  {

   cout<<"\nEnter value of a and b=";

   cin>>a,b;

  }

//============================================

 

virtual void display()

 {

   cout<<"\n value of a="<<a;

   cout<<"\n value of b="<<b;

 

 }

//===================================

 

                    };//end of shape class

 

                     class rectangle :public shape

{

   double arear;

 

   getdata();

 

   void display()

   {

    arear=a*b;

    cout<<"\n area of rectangle="<<arear;

   }

 

                      };

                      class tringle:public shape

{

  double areat;

  getdata();

  void display()

  {

   areat=0.5*a*b;

   cout<<"\narea of Tringle="<<areat;

  }

};

                   //------------------------------------------

void main()

{

clrscr();

 

 

getch();

}

 

 

 

 

 

 

 

 

 

 

 

 

 

Lab 9:

C++ Template Examples

 

 


1)    W.A.P. To create class stack and Templates for class, the class has member function push () and Pop ().(60)

 

/*Program to create function template for min()*/

#include<iostream.h>

#include<conio.h>

 

template<class T>

 

T min(T a,T b)

{

  return (a<b)?a:b;

}

 

void main()

{

 clrscr();

 int i=10,j=20;

 cout<<"minimum value="<<min(i,j);

 float x=8.9,y=4.2;

 cout<<endl<<"minimum value="<<min(x,y); //function cal for float value

 char c='A',ch='Z';

 //function call for float value

 cout<<endl<<"minimum value="<<min(c,ch);

 

 double d=1.23,e=1.34;

 //function call for double value

 cout<<endl<<"minimum value="<<min(d,e);

 getch();

 }

     output

 

    

 

2)    W.A.P. To create function template for min() where we write different data type for function min()(61)

/*Program to create function template for swap()*/

#include<iostream.h>

#include<conio.h>

 

template<class T>

 

T swap(T &a,T &b)

{   T c;

    c=a;

    a=b;

    b=c;

 return 0;

 

}

 

void main()

{

 clrscr();

 int i=10,j=20;

 cout<<"\nSwapping of two integers value=";

 swap(i,j);

 cout<<i<<"\t"<<j;

 float x=8.9,y=4.2;

 cout<<endl<<"\nswapping for two float value=";

 swap(x,y); //function cal for float value

 cout<<x<<"\t"<<y;

 char c='A',ch='Z';

 //function call for float value

 cout<<endl<<"\nswapping for two chracters value=";

 swap(c,ch);

 cout<<c<<"\t"<<ch;

 getch();

 

 }

OUTPUT

 

3)    W.A.P. To create Function templates for swap (), this function perform one swap of contents of two variables.(62)

 

/*Program to create function template for multiple arguments*/

#include<iostream.h>

#include<conio.h>

 

template<class I,class F,class C>

 

void fun(I a,F b,C c)

{

cout<<"Integer value="<<a<<"\nFloat value="<<b<<"\nCharacter value="<<c;

//  return 0;

}

 

void main()

{

 clrscr();

 int i=10;

 float x=8.9;

 char c='A';

 //function call

 fun(i,x,c);

 

 getch();

 }

      OUTPUT

          

 

4)    W.A.P. To create Template class demo which has template function which takes multiple arguments type and display that values.(63)

/*program for create class template for link list*/

#include<iostream.h>

#include<conio.h>

#include<string.h>

 

class employee

{

  private:

 

 char name[20];

 int age;

 float sal;

 

 public:

  //constructor

 

  employee(char *n="",int a=0,float s=0.0)

  {

    strcpy(name,n);

    age=a;

    sal=s;

  }

  friend ostream& operator<<(ostream& s,employee& e);

 

 };//class end

 

 //friend function

 ostream& operator<<(ostream& s,employee& e)

 {

  cout<<e.name<<"\t"<<e.age<<"\t"<<e.sal;

  return s;

 }

 

 //--------------------------------------------------------

 //template for link list

 

 template <class T>

 class linklist

 {

  struct node

  {

   T data;

   node *link;

   }*p;

   public:

   linklist();

   ~linklist();

   void append(T);

   void addbeg(T);

   void del();

   void display();

   int count();

 

 };//class end

 

 //----------------------------------

 template<class T>

 linklist<T>::linklist()

 {

  p=NULL;

 }

 

 template <class T>

 linklist<T> ::~linklist()

 {

  node *t;

  while(p!=NULL)

  {

   t=p;

   p=p->link;

   delete t;

   }

 }

 

 //--------------------------------

 //append()

 

 template <class T>

 void linklist<T>::append(T num)

 {

  node *q,*t;

  if(p==NULL)

  {

   p=new node;

   p->data=num;

   p->link=NULL;

   }

   else

   {

    q=p;

    while(q->link!=NULL)

    q=q->link;

 

    t=new node;

    t->data=num;

    t->link=NULL;

    q->link=t;

 

   }

  }

 

  //------------------------------------------------

 

  //add node at beginning

 

  template<class T>

  void linklist<T>::addbeg(T num)

  {

 

   node *q;

   q=new node;

   q->data=num;

   q->link=p;

   p=q;

  }

 //delete----------------------

 

/* template<class T>

 void linklist<T>::del(int n)

 {

   node *q,*r;

   int i=1;

   q=p;

   if(n==1)

   {

   p=q->link;

   delete q;

   return;

   }

   r=q;

    while(q!=NULL)

     {

       if(i==n)

       {

      r->link=q->link;

      delete q;

      return;

 

       }//end if

       r=q;

       q=q->link;

       i++;

     }

 

     cout<<"\nElement " <<n<<"not found";

     }

 

  */

 

  template <class T>

  void linklist<T>::display()

  {

   node *q;

   cout<<"\n";

   for(q=p;q!=NULL;q=q->link)

    cout<<q->data<<"\t";

    }

 

   //------------------------------

 

   void main()

   {

   clrscr();

    linklist<int>l1;

   // cout<<"\n Number of elementin linklist=<<";

   l1.append(11);

   l1.append(22);

   l1.append(33);

   l1.append(44);

   l1.append(55);

   l1.addbeg(66);

   l1.addbeg(100);

   l1.display();

  // l1.del(100);

   l1.display();

   getch();

   }

OUTPUT

 

5)    W.A.P. that will implement a binary tree as a class template.(68)

 

 

6)    W.A.P. to implement a doubly liked list as a class template.(69)

 

 

 

 

Lab 10:

 

C++ File Handling Examples

 


1)    W.A.P. to create file Item getdata in file (Item type ,cost) and display that data.(81)

/*program to create class inventory getdata() and putdata() functions and write content into file*/

 

#include<iostream.h>

#include<conio.h>

#include<fstream.h>

#include<iomanip.h>

class Inventory

{

char name[10];

int code;

float cost;

public:

 

 void readdata();

 void writedata();

};

void Inventory ::readdata()

{

 cout<<"\nEnter name=";

 cin>>name;

 cout<<"\nEnter code=";

 cin>>code;

 cout<<"\nEnter cost=";

 cin>>cost;

 

}

 

void Inventory::writedata()

{

 cout<<setiosflags(ios::left)

 <<setw(10)<<name

 <<setiosflags(ios::right)

 <<setw(10)<<code

<<setprecision(2)

 <<setw(10)

 <<cost

 <<endl;

}

 

void main()

{

 clrscr();

 Inventory item[3];

 fstream file;

 

 file.open("STOCK.DAT",ios::in|ios::out);

 cout<<"\nEnter detail for Three Item=";

 for(int i=0;i<3;i++)

 {

  item[i].readdata();

  file.write((char *)& item[i],sizeof(item[i]));

 }

 

 file.seekg(0);

 cout<<"\noutput\nItem\t\tCode\tCost\n";

 for(i=0;i<3;i++)

 {

  file.read((char*) &item[i],sizeof(item[i]));

  item[i].writedata();

 }

 file.close();

getch();

}

 

                      

 

2)    W.A.P. To open file in binary mode and then get and put data in file.(79)

 

/*program to open file in binary mode and perform read ,write operation*/

#include<iostream.h>

#include<conio.h>

#include<fstream.h>

#include<iomanip.h>

 

 const char * filename="BINARY";

          void main()

 {

  clrscr();

  float height[4]={175.5,153.0,167.25,160.70};

 

   ofstream outfile;

   outfile.open(filename);

 

 outfile.write((char *) & height,sizeof(height));

 outfile.close();

 

  for(int i=0;i<4;i++)

  height[i]=0;

 

  ifstream infile;

  infile.open(filename);

 

  infile.read((char *) & height,sizeof(height));

 

  for(i=0;i<4;i++)

  {

   cout.setf(ios::showpoint);

   cout<<setw(10)<<setprecision(2)<<height[i];

 

   }

   infile.close();

            getch();

 }

 

 

          OUTPUT

         

 

 

3)    W.A.P to create class demo which has member function getfilename (), in main () function open file, read content of the file and close () file.(65)

 

/create file getfile name from function and read content of the file

#include<iostream.h>

#include<conio.h>

#include<fstream.h>

#include<string.h>

class demo

{

  public:

  char name[100];

  void getfile()

  {

   cout<<"\nEnter file name=";

   cin>>name;

 

  }

};

 

void main()

{

clrscr();

demo d;

char s[100];

d.getfile();

strcpy(s,d.name);

ofstream outfile(s);//create file

outfile<<"Target  computer  Institute";

outfile.close();

const Max=100;

char str[Max];

ifstream infile(s);

 

//open file in write mode another filofstream outfile1("Sample58.txt");

 

while(!infile.eof())

{

 char c[100];

 

 infile.getline(c,100);

  cout<< c;

// outfile1<<c;

}

getch();

}

 

4)    W.A.P. to create class inventory which having data members Item_name, code, cost, write getdata () and putdata () function; write that content into the file.(66)

5)    W.A.P. to create two files called ODD, EVEN using command line arguments, and set of number stored in an array are written to these files. The program then displays contents of the files.(67)

6)    W.A.P.  To create new file (Item), write Item name, and cost into file and display it (read from file). (57)

7)    W.A.P. that reads a text file and creates another file that is identical except that every sequence of consecutive blank spaces is replaced by a single space.(58)

8)    W.A.P. that contain file which having list of telephone numbers in following form

As     32333

Dfdfd 3555

The name contains only one word and the names and telephone numbers are separated by white spaces. Write a program to read file and output list two columns. The name should be left-justified and number right justified.(59)

Lab 11:

 C++ String Manipulation Examples

This page contains example and source code on String Manipulation. To perform different function of string (concat, find, trim, etc.).

 

 

C++ String Manipulation Examples

 


1)    W.A.P. that reads list of countries in random order and displays them in alphabetical order. Use comparison operators and function.(71)

2)    W.A.P. that’s read following text and counts the number of time words “It” appears in it.

It is new. It is singular. It is simple It must succeed! (72)

3)    W.A.P. that will read a line of text containing more than three words and then replace all the blank spaces with an underscore (_).(73)

4)    WAP which show the string related function which is following by :Sting to lower case, String to upper case, String ,trim String ,Count the length of a string(74)

 

5)    W.A.P. using iterator and while () construct to display the contents of string object.(75)

6)    W.A.P. that reads several city names from keyboard and displays only those names beginning with characters “B” or “C”.(76)

 

 

 

 

 

 

 

Post a Comment

0 Comments

Popular Posts

Visual Basic 6.0 Program
Node js practical