Monday, November 13, 2017

Add/Sum two numbers using pointers in C/C++ Language

1 comments

Problem

Take two integer inputs from user. Create Sum function which should receive two integers using pointers. Calculate the sum and display the result in main function.

Code

#include "stdafx.h"
#include <iostream>
#include<conio.h>
using namespace std;


int sum (int *, int *);

int main()
{
int a,b,c;

cout << "Enter 1st number: ";
cin >> a;
cout<<"enter 2nd number: ";
cin >> b;

c = sum (&a,&b);

cout << "Sum = "<< c << endl;

cout<<"Press any key to close.";

getch();

return 0;
}

int sum (int *a, int *b)
{
int c;
c = (*a + *b);
return c;
}

Output

Add/Sum two numbers using pointers in C/C++ Language
Add/Sum two numbers using pointers in C/C++ Language

Read More..

Saturday, November 4, 2017

Calculate Square of 3 input integers using function and pointers

0 comments

Problem

Write a program to calculate square of an integer, input by the user. Declare a function with the name of square and should receive 3 integers. The function should then calculate the square of these three integers and return the square. Display the result.

Code

#include "stdafx.h"
#include <iostream>
#include<conio.h>
using namespace std;

void square (int *, int *, int *);

int main()
{
int a,b,c;

cout << "Enter 1st number: ";
cin >> a;

cout << "Enter 2nd number: ";
cin >> b;

cout << "Enter 3rd number: ";
cin >> c;

square (&a, &b, &c);

cout << "Square of Ist number = "<< a;
cout << "\nSquare of 2nd number = "<< b;
cout << "\nSquare of 3rd number = "<< c << endl ;


cout<<"Press any key to close.";

getch();

return 0;
}

void square (int *a, int *b, int *c)
{
*a = (*a * *a);
*b = (*b * *b);
*c = (*c * *c);
}

Output

Calculate Square of 3 input integers using function and pointers
Calculate Square of 3 input integers using function and pointers

Read More..

Sunday, October 15, 2017

Display Add/Sum of two integers in C Language

0 comments

Problem

Write a program in C language which takes two integers as input from user. Write a function to add these two integers and store the sum in another integer. Display the result.

Code

// lab02..cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include<conio.h>
using namespace std;


int sum (int, int);

int main()
{
int a,b,c;

cout << "Enter 1st number: ";
cin >> a;
cout<<"enter 2nd number: ";
cin >> b;

c = sum (a,b);

cout << "Sum = "<< c << endl;

cout<<"Press any key to close.";

getch();

return 0;
}

int sum (int a, int b)
{
int c;
c = a+b;
return c;
}

Output

Display Add/Sum of two integers in C Language
Display Add/Sum of two integers in C Language

Read More..

Saturday, October 7, 2017

Date Sum Using Structure in C/C++ Language

0 comments

Problem

Create a struct called data. User should be able to input day, month, and year. Take two date inputs and add them. Display the result.

Code

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

//struct decleration
struct data {
int years;
int months;
int days;
}d1,d2;

//function protorypes
void add_data();
void add_dates();
void display(int ,int ,int);

int main()
{
    //function calls
    add_data();
    add_dates();
   
printf ("\n\nPress any key to exit.");
getch();
return 0;
}

//adding record
void add_data()
{
     //1st date
     printf ("Enter 1st date.");
   
     printf ("\n\nEnter year: ");
     scanf ("%d",&d1.years);
   
     printf ("\nEnter month: ");
     scanf ("%d",&d1.months);
   
     printf ("\nEnter day: ");
     scanf ("%d",&d1.days);
   
     display(d1.days,d1.months,d1.years);
     //printf ("\n\nThe 1st date is %d/%d/%d",d1.days,d1.months,d1.years);
   
     //Second time
     printf ("\n\n\nNow, please type the 2nd date.");
   
     printf ("\nEnter year: ");
     scanf ("%d",&d2.years);
   
     printf ("\nEnter month: ");
     scanf ("%d",&d2.months);
   
     printf ("\nEnter day: ");
     scanf ("%d",&d2.days);
   
     display(d2.days,d2.months,d2.years);
}

void display (int a,int b,int c)
{
     printf("\nThe date is %d/%d/%d \n\n", a,b,c);
}   

void add_dates()
{
     int y,m,d;
   
     y = d1.years + d2.years;
     m = d1.months + d2.months;
     d = d1.days + d2.days;
   
     printf ("\n\n\nSum of the date's is %d/%d/%d",d,m,y);
}

