C++ Programming
CLASS AND OBJECT
Question 1 Define a class student with the following specification
Private members of class student admno integer sname 20 character eng. math, science float total float ctotal() a function to calculate eng + math + science with float return type.
Public member function of class student Takedata() Function to accept values for admno, sname, eng, scienceand invoke ctotal() to calculate total. Showdata() Function to display all the data members on the screen.
Code:
#include<iostream>
using namespace std;
class student
{
private:
int admno;
char sname[20];
float eng,math,science;
float total;
float ctotal()
{
return eng+math+science;
}
public:
void Takedata()
{
cout<<"Enter admission number :"<<endl;
cin>> admno;
cout<<"Enter student name :"<<endl ;
gets(sname);
cout<< "Enter marks in english, math, science: "<<endl;
cin>>eng>>math>>science;
total=ctotal();
}
void Showdata()
{
cout<<"Admission number "<<admno<<"\nStudent name "<<sname<<"\nEnglish "
<<eng<<"\nMath "<<math<<"\nScience "<<science<<"\nTotal "<<total;
}
};
int main ()
{ student obj ;
obj.Takedata();
obj.Showdata();
return 0;
}
Question 2 Define a class batsman with the following specifications: Private members: bcode 4 digits code number bname 20 characters innings, notout, runs integer type batavg it is calculated according to the formula batavg =runs/(innings-notout) calcavg() Function to compute batavg Public members: readdata() Function to accept value from bcode, name, innings, notout and invoke the function calcavg() displaydata() Function to display the data members on the screen.
Code:
#include<iostream>
using namespace std;
class Batsman {
private:
int bcode;
char bname[20];
int innings, notout, runs;
int batavg;
void calcavg() {
if(innings!=notout)
batavg = runs/(innings-notout);
batavg=0;
}
public :
void readdata();
void displaydata();
};
void Batsman::readdata () {
cout<<"Enter Batsman code: ";
cin>> bcode;
cout<<"Enter Batsman name: ";
cin.ignore();
cin.getline(bname, 20);
cout<<"Enter innings: ";
cin >> innings;
cout<<"Enter notout: ";
cin >> notout;
cout<<"Enter runs: ";
cin >> runs;
calcavg();
cout<<"================================="<<endl;
}
void Batsman::displaydata() {
cout<<"Batsman code "<<bcode<<endl
<<"Batsman name "<<bname<<endl
<<"Innings "<<innings<<endl
<<"Not out "<<notout<<endl
<<"Runs "<<runs<<endl
<<"Batting Average "<<batavg<<endl;
}
int main()
{
Batsman myBatsman;
myBatsman.readdata();
myBatsman.displaydata();
return 0;
}
Question 3 Define a class TEST in C++ with following description: Private Members TestCode of type integer Description of type string NoCandidate of type integer CenterReqd (number of centers required) of type integer A member function CALCNTR() to calculate and return the number of centers as (NoCandidates/100+1) Public Members - A function SCHEDULE() to allow user to enter values for TestCode, Description, NoCandidate & call function CALCNTR() to calculate the number of Centres
Code:
#include<iostream>
using namespace std;
class TEST {
private:
int TestCode;
string Description;
int NoCandidates;
int CALCNTR() {
return (NoCandidates/100+1);
}
public :
void SCHEDULE();
void DISPTEST();
};
void TEST::SCHEDULE () {
cout<<"Enter TestCode: ";
cin>> TestCode;
cout<<"Enter Description: ";
cin.ignore();
getline(cin, Description);
cout<<"Enter NoCandidate: ";
cin >> NoCandidates ;
int number_of_centers = CALCNTR();
cout<<"================================="<<endl;
}
void TEST ::DISPTEST() {
cout<<"TestCode: "<<TestCode<<endl
<<"Description: "<<Description<<endl
<<"NoCandidates "<<NoCandidates<<endl
<<"number_of_centers "<<CALCNTR()<<endl;
}
int main()
{
TEST myTEST ;
myTEST.SCHEDULE();
myTEST.DISPTEST();
return 0;
}
Question 4 Define a class in C++ with following description: Private Members A data member Flight number of type integer A data member Destination of type string A data member Distance of type float A data member Fuel of type float A member function CALFUEL() to calculate the value of Fuel as per the following criteria Distance Fuel <=1000 500 more than 1000 and <=2000 1100 more than 2000 2200 Public Members A function FEEDINFO() to allow user to enter values for Flight Number, Destination, Distance & call function CALFUEL() to calculate the quantity of Fuel A function SHOWINFO() to allow user to view the content of all the data members
Code:
#include <iostream>
#include <string>
using namespace std;
class Flight {
int FlightNumber;
string Destination;
float Distance;
float Fuel;
void CALFUEL();
public:
Flight(int num, string dest, float dist);
void Display(ostream& os);
};
Flight::Flight(int num, string dest, float dist) :
FlightNumber(num), Destination(dest), Distance(dist) {
CALFUEL();
}
void Flight::CALFUEL() {
if (Distance <= 1000)
Fuel = 500;
else if (Distance <= 2000)
Fuel = 1100;
else
Fuel = 2200;
}
void Flight::Display(ostream& os) {
os << "Flight number " << FlightNumber << " to "
<< Destination << " needs " << Fuel << " fuel" << endl;
}
int main() {
Flight fl1(123, "Philadelphia", 200);
Flight fl2(345, "Memphis", 1230);
Flight fl3(987, "Austin", 2120);
fl1.Display(cout);
fl2.Display(cout);
fl3.Display(cout);
}
Question 5 Define a class BOOK with the following specifications : Private members of the class BOOK are BOOK NO integer type BOOKTITLE 20 characters PRICE float (price per copy) TOTAL_COST() A function to calculate the total cost for N number of copies where N is passed to the function as argument. Public members of the class BOOK are INPUT() function to read BOOK_NO. BOOKTITLE, PRICE PURCHASE() function to ask the user to input the number of copies to be purchased. It invokes TOTAL_COST() and prints the total cost to be paid by the user. Note : You are also required to give detailed function definitions.
Code :
#include <iostream>
using namespace std;
class Author
{
public:
int number_copyes = 0;
void purchased()
{
cout << "Input the number of copies to be purchased: ";
cin >> number_copyes;
}
float total_cost()
{
return number_copyes * price_float;
}
void input()
{
cout << "Enter book_no: ";
cin >> book_no;
cout<<"Enter book_tittle: ";
cin >> book_tittle;
cout << "Enter price book: ";
cin >> price_float;
}
private:
int book_no;
char book_tittle [20];
double price_float;
};
int main()
{
Author example;
example.input();
example.purchased();
cout << "Total cost: " << example.total_cost();
return 0;
}
Question 6 Define a class REPORT with the following specification: Private members : adno 4 digit admission number name 20 characters marks an array of 5 floating point values average average marks obtained GETAVG() a function to compute the average obtained in five subject Public members: READINFO() function to accept values for adno, name, marks. Invoke the function GETAVG() DISPLAYINFO() function to display all data members of report on the screen. You should give function definitions.
Code :
#include<iostream>
using namespace std;
class BOOK
{
int BOOKNO;
char BOOKTITLE[20];
float PRICE;
void TOTAL_COST(int N)
{
float tcost;
tcost=PRICE*N;
cout<<tcost;
}
public:
void INPUT()
{
cout<<"Enter Book Number ";
cin>>BOOKNO;
cout<<"Enter Book Title ";
gets(BOOKTITLE);
cout<<"Enter price per copy ";
cin>>PRICE;
}
void PURCHASE()
{
int n;
cout<<"Enter number of copies to purchase ";
cin>>n;
cout<<"Total cost is ";
TOTAL_COST(n);
}
};
int main()
{
BOOK obj;
obj.INPUT();
obj.PURCHASE();
return 0;
}
Question 7:
store details related to a student in a class consisting of his age (int), first_name (string), last_name (string) and standard (int). You have to create a class, named Student, representing the student's details, as mentioned above, and store the data of a student. Create setter and getter functions for each element; that is, the class should at least have following functions:
• get_age, set_age
• get_first_name, set_first_name
• get_last_name, set_last_name
• get_standard, set_standard
Also, you have to create another method to_string() which returns the string consisting of the above elements, separated by a comma(,). You can refer to stringstream for this.
Input Format
Input will consist of four lines. The first line will contain an integer, representing the age. The second line will contain a string, consisting of lower-case Latin characters ('a'-'z'), representing the first_name of a student. The third line will contain another string, consisting of lower-case Latin characters ('a'-'z'), representing the last_name of a student. The fourth line will contain an integer, representing the standard of student.
Note: The number of characters in first_name and last_name will not exceed 50.
Output Format
The code provided by HackerRank will use your class members to set and then get the elements of the Student class.
Sample Input
15
john
carmack
10
Sample Output
15
carmack, john
10
15,john,carmack,10
Code :
#include <iostream>
#include <sstream>
using namespace std;
class Student{
int age;
int standard;
string first_name;
string last_name;
public:
Student()
{
age = 0;
standard = 0;
first_name.clear();
last_name.clear();
}
void set_age(int newAge)
{
age = newAge;
}
void set_standard(int newStandard)
{
standard = newStandard;
}
void set_first_name(string newFirst_name)
{
first_name = newFirst_name;
}
void set_last_name(string newLast_name)
{
last_name = newLast_name;
}
int get_age() {return age;}
int get_standard() {return standard;}
string get_first_name() {return first_name;}
string get_last_name() {return last_name;}
string to_string()
{
stringstream ss;
char c = ',';
ss << age << c << first_name << c << last_name << c << standard;
return ss.str();
}
};
int main() {
int age, standard;
string first_name, last_name;
cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
cout << st.get_age() << "\n";
cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
cout << st.get_standard() << "\n";
cout << "\n";
cout << st.to_string();
return 0;
}
Question 8 Write the definition for a class called Rectangle that has floating point data member length and width. The class has the following member functions:
void setlength(float) to set the length data member void setwidth(float) to set the width data member float perimeter() to calculate and return the perimeter of the rectangle float area() to calculate and return the area of the rectangle
void show() to display the length and width of the rectangle int sameArea(Rectangle) that has one parameter of type Rectangle. sameArea returns 1 if the two Rectangles have the same area, and returns 0 if they don't.
1. Write the definitions for each of the above member functions. 2. Write main function to create two rectangle objects. Set the length and width of the first rectangle to 5 and 2.5. Set the length and width of the second rectangle to 5 and 18.9. Display each rectangle and its area and perimeter. 3. Check whether the two Rectangles have the same area and print a message indicating the result. Set the length and width of the first rectangle to 15 and 6.3. Display each Rectangle and its area and perimeter again. Again, check whether the two Rectangles have the same area and print a message indicating the result.
Code:
#include<iostream>
using namespace std;
class rectangle
{
float l,w;
public:
rectangle(){}
rectangle(float l,float w)
{
setlength(l);
setwidth(w);
}
void setlength(float l)
{
this->l=l;
}
void setwidth(float w)
{
this->w=w;
}
float getlength()
{
return l;
}
float getwidth()
{
return w;
}
void show()
{
cout<<"\nLength of Rectangle: "<<getlength()<<endl;
cout<<"\nWidth of Rectangle: "<<getwidth()<<endl;
}
float perimeter()
{
float p=0;
p= 2*(this->l + this->w);
return p;
}
float area()
{
float a;
a= (this->l * this->w);
return a;
}
void compare(rectangle &o)
{
int lf1=0,wf1=0,lf2=0,wf2=0;
if( this->l > o.l)
{
cout<<"\nLength of Rectangle 1st is larger"<<endl;
lf1=1;
}
else
{
cout<<"\nLength of Rectangle 2nd is larger"<<endl;
lf2=1;
}
if( this->w > o.w)
{
cout<<"\nWidth of Rectangle 1st is larger"<<endl;
wf1=1;
}
else
{
cout<<"\nWidth of Rectangle 2nd is larger"<<endl;
wf2=1;
}
}
void compare(int a)
{
int areas;
areas=this->area();
if(areas > a)
cout<<"\nArea of Rectangle 1st is more than 2nd\n";
else
cout<<"\nArea of Rectangle 2nd is more than 1st\n";
}
};
int main(void)
{
rectangle obj1(2.6,8.1),obj2;
obj1.show();
obj2.setlength(4.9);
obj2.setwidth(2.3);
obj2.show();
cout<<"\nPerimeter of Rectangle: "<<obj1.perimeter();
cout<<"\nArea of Rectangle: "<<obj1.area();
obj1.compare(obj2);
obj1.compare(obj2.area());
}
Question 9 Write the definition for a class called complex that has floating point data members for storing real and imaginary parts. The class has the following member functions:
void set(float, float) to set the specified value in object
void disp() to display complex number object
complex sum(complex) to sum two complex numbers & return complex number
1. Write the definitions for each of the above member functions.
2. Write main function to create three complex number objects. Set the value in two objects and call sum() to calculate sum and assign it in third object. Display all complex numbers.
Code :
#include<iostream>
using namespace std;
class complex
{
private:
float x;
float y;
public:
void set(float real, float img)
{
x=real; y=img;
}
complex sum(complex);
void disp();
};
complex complex::sum(complex C)
{
complex t;
t.x = x + C.x;
t.y = y + C.y;
return t;
}
void complex::disp()
{
cout<<x<<" + j"<<y<<endl;
}
int main()
{
complex C1,C2,C3;
C1.set(2.5,7.1);
C2.set(4.2,5.5);
C3=C1.sum(C2);
cout<<"\n complex Number 1 = ";C1.disp();
cout<<"\n complex Number 2 = ";C2.disp();
cout<<"\n complex Number 3 = ";C3.disp();
return 0;
}
Question 10 Write the definition for a class called Distance that has data member feet as integer and inches as float. The class has the following member functions:
void set(int, float) to give value to object
void disp() to display distance in feet and inches
Distance add(Distance) to sum two distances & return distance
1. Write the definitions for each of the above member functions.
2. Write main function to create three Distance objects. Set the value in two objects and call add() to calculate sum and assign it in third object. Display all distances.
Code :
#include <iostream>
using namespace std;
class Distance
{
int feet;
float inches;
public:
Distance():feet(0),inches(0){}
void set(int ft,float in)
{
feet = ft;
if (in >= 12)
{
feet += in / 12;
int tmpin = (int)in;
inches = (tmpin % 12)+ in- tmpin;
}
else
inches = in;
}
Distance add(const Distance& d)
{
Distance x;
int tmpf = feet + d.feet;
float tmpi = inches + d.inches;
x.set(tmpf, tmpi);
return x;
}
void disp()
{
cout << "Feet of distance: " << feet
<< "\nInches of distance:" << inches<<endl;
}
};
int main()
{
Distance a;
a.set(5, 23.7);
cout << "Info about a:\n";
a.disp();
Distance b;
b.set(3, 14.8);
cout << "Info about b:\n";
b.disp();
Distance c = a.add(b);
cout << "Info about c = a.add(b):\n";
c.disp();
}
Question 11 Write the definition for a class called time that has hours and minutes as integer. The class has the following member functions:
void settime(int, int) to set the specified value in object
void showtime() to display time object
time sum(time) to sum two time object & return time
1. Write the definitions for each of the above member functions.
2. Write main function to create three time objects. Set the value in two objects and call sum() to calculate sum and assign it in third object. Display all time objects.
Code :
#include<iostream>
using namespace std;
class time
{
private:
int hours;
int minutes;
public:
void settime(int h, int m)
{
hours=h; minutes=m;
}
time sum(time);
void showtime();
};
time time::sum(time TM)
{
time t;
t.minutes = minutes + TM.minutes;
t.hours=t.minutes/60;
t.minutes=t.minutes%60;
t.hours += hours + TM.hours;
return t;
}
void time::showtime()
{
cout<<hours<<" hours and "<<minutes<<" minutes"<<endl;
}
int main()
{
time T1,T2,T3;
T1.settime(2,45);
T2.settime(3,30);
T3=T1.sum(T2);
cout<<"\n Time 1 : ";T1.showtime();
cout<<"\n Time 2 : ";T2.showtime();
cout<<"\n Time 3 : ";T3.showtime();
return 0;
}
Optput:
Question12: Kristen is a contender for valedictorian of her high school. She wants to know how many students (if any) have scored higher than her in the 5 exams given during this semester.
Create a class named student with the following specifications:
• An instance variable named scores to hold a student's exam scores.
• A void input() function that reads 5 integers and saves them to scores.
• An int calculateTotalScore() function that returns the sum of the student's scores.
Input Format
• Most of the input is handled for you by the locked code in the editor.
• In the void Student::input() function, you must read 5 scores from stdin and save them to your scores instance variable.
Output Format
• In the int Student::calculateTotalScore() function, you must return the student's total grade (the sum of the values in scores).
• The locked code in the editor will determine how many scores are larger than Kristen's and print that number to the console.
Sample Input
The first line contains ,n the number of students in Kristen's class. The n subsequent lines contain each student's exam grades for this semester.
3
30 40 45 10 10
40 40 40 10 10
50 20 30 10 10
Sample Output
1
Explanation
Kristen's grades are on the first line of grades. Only student scored higher than her.
Code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
class Student {
private:
int scores[5];
int sum;
public:
Student() : sum(0) {}
int calculateTotalScore() {return sum;}
void input() {
for(int i=0; i<5; i++) {
cin >> scores[i];
sum+=scores[i];
}
}
};
int main() {
int n;
cin >> n;
Student *s = new Student[n];
for(int i = 0; i < n; i++){
s[i].input();
}
int kristen_score = s[0].calculateTotalScore();
int count = 0;
for(int i = 1; i < n; i++){
int total = s[i].calculateTotalScore();
if(total > kristen_score){
count++;
}
}
cout << count;
return 0;
}
Comments
Post a Comment