C PracticalFile
C PracticalFile
OUTPUT :
Enter 2 Numbers : 10 10
10 + 10 = 20
10 - 10 = 0
10 * 10 = 100
10 / 10 = 1
PROGRAM 2
QUESTION 2 : WAP TO IMPLEMENT CALL BY REFERENCE AND
RETURN BY REFERENCE USING CLASS. [HINT. ASSUME
NECESSARY FUNCTIONS]
CODE :
#include <iostream>
class SimpleClass{
int value:
public:
SimpleClass(int initialValue) { value = initialValue; }
void displayValue() { std::cout << "Value: " << value << std::endl; }
void modifyValueByReference(int &newValue) { value = newValue; }
int &getValueReference(){return value;}
};
int main(){
SimpleClass obj(42);
std::cout << "Initial ";
obj.displayValue();
int newValue = 99;
obj.modifyValueByReference(newValue);
std::cout << "After modification (using Call By Refrence) ";
obj.displayValue();
obj.getValueReference() = 123;
std::cout << "After return by reference ";
obj.displayValue();
return 0;
}
OUTPUT :
Initial Value: 42
After modification (using Call By Refrence) Value: 99
After return by reference Value: 123
PROGRAM 3
QUESTION 3 : WAP TO IMPLEMENT FRIEND FUNCTION BY
TAKING SOME REAL LIFE EXAMPLE
CODE :
#include <iostream>
class Rectangle
{
private:
int length;
int width;
public:
Rectangle(int l, int w) : length(l), width(w) {}
friend int calculateArea(const Rectangle &rect);
};
int calculateArea(const Rectangle &rect){
return rect.length * rect.width;
}`
int main()
{
Rectangle myRectangle(5, 8);
std::cout << "Area of the rectangle: " << calculateArea(myRectangle) << std::endl;
return 0;
}
OUTPUT :
Area of the rectangle: 40
PROGRAM 4
QUESTION 4 : WAP TO IMPLEMENT ‘FUNCTION OVERLOADING’
CODE :
#include <iostream>
using namespace std;
OUTPUT :
Before swapping: num1 = 5, num2 = 10
After swapping: num1 = 10, num2 = 5
Before swapping: str1 = Hello, str2 = World
After swapping: str1 = World, str2 = Hello
PROGRAM 9
QUESTION 9: WRITE A C++ PROGRAM TO IMPLEMENT
EXCEPTION HANDLING.
CODE :
#include <iostream>
#include <stdexcept>
double divide(int numerator, int denominator) {
if (denominator == 0) {
throw std::invalid_argument("Cannot divide by zero.");
}
return static_cast<double>(numerator) / denominator;
}
int main() {
OUTPUT:
// Example with exception handling for division
Enter numerator: 10
int numerator, denominator;
Enter denominator: 2
// Get user input for numerator and denominator
Result of division: 5
std::cout << "Enter numerator: ";
std::cin >> numerator;
Enter numerator: 8
std::cout << "Enter denominator: ";
Enter denominator: 0
std::cin >> denominator;
Exception caught: Cannot
try {
divide by zero.
// Call the divide function with exception handling
double result = divide(numerator, denominator);
std::cout << "Result of division: " << result << std::endl;
} catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
PROGRAM 10
QUESTION 10: WAP TO READ AND WRITE VALUES THROUGH
OBJECT USING FILE HANDLING
#include <iostream>
#include <fstream>
class Student {
public:
Student() : rollNumber(0), name(""), marks(0.0) {}
Student(int roll, const std::string& studentName, double studentMarks)
: rollNumber(roll), name(studentName), marks(studentMarks) {}
void displayInfo() const {
std::cout << "Roll Number: " << rollNumber << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Marks: " << marks << std::endl;
std::cout << "---------------------" << std::endl;
}
void writeToFile(std::ofstream& outFile) const {
outFile << rollNumber << " " << name << " " << marks << std::endl; }
void readFromFile(std::ifstream& inFile) { inFile >> rollNumber >> name >> marks; }
private:
int rollNumber;
std::string name;
double marks;
};
int main() {
Student students[3] = {
{101, "John Doe", 85.5},
{102, "Jane Smith", 90.0},
{103, "Bob Johnson", 78.3}
};
std::ofstream outFile("students.txt");
for (const auto& student : students) {
student.writeToFile(outFile);
}
outFile.close();
std::ifstream inFile("students.txt");
for (auto& student : students) {
student.readFromFile(inFile);
}
inFile.close();
for (const auto& student : students) {
student.displayInfo();
}
return 0;
}
OUTPUT :
Roll Number: 101
Name: Chandan Pandey
Marks: 0
---------------------
Roll Number: 102
Name: Harsh Singh
Marks: 90
---------------------
Roll Number: 103
Name: Sachin Goswami
Marks: 78.3
---------------------
PROGRAM 11
QUESTION 11 : Create a class employee which have name, age and
address of employee, include functions getdata() and showdata(), getdata()
takes the input from the user, showdata() display the data in following
format:
Name:
Age:
Address:
CODE :
#include <iostream>
#include <string>
class Employee
{
private:
std::string name;
int age;
std::string address;
public:
void getdata()
{
std::cout << "Enter employee details:" << std::endl;
std::cout << "Name: ";
std::getline(std::cin, name);
std::cout << "Age: ";
std::cin >> age;
std::cin.ignore();
std::cout << "Address: ";
std::getline(std::cin, address);
}
void showdata(){
std::cout << "\nEmployee Details:\n";
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Address: " << address << std::endl;
}
};
int main()
{
Employee employee;
employee.getdata();
employee.showdata();
return 0;
}
OUTPUT :
Enter employee details:
Name: Chandan Pandey
Age: 19
Address: Noida sec-56
Employee Details:
Name: Chandan Pandey
Age: 19
Address: Noida sec-56
PROGRAM 12
QUESTION 12 : Write a class called CAccount which contains two private
data elements, an integer accountNumber and a floating point
accountBalance, and three member functions: A constructor that allows
the user to set initial values for accountNumber and accountBalance and a
default constructor that prompts for the input of the values for the above
data numbers. A function called inputTransaction, which reads a
character value for transactionType(‘D’ for deposit and ‘W’ for
withdrawal), and a floating point value for transactionAmount, which
updates accountBalance. A function called printBalance, which prints on
the screen the accountNumber and accountBalance.
CODE :
#include <iostream>
class CAccount{
private:
int accountNumber;
float accountBalance;
public:
CAccount(int number, float balance){
accountNumber = number;
accountBalance = balance;
}
CAccount(){
std::cout << "Enter Account Number: ";
std::cin >> accountNumber;
std::cout << "Enter Initial Account Balance: ";
std::cin >> accountBalance;
}
void inputTransaction(){
char transactionType;
float transactionAmount;
std::cout << "Enter transaction type of Account Number " <<
accountNumber << " (D for deposit, W for withdrawal) : ";
std::cin >> transactionType;
std::cout << "Enter transaction amount: ";
std::cin >> transactionAmount;
if (transactionType == 'D'){
accountBalance += transactionAmount;
}else if (transactionType == 'W'){
if (transactionAmount <= accountBalance){
accountBalance -= transactionAmount;
} else{
std::cout << "Insufficient balance for withdrawal." << std::endl;
}
} else{
std::cout << "Invalid transaction type." << std::endl;
}
}
void printBalance(){
std::cout << "Account Number: " << accountNumber << std::endl;
std::cout << "Account Balance: $" << accountBalance << std::endl;
}
};
int main(){
CAccount account1(123, 1000.0);
CAccount account2;
account2.inputTransaction();
account1.inputTransaction();
account1.printBalance();
account2.printBalance();
return 0;
}
OUTPUT :
Enter Account Number: 121
Enter Initial Account Balance: 10000
Enter transaction type of Account Number 121 (D for deposit, W for withdrawal) : D
Enter transaction amount: 12000
Enter transaction type of Account Number 122 (D for deposit, W for withdrawal) : W
Enter transaction amount: 600
Account Number: 122
Account Balance: 9400rs
Account Number: 121
Account Balance: 22000rs
PROGRAM 13
QUESTION 13 : Define a class Counter which contains an int variable
count defined as static and a static function Display () to display the value
of count. Whenever an object of this class is created count is incremented
by 1. Use this class in main to create multiple objects of this class and
display value of count each time
CODE :
#include <iostream>
class Counter {
static int count;
public:
Counter() { count++; }
static void Display() {
std::cout << "Count: " << count << std::endl;
}
};
int Counter::count = 0;
int main(){
Counter obj1;
Counter::Display(); // Count: 1
Counter obj2;
Counter::Display(); // Count: 2
Counter obj3;
Counter::Display(); // Count: 3
return 0;
}
OUTPUT :
Count : 1
Count : 2
Count : 3
PROGRAM 14
QUESTION 14 : WAP TO ADD AND SUBTRACT TWO COMPLEX
NUMBERS USING CLASSES
CODE :
#include <iostream>
class Complex {
double real;
double imaginary;
public:
Complex() : real(0.0), imaginary(0.0) {}
Complex(double r, double i) : real(r), imaginary(i) {}
Complex add(Complex &other) {
return Complex(real + other.real, imaginary + other.imaginary); }
Complex subtract(Complex &other) {
return Complex(real - other.real, imaginary - other.imaginary); }
void display() { std::cout << "(" << real << " + " << imaginary << "i)" << std::endl; }
};
int main(){
Complex complex1(3.0, 4.0);
Complex complex2(1.5, 2.5);
Complex sum = complex1.add(complex2);
Complex difference = complex1.subtract(complex2);
std::cout << "Complex Number 1: ";
complex1.display();
std::cout << "Complex Number 2: ";
OUTPUT :
complex2.display();
Complex Number 1: (3 + 4i)
std::cout << "Sum: ";
Complex Number 2: (1.5 + 2.5i)
sum.display();
std::cout << "Difference: "; Sum: (4.5 + 6.5i)
return 0;
}
OUTPUT :
After addition:
Value: 15
PROGRAM 16
QUESTION 16 : WAP TO IMPLEMENT += AND = OPERATOR
CODE :
#include <iostream>
class MyNumber{
int value;
public:
MyNumber() : value(0) {}
MyNumber(int val) : value(val) {}
MyNumber &operator+=(const MyNumber &other){
this->value += other.value;
return *this;
}
MyNumber &operator=(const MyNumber &other){
if (this != &other){ this->value = other.value; }
return *this;
}
void display() const{ std::cout << "Value: " << value << std::endl; }
};
int main(){
MyNumber num1(5);
MyNumber num2(10);
num1 += num2;
std::cout << "After += operation:" << std::endl;
num1.display();
OUTPUT :
MyNumber num3 = num2;
After += operation:
std::cout << "After = operation:" << std::endl;
Value: 15
num3.display();
After = operation:
return 0;
Value: 1
}
PROGRAM 17
QUESTION 17 : IMPLEMENT THE FOLLOWING CLASS
HIERARCHY CONSIDERING APPROPRIATE DATA MEMBERS AND
MEMBER FUNCTIONS
CODE :
#include <iostream>
#include <string>
class Student{
protected:
std::string name;
int rollNumber;
public:
Student(const std::string &studentName, int studentRollNumber)
: name(studentName), rollNumber(studentRollNumber) {}
void displayStudentInfo() const {
std::cout << "Student Name: " << name << std::endl;
std::cout << "Roll Number: " << rollNumber << std::endl; }
};
class Test : public Student{
protected:
int testScore;
public:
Test(const std::string &studentName, int studentRollNumber, int score)
: Student(studentName, studentRollNumber), testScore(score) {}
void displayTestInfo() const{
Student::displayStudentInfo(); // Specify Student's version
std::cout << "Test Score: " << testScore << std::endl;
}
};
class Sports : public Student{
protected:
std::string sportName;
public:
Sports(const std::string &studentName, int studentRollNumber, const std::string &sport)
: Student(studentName, studentRollNumber), sportName(sport) {}
void displaySportsInfo() const{
Student::displayStudentInfo(); // Specify Student's version
std::cout << "Sport: " << sportName << std::endl;
}
};
class Performance : public Test, public Sports{
public:
Performance(const std::string &studentName, int studentRollNumber, int testScore, const
std::string &sport)
: Test(studentName, studentRollNumber, testScore), Sports(studentName,
studentRollNumber, sport) {}
OUTPUT :
Student Name: John Doe
Roll Number: 101
Student Name: John Doe
Roll Number: 101
Test Score: 85
Student Name: John Doe
Roll Number: 101
Sport: Football
PROGRAM 18
QUESTION 18 : IMPLEMENT THE FOLLOWING HIERARCHY
CONSIDERING APPROPRIATE DATA MEMBERS AND MEMBER
FUNCTIONS (USE VIRTUAL FUNCTIONS).
CODE :
#include <iostream>
class Shape{
public:
virtual double calculateArea() const = 0;
virtual void displayShapeInfo() const = 0;
};
class Triangle : public Shape{
double base;
double height;
public:
Triangle(double b, double h) : base(b), height(h) {}
double calculateArea() const override { return 0.5 * base * height; }
void displayShapeInfo() const override{
std::cout << "Triangle - Base: " << base << ", Height: " << height << std::endl; }
};
class Rectangle : public Shape{
double length;
double width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double calculateArea() const override{
return length * width;
}
void displayShapeInfo() const override {
std::cout << "Rectangle - Length: " << length << ", Width: " << width << std::endl; }
};
class Circle : public Shape{
double radius;
public:
Circle(double r) : radius(r) {}
double calculateArea() const override{
return 3.14159 * radius * radius;
}
void displayShapeInfo() const override{
std::cout << "Circle - Radius: " << radius << std::endl;
}
};
int main(){
Triangle triangle(5, 8);
Rectangle rectangle(4, 6);
Circle circle(3);
triangle.displayShapeInfo();
std::cout << "Area: " << triangle.calculateArea() << std::endl;
rectangle.displayShapeInfo();
std::cout << "Area: " << rectangle.calculateArea() << std::endl;
circle.displayShapeInfo();
std::cout << "Area: " << circle.calculateArea() << std::endl;
return 0; }
OUTPUT :
Triangle - Base: 5, Height: 8
Area: 20
Rectangle - Length: 4, Width: 6
Area: 24
Circle - Radius: 3
Area: 28.2743
PROGRAM 19
QUESTION 19 : IMPLEMENT THE FOLLOWING HIERARCHY
CONSIDERING APPROPRIATE DATA MEMBERS AND MEMBER
FUNCTIONS (USE VIRTUAL FUNCTIONS).
CODE :
#include <iostream>
class LengthConverter {
double length; // length in meters
public:
LengthConverter(double l) : length(l) {}
operator double() const { return length * 100; // 1 meter = 100 centimeters }
LengthConverter& operator=(const double& centimeters) {
length = centimeters / 100; // 1 meter = 100 centimeters
return *this;
}
void displayInMeters() const {
std::cout << "Length in meters: " << length << " m" << std::endl; }
void displayInCentimeters() const {
std::cout << "Length in centimeters: " << static_cast<double>(*this) << " cm" <<
std::endl;}
};
int main() {
OUTPUT :
LengthConverter lengthInMeters(5.0);
Length in meters: 5 m
lengthInMeters.displayInMeters();
Length in centimeters: 500 cm
lengthInMeters.displayInCentimeters();
Length in centimeters: 20000 cm
Length in meters: 200 m
LengthConverter lengthInCentimeters = 200.0;
lengthInCentimeters.displayInCentimeters();
lengthInCentimeters.displayInMeters();
return 0;
}
PROGRAM 20
QUESTION 20 : WAP TO COUNT DIGITS, ALPHABETS AND
SPACES, STORED IN A TEXT FILE, USING STREAMS
CODE :
#include <iostream>
#include <fstream>
#include <cctype> // For isdigit and isalpha functions
int main(){
std::ifstream inputFile("sample.txt");
if (!inputFile.is_open()){
std::cerr << "Error opening file." << std::endl;
return 1;
}
char ch;
int digitCount = 0;
int alphabetCount = 0;
int spaceCount = 0;
while (inputFile.get(ch)){
if (isdigit(ch)) { digitCount++; }
else if (isalpha(ch)) { alphabetCount++; }
else if (isspace(ch)) { spaceCount++; } }
inputFile.close();
std::cout << "Digit Count: " << digitCount << std::endl;
std::cout << "Alphabet Count: " << alphabetCount << std::endl;
std::cout << "Space Count: " << spaceCount << std::endl;
return 0;
}
OUTPUT :
Digit Count: 3
Alphabet Count: 27
Space Count: 7