Output

Date Sum Using Structure in C/C++ Language
Date Sum Using Structure in C/C++ Language

Read More..

Sunday, October 1, 2017

Time Sum Using Structure in C/C++ Language

1 comments

Problem

Create a structure called time. Its three members, all type int, should be called hours, minutes, and seconds. Write a program that prompts the user to enter a time value in hours, minutes, and seconds. This can be in 12:59:59 format, or each number can be entered at a separate prompt (“Enter hours:”, and so forth). The program should then store the time in a variable of type struct time, and finally print out the total number of seconds represented by this time value:
long totalsecs = t1.hours*3600 + t1.minutes*60 + t1.seconds

Code

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

struct time {
int hours;
int minutes;
int seconds;
};

//function prototype
void add (int,int,int,int,int,int);

int main()
{
    struct time t1,t2;
   
    //1st time
    printf ("Enter 1st time.");
   
printf ("\n\nEnter Hours: ");
scanf ("%d",&t1.hours);

printf ("\nEnter Minutes: ");
scanf ("%d",&t1.minutes);

printf ("\nEnter Seconds: ");
scanf ("%d",&t1.seconds);

    printf ("\n\nThe Time is %d:%d:%d",t1.hours,t1.minutes,t1.seconds);
   
    //Second time
    printf ("\n\n\nNow, please type the 2nd time.");
   
    printf ("\n\nEnter Hours: ");
scanf ("%d",&t2.hours);

printf ("\nEnter Minutes: ");
scanf ("%d",&t2.minutes);

printf ("\nEnter Seconds: ");
scanf ("%d",&t2.seconds);

    printf ("\n\nThe Time is %d:%d:%d",t2.hours,t2.minutes,t2.seconds);
   
    //function call
    add (t1.hours,t1.minutes,t1.seconds,t2.hours,t2.minutes,t2.seconds);
   
printf ("\n\nPress any key to exit.");
getch();
return 0;
}

//function definition
void add (int x,int y,int z,int a,int b,int c)
{
     int h,m,s;
   
     h = x + a;
     m = y + b;
     s = z + c;
   
     printf ("\n\n\nSum of the two time's is %d:%d:%d",h,m,s);
}

Code

Time Sum Using Structure in C/C++ Language
Time Sum Using Structure in C/C++ Language

Read More..

Sunday, September 24, 2017

Input Length and Breadth. Calculate Area and Perimeter Using Struct in C Language

0 comments

Problem:

Write a program which takes length and breadth as input. Than calculate area and perimeter of the room.

Code

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

struct distance{
int length;
int width;
};
struct room{
struct distance a;
}r;

void myftn();

int main()
{
myftn();


printf ("\n\nPress any key to exit.");
getch();
return 0;
}

void myftn ()
{
int p,s;

printf ("Enter lengtgh: ");
scanf ("%d",&r.a.length);
printf ("Enter widtgh: ");
scanf ("%d",&r.a.width);

p = 2 * (r.a.length * r.a.width);
s = (r.a.length * r.a.width);

printf ("\n\nArea = %d",s);
printf ("\nPerimeter = %d",p);
}

Output

Input Length and Breadth. Calculate Area and Perimeter Using Struct in C Language
Input Length and Breadth. Calculate Area and Perimeter Using Struct in C Language



Read More..

Sunday, September 17, 2017

Convert Fahrenheit to Celsius | Convert Celsius to Fahrenheit

0 comments

Problem

Write two functions in a program of C language to convert:

  • Function 1: Fahrenheit to Celsius
  • Function 2: Celsius to Fahrenheit

Code


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

void ftoc();
void ctof();

int main()
{
ftoc();
        ctof();
    
printf ("\n\nPress any key to exit.");
getch();
return 0;
}

void ftoc()
{
float f,c;
printf ("Enter temperature in Fahrenheit: ");
scanf ("%f",&f);

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

printf ("Temperature in celsius: %f",c);
}

void ctof()
{
float f,c;
printf ("\n\nEnter temperature in celsius: ");
scanf ("%f",&c);

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

printf (" Temperature in celsius: %f",f);
}

Output

Convert Fahrenheit to Celsius | Convert Celsius to Fahrenheit
Convert Fahrenheit to Celsius | Convert Celsius to Fahrenheit

Read More..

Thursday, April 27, 2017

File Handling: Reading and Writing into a text file using class

0 comments

Code

#include<iostream>
#include<fstream>
#include<string>
#include<conio.h>
using namespace std;

class marks
{
      private:
              int oop;
              int cal;
              int dis;
              int s;
              int a;
             
      public:
             marks():oop(0),cal(0),dis(0)
               {    }
           
             void getdata()
             {
                  cout<<"Enter marks of oop: ";
                  cin>>oop;
                  cout<<"Enter marks of cal: ";
                  cin>>cal;
                  cout<<"Enter marks of dis: ";
                  cin>>dis;
             }
           
             void display()
             {
                  cout<<"OOP = "<<oop<<endl;
                  cout<<"Cal = "<<cal<<endl;
                  cout<<"Dis = "<<dis<<endl;
             }
};

int main ()
{
    marks m;
    int s;
   
    m.getdata();
                                                        //opening the file in binary mode
    ofstream myfile("Writing_Reading_class.txt",ios::binary);        
                                                     
                                                       //writing in the file
    myfile.write(reinterpret_cast<char *>(&m),sizeof(m));
                 //closing the file
    myfile.close();
                                                      //re-opening the file in binary mode
    ifstream my("Writing_Reading.txt",ios::binary);
                                                      //Reading from the file
    my.read(reinterpret_cast<char *>(&m),sizeof(m));
             //display
    m.display();
   
    cout << "\n\nPress any key to close.";
    getch ();
    return 0;
}

Output


Read More..

Friday, April 14, 2017

File Handling: Reading and Writing into a binary text file

0 comments

Code:

#include<iostream>
#include<fstream>
#include<string>
#include<conio.h>
using namespace std;

int main()
{
    int max = 10;
    int a[max];
 
    ofstream myfile("Writing_Reading.txt",ios::binary);        //opening the file in binary mode
 
    for(int j=0;j<max;j++)                                     //assigning values(array)
            a[j] = (j + 1);
         
                                                       //writing in the file
    myfile.write(reinterpret_cast<char *>(a),sizeof(a));
    cout<<"File written."<<endl<<endl;
 
    myfile.close();                                   //closing the file
 
    ifstream my("Writing_Reading.txt",ios::binary);        //opening the file in binary mode
 
                                                      //Emptying the array
    for(int j=0;j<max;j++)
            a[j] = 0;
                                                      //Reading from the file
    my.read(reinterpret_cast<char *>(a),sizeof(a));
 
    for(int j=0;j<max;j++)                             //display array
            cout<<a[j];
 
    cout<<endl<<"Press any key to exit.";
    getch();
    return 0;
}

Output:

File Handling: Writing into a binary text file

Read More..

Friday, March 10, 2017

find index number of the largest element using class

0 comments

Problem

Start with a program that allows the user to input a number of integers, and then stores them in an int array. Write a function called maxint() that goes through the array, element by element, looking for the largest one. The function should take as arguments the address of the array and the number of elements in it, and return the index number of the largest element. The program should call this function and then display the largest element and its index number.

Code

// p[4].cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string.h>
using namespace std;

class intgrs
{
private:
int a[5];
int i,j,z;

public:
intgrs():j(0),i(0),z(0)
{ }

void maxint()
{
cout<<"Enter Integers: ";
for(i=0; i<5; i++)
{
cin>>a[i];
}
for(i=0;i<5;i++)
{
if(a[i]>j)
{
j = a[i];
z=i;
}
}
cout<<"\n\nLargest Element = "<<j;
cout<<"\n\nIndex Number = "<<(z+1)<<endl;
}
};

int main()
{
intgrs i;

i.maxint();

cout<<"\n\nPress any key to close.";
getch();
return 0;
}

Output

find index number of the largest element using class

Read More..

Thursday, March 9, 2017

Input and display employee data of 100 employees using array of objects

1 comments

Problem

Create a class called employee that contains a name (an object of class string) and an employee number (type long). Include a member function called getdata() to get data from the user for insertion into the object, and another function called putdata() to display the data. Assume the name has no embedded blanks.
Write a main() program to exercise this class. It should create an array of type employee, and then invite the user to input data for up to 100 employees. Finally, it should print out the data for all the employees.

Code

#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string.h>
using namespace std;

class employee
{
private:
char name[50];
long no;

public:
employee():no(0)
{ }

void getdata()
{
fflush(stdin);
cout<<"\nEnter Employee Data:\n";
cout<<"Enter Name: ";
cin.get(name,50);
fflush(stdin);
cout<<"Enter Number: ";
cin>>no;
fflush(stdin);
}

void putdata()
{
cout<<"\n\nName= "<<name<<"\nE.number = "<<no<<endl;
}

};

int main()
{
int array_length = 3;
employee e1[array_length];

for(int i=0;i<array_length;i++){
e1[i].getdata();
fflush(stdin);
}

for(int i=0;i<array_length;i++){
e1[i].putdata();
}

cout<<"\n\nPress any key to close.";
getch();
return 0;
}

Output


Input and display employee data of 100 employees using array of objects
Read More..

Saturday, October 22, 2016

Reverse input string in c++

0 comments

Problem

Take a string input from user and reverse it using C++ language.

Code

// P[1].cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<conio.h>
#include<iostream>
#include<string.h>
using namespace std;

class rvrstr
{
private:
char str1[80];
char str2[80];
int i,j,n;
char ch;

public:
rvrstr(): i(0),j(0),n(0)
{ }

void setstr()
{
cout<<"Enter string: ";
cin.get(str1,80);
}

void reversit()
{
n = strlen(str1);
cout<<"\n\nReversed String: ";
for(i=n;i>=0;i--)
{
str2[j] = str1[i];
cout<<str2[j];
j++;
}
}
};

int main()
{
rvrstr r1;

r1.setstr();
r1.reversit();

cout<<"\n\nPress any key to close.";
getch();
return 0;
}

Output

Reverse input string in c++

Read More..

Thursday, October 20, 2016

Electronic Polling System in C++ Language

1 comments

Problem

Implement (a part of) electronic Pakistani election Scenario where following political parties are participating in election: PPP, PML and PTI.  Create a class PollingStation where it stores the vote’s count, against each party, cast by the Pakistani legal registered voters.  Your program must query the voter for its ID card number before he/she cast the vote and check it against voter list. (Suppose voter list is already with you). If voter is not found in the voter’s list, your program throws the exception IllegalVoter() and discard that voter. The Application again starts working in normal state and terminates only when user wants to quit it. At the end of the day (or whenever user wants) it generates report about the vote count against each party including header that contains date, day and location.

Code

// Poling station.cpp : Defines the entry point for the console application.
//
                      //HEADER FILES
#include "stdafx.h"   //ESSENTIAL TO WORK ON VISUAL STUDIO
#include<fstream>     //FOR FILE
#include<conio.h>     //FOR GETCH FUNCTION
#include<string>      //fOR STRINGS USAGE
#include<iostream>    //FOR COUT AND CIN
using namespace std;
                      //CLASS BEGINS
class PollingStation
{
private:            //VARIABLES DECLARED PRIVATLY, ONLY ACCESSABLE IN THIS CLASS
int votes_count_ppp;
int votes_count_pml;
int votes_count_pti;
int total_votes,hr,mn,sc,flag,choice,offset;
string line,day,location;

public:    //EXCEPTION CLASS
class IllegalVoter
{     };
     //CONSTRUCTOR OF POLLING STATION CLASS
    PollingStation(): votes_count_ppp(0), votes_count_pml(0), votes_count_pti(0),total_votes(0),
                 hr(0),mn(0),sc(0),flag(0),line(""),choice(0)
{ }
          //DESTRUCTOR OF POLLING STATION CLASS
~PollingStation()
{
cout<<"polling Station Destructor";
}
          //GETING THE DATA FROM USER(DAY,DTAE & LOCATION)
void start()
    {                  //GET DAY
         system("cls");
         cout<<"Enter Day: ";
         cin>>day;
                      //GET LOCATION
         system("cls");
         cout<<"\nEnter Location: ";
         cin>>location;
                       //GET TIME
         system("cls");
         cout<<"\nEnter time: "<<endl;
         cout<<"Enter Hour: ";
         cin>>hr;
         cout<<"Enter Minutes: ";
         cin>>mn;
    }
          //CHECKING WHETHER THE PERSON IS ILLEGIBEL FOR VOTE
    void checkdata(string search)
    {
         ifstream Myfile;    //OPENING THE FILE FOR READING
         Myfile.open ("VOTERS_LIST.txt");
         {
         if(Myfile.is_open())
         {                   //READING UNTIL END OF FILE
             while(!Myfile.eof())
             {
                 getline(Myfile,line);       //CHECKIMG
                 if ((offset = line.find(search)) != string::npos)
                 {
                      flag = 1;
                 }
             }
             Myfile.close();
         }   //IF FILE IS NOT OPENED
         else
             cout<<"Unable to open this file."<<endl;
         }
         if(flag == 0)     //THROWING EXCEPTION
                 throw IllegalVoter();
    }
          //PERSON WILL CAST HIS/HER VOTE
void cast_vote()
{
         system("cls");
         cout<<"CAST YOUR VOTE:"<<endl;
         cout<<"1. PPP"<<endl;
         cout<<"2. PML"<<endl;
         cout<<"3. PTI"<<endl;
             
         cout<<"\nEnter Your Choice: ";
         cin>>choice;
                     //IF USER HAS VOTED FOR PPP
         if(choice == 1)
         {
              votes_count_ppp++;
              total_votes++;
         }           //IF USER HAS VOTED FOR PML
         else if(choice == 2)
         {
              votes_count_pml++;
              total_votes++;
         }           //IF USER HAS VOTED FOR PTI
         else if (choice == 3)
         {
              votes_count_pti++;
              total_votes++;
         }          //IF USER HAS ENTERED WRONG CHOICE
         else
         {
             system("cls");
             cout<<"Invalid Key."<<endl;
             cout<<"Press Any Key To Continue."<<endl;
             getch();
         }
}
     //DISPLYING RESULTS
void display()
{
         system("cls");
         cout<<"\n\n********************************************************************************";
         cout<<"Time = "<<hr<<" : "<<mn<<"\t\t\tDay = "<<day<<"\t\tLocation = "<<location<<endl;
         cout<<"\n********************************************************************************";
       
         cout<<"Total number of votes voted for:"<<endl<<endl;
         cout<<"\tPPP = "<<votes_count_ppp<<endl;
         cout<<"\tPML = "<<votes_count_pml<<endl;
         cout<<"\tPTI = "<<votes_count_pti<<endl<<endl;
         cout<<"\tTotal = "<<total_votes<<endl;
     }
};

int main()
{
PollingStation p;   //OBJECT OF POLLING STATION CLASS
    char another;       //VARIABLES
    string id;        
   
    p.start();          //CALLING THE FUNTION TO GET DATA
                       
    do{                 //LOOP UNTIL USER WANTS
        try{
              system("cls");   //USER WILL ENTER HIS/HER ID CARD NUMBER
              cout<<"Enter ID Card Number: ";
     cin>>id;
     p.checkdata(id);     //CHECKING
     p.cast_vote();       //CASTING VOTE(IF ILLEGIBLE)
           }
        catch(PollingStation::IllegalVoter)  //IF NOT ILLEGIBLE THEN
          {
              cout<<"NO ENTRY WITH THIS ID"<<endl;
              cout<<"Press any key to continue...";
              getch();
          }
         
        system("cls");         //ASKING USER WHETHER HE/SHE WANTS TO ENTER DATA
        cout<<"Enter another phone number(y/n)? ";
        another = getch();
      }while(another == 'Y' || another == 'y'); //LOOP TERMINATION CONDITION
   
   
    ofstream file;   //OPENING FILE FOR WRITTING
    file.open("POLLING_RESULTS.DAT", ios::binary);
    p.display();     //DISPLYING THE DATA & WRITTING TO THE FILE
    file.write(reinterpret_cast<char*>(&p),sizeof(p));  //SO THAT IT COULD BE DSPLAYED ANYTIME
    file.close();                                       //USER WANTS & THEN CLOSING THE FILE
   
    cout<<"\nFile Written"<<endl;
    cout<<"Press any key to exit"<<endl;
getch();
return 0;
}

Output

electronic polling system in c++ language

Read More..

Wednesday, October 19, 2016

Polymorphism example in c++ language

0 comments

Problem

Implement the following given scenario, include two  constructors (no argument, with arguments), two functions getvalue(), and  displayvalue() for all classes.
polymorphism program in c++

Code

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;

class Vehicle
{
      protected:
                int i;
                string s;
     
      public:
             Vehicle(): i(0), s("")
             {         }
             Vehicle(int a,string ss): i(a), s(ss)
             {           }
             void getdata()
             {
                  cout<<"Enter Vehicle Number: ";
                  cin>>i;
                  fflush(stdin);
                  cout<<"Enter vehicle name: ";
                  getline(cin, s);
             }
           
             void display()
             {
                  cout<<"Vehicle Number: "<<i;
                  cout<<"Vehicle Name: "<<s;
             }
};

class land_Vehicle : public Vehicle
{
      protected:
                int b;
                string s1;
     
      public:
             land_Vehicle(): b(0), s1("")
             {         }
             land_Vehicle(int a,string ss, int r, string s0): b(a), s1(ss), Vehicle(r,s0)
             {           }
             void getdata()
             {
                  Vehicle :: getdata();
                  cout<<"Enter Land Vehicle Number: ";
                  cin>>b;
                  fflush(stdin);
                  cout<<"Enter Land vehicle name: ";
                  getline(cin, s1);
             }
           
             void display()
             {
                  Vehicle :: display();
                  cout<<"Vehicle Number: "<<b;
                  cout<<"Vehicle Name: "<<s1;
             }
};

class Boat : public Vehicle
{
      protected:
                int c;
                string s2;
     
      public:
             Boat(): c(0), s2("")
             {         }
             Boat(int a,string ss, int r, string s0): c(a), s2(ss), Vehicle(r,s0)
             {           }
             void getdata()
             {
                  Vehicle :: getdata();
                  cout<<"Enter Boat Number: ";
                  cin>>c;
                  fflush(stdin);
                  cout<<"Enter Boat name: ";
                  getline(cin, s2);
             }
           
             void display()
             {
                  Vehicle :: display();
                  cout<<"Vehicle Number: "<<c;
                  cout<<"Vehicle Name: "<<s2;
             }
};

class aircraft : public Vehicle
{
      protected:
                int d;
                string s3;
     
      public:
             aircraft(): d(0), s3("")
             {         }
             aircraft(int a,string ss, int r, string s0): d(a), s3(ss), Vehicle(r,s0)
             {           }
             void getdata()
             {
                  Vehicle :: getdata();
                  cout<<"Enter Aircraft Number: ";
                  cin>>d;
                  fflush(stdin);
                  cout<<"Enter Aircarft name: ";
                  getline(cin, s3);
             }
           
             void display()
             {
                  Vehicle :: display();
                  cout<<"Vehicle Number: "<<d;
                  cout<<"Vehicle Name: "<<s3;
             }
};

class car : public land_Vehicle
{
      protected:
                int e;
                string s4;
     
      public:
             car(): e(0), s4("")
             {         }
             car(int a,string ss, int q1, string q2,int q3,string q4): e(a), s4(ss),land_Vehicle(q1,q2,q3,q4)
             {
             }
             void getdata()
             {
                  land_Vehicle :: getdata();
                  cout<<"Enter car Number: ";
                  cin>>e;
                  fflush(stdin);
                  cout<<"Enter car name: ";
                  getline(cin, s4);
             }
           
             void display()
             {
                  land_Vehicle :: display();
                  cout<<"Vehicle Number: "<<e;
                  cout<<"Vehicle Name: "<<s4;
             }
};

class truck  : public land_Vehicle
{
      protected:
                int f;
                string s5;
     
      public:
             truck(): f(0), s5("")
             {         }
             truck(int a,string ss, int q, string qq,int q3,string q4): f(a), s5(ss),land_Vehicle(q,qq,q3,q4)
             {           }
             void getdata()
             {
                  land_Vehicle :: getdata();
                  cout<<"Enter truck Number: ";
                  cin>>f;
                  fflush(stdin);
                  cout<<"Enter truck name: ";
                  getline(cin, s5);
             }
           
             void display()
             {
                  land_Vehicle :: display();
                  cout<<"Vehicle Number: "<<f;
                  cout<<"Vehicle Name: "<<s5;
             }
};

class sports_car  : public car
{
      protected:
                int g;
                string s6;
     
      public:
             sports_car(): g(0), s6("")
             {         }
           
             sports_car(int a,string ss, int q, string qq,int q3,string q4,int q5,string q6): g(a), s6(ss),car(q,qq,q3,q4,q5,q6)
             {           }
             void getdata()
             {
                  car:: getdata();
                  cout<<"Enter sports car Number: ";
                  cin>>g;
                  fflush(stdin);
                  cout<<"Enter sports car name: ";
                  getline(cin, s6);
             }
           
             void display()
             {
                  car:: display();
                  cout<<"Vehicle Number: "<<g;
                  cout<<"Vehicle Name: "<<s6;
             }
};

class yacht  : public Boat
{
      protected:
                int h;
                string s7;
     
      public:
             yacht(): h(0), s7("")
             {         }
             yacht(int a,string ss, int q, string qq,int q3,string q4): h(a), s7(ss),Boat(q,qq,q3,q4)
             {           }
             void getdata()
             {
                  Boat::getdata();
                  cout<<"Enter yacht Number: ";
                  cin>>h;
                  fflush(stdin);
                  cout<<"Enter yacht name: ";
                  getline(cin, s7);
             }
           
             void display()
             {
                  Boat :: display();
                  cout<<"Vehicle Number: "<<h;
                  cout<<"Vehicle Name: "<<s7;
             }
};

class sail_boat  : public Boat
{
      protected:
                int k;
                string s8;
     
      public:
             sail_boat(): k(0), s8("")
             {         }
             sail_boat(int a,string ss, int q, string qq,int q3,string q4): k(a), s8(ss),Boat(q,qq,q3,q4)
             {           }
             void getdata()
             {
                  Boat :: getdata();
                  cout<<"Enter sail_boat Number: ";
                  cin>>k;
                  fflush(stdin);
                  cout<<"Enter sail_boat name: ";
                  getline(cin, s8);
             }
           
             void display()
             {
                  Boat :: display();
                  cout<<"Vehicle Number: "<<k;
                  cout<<"Vehicle Name: "<<s8;
             }
};

class f16 : public aircraft
{
       protected:
                int j;
                string s9;
     
      public:
             f16(): j(0), s9("")
             {         }
             f16(int a,string ss, int q, string qq,int q3,string q4): j(a), s9(ss), aircraft(q,qq,q3,q4)
             {           }
             void getdata()
             {
                  aircraft :: getdata();
                  cout<<"Enter f16 Number: ";
                  cin>>j;fflush(stdin);
                  cout<<"Enter f16 model: ";
                  getline(cin, s9);
             }
           
             void display()
             {
                  aircraft :: display();
                  cout<<"f16 Number: "<<j;
                  cout<<"f16 model: "<<s9;
             }
};

class helicopter  : public aircraft
{
      protected:
                int l;
                string s10;
     
      public:
             helicopter(): l(0), s10("")
             {         }
             helicopter(int a,string ss, int q, string qq,int q3,string q4): l(a), s10(ss),aircraft(q,qq,q3,q4)
             {           }
             void getdata()
             {
                  aircraft :: getdata();
                  cout<<"Enter helicopter Number: ";
                  cin>>l;
                  cout<<"Enter helicopter model: ";
                  getline(cin, s10);
             }
           
             void display()
             {
                  aircraft :: display();
                  cout<<"helicopter Number: "<<l;
                  cout<<"helicopter model: "<<s10;
             }
};

int main()
{
    aircraft a;
    a.getdata();
    a.display();
   
    Boat b;
    b.getdata();
    b.display();
   
    land_Vehicle l;
    l.getdata();
    l.display();
   
    car c;
    c.getdata();
    c.display();
   
    truck t;
    t.getdata();
    t.display();
   
    sports_car sp;
    sp.getdata();
    sp.display();
   
    yacht y;
    y.getdata();
    y.display();
   
    sail_boat s;
    s.getdata();
    s.display();
   
    f16 f;
    f.getdata();
    f.display();
   
    helicopter h;
    h.getdata();
    h.display();
   
    cout<<"Press any key exit.";
    getch();
    return 0;
}

Output

polymorphism program in c++

Read More..

Thursday, October 13, 2016

CD player simulator using c++

0 comments

Problem

Design a simple CD player simulator. The CD player has the following buttons: "POWER", "EJECT", "PLAY" and "STOP", and a tray where a CD is loaded. User can load a CD only if the tray is open. The tray can be opened only if the power is turned on (regard it as something like a motor-driven tray installed on a PC). If the power is turned off with the tray open, the tray will keep open and the power is turned off.
Implement the following actions of the CD player as methods of class CDPlayer.
  • pushPower() -- simulates pushing POWER(on/off) button.
    • if the power is turned off, turn on the power, and display "Power turned on."
    • if the power is turned on,
      • if playing, stop it.
turn off the power, and display "Power turned off."
  • pushEject() -- simulates pushing EJECT(tray open/close) button
    • if the power is not turned on, display "Power not turned on."
    • if the power is turned on,
      • if the tray is not open, open the tray and display "Tray opened."
      • if the tray is open, close the tray and display "Tray closed."
  • pushPlay() -- simulates pushing PLAY button
    • if the power is turned on,
      • if the media is loaded and tray is closed, begin to play and display "Now playing..."
      • otherwise, display "No CD loaded or tray is open."
  • pushStop() -- simulates pushing STOP button
    • if the power is turned on,
      • if it's playing, stop playing and display "Playing stopped."
  • loadUnloadMedia() -- simulates loading/unloading media to/from the tray (tray must be open when loading/unloading)
    • if the tray is open,
      • if the media is loaded, unload the media and display "Media unloaded."
      • if the media is not loaded, load the media and display "Media loaded."
    • if the tray is not open,
      • display "Tray is not open."

Code

#include<iostream>
#include<conio.h>
using namespace std;


class CDplayer
{
      private:
              int power;
              int eject;
              int tray;
              int media;
              int play;
              
      public:
      CDplayer():power(0),eject(0),tray(0),media(0),play(0)
      {
      }
      
      void pushPower()
      {
           cout<<"\n\nNOTE: Press one(1) to turn on and zero(0) to turn off.";
           cout<<"\nWant to turn on the power? ";
           cin>>power;
           
           if(power == 1)
                cout<<"Power is ON.";
           else if (power == 0)
                cout<<"Power is OFF.";
           else
               cout<<"Invalid key";
           
           cout<<"\n\nPress any key to continue.";
           getch();
      }
      
      void pushEject()
      {
           if(power == 1)
           {
                if(tray == 0)
                {
                         tray = 1;
                         cout<<"Tray opened.";
                }
                else if(tray == 1)
                {
                     tray = 0;
                     cout<<"Tray closed.";
                }
           }
           else if(power == 0)
                cout<<"Power not turned on.";
           
           cout<<"\n\nPress any key to continue.";
           getch();
      }
      
      void pushPlay() 
      {
           if(power == 1)
           {
                if(media == 1 && tray == 0)
                {
                    play = 1;
                    cout<<"Now playing...";
                }
                else
                    cout<<"No CD loaded or tray is open.";
           }
           else if(power == 0)
                cout<<"Power not turned on.";
                
           cout<<"\n\nPress any key to continue.";
           getch();
      }
      
      void pushStop() 
      {
           if(power == 1)
           {
                if(play == 1)
                {
                        play = 0;
                        cout<<"Playing stopped.";
                }
           }
           cout<<"\n\nPress any key to continue.";
           getch();
      }
      
      void loadUnloadMedia()
      {
           if(tray == 1)
           {
                   if(media == 1)
                   {
                            media = 0;
                            cout<<"Media unloaded.";
                   }
                   else if(media == 0)
                   {
                        media = 1;
                        cout<<"Media loaded.";
                   }
           }
           else if(tray == 0)
                cout<<"Tray is not open.";
           
           cout<<"\n\nPress any key to continue.";
           getch();
      }
};

int main()
{
    CDplayer c1;
    int s;
    while(1)
    {
            system ("cls");
            cout<<"\n\nPlease, Press one of the following buttons: ";
            cout<<"\n1. POWER(on/off)";
            cout<<"\n2. EJECT(tray open/close)";
            cout<<"\n3. PLAY";
            cout<<"\n4. STOP";
            cout<<"\n5. Load/Unload media to/from the tray(tray will be opened)";
            cout<<"\n6. Close CDplayer";
            
            cout<<"\n\nEnter your choice: ";
            cin>>s;
            
            switch(s)
            {
                     case 1:
                          system ("cls");
                          c1.pushPower();
                          break;
            
                     case 2:
                          system ("cls");
                          c1.pushEject();
                          break;
            
                     case 3:
                          system ("cls");
                          c1.pushPlay();
                          break;
            
                     case 4:
                          system ("cls");
                          c1.pushStop();
                          break;
            
                     case 5:
                          system ("cls");
                          c1.loadUnloadMedia();
                          break;
            
                     case 6:
                          exit(0);
            }
    }
    
    getch();
    return 0;
}

Output

CD player simulator using c++
CD player simulator using c++

Read More..

Copyright 2017. All Rights Reserved. Privacy Policy / Terms And Conditions / Sitemap / Contact