0% found this document useful (0 votes)
5 views

C-- Programs

Ntg

Uploaded by

abdvilliers64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C-- Programs

Ntg

Uploaded by

abdvilliers64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

1) C++ program to find the largest of three numbers

#include <iostream>
using namespace std;

int main() {
double num1, num2, num3;

cout << "Enter three numbers: ";


cin >> num1 >> num2 >> num3;

if (num1 >= num2 && num1 >= num3) {


cout << "The largest number is " << num1 << endl;
} else if (num2 >= num1 && num2 >= num3) {
cout << "The largest number is " << num2 << endl;
} else {
cout << "The largest number is " << num3 << endl;
}

return 0;
}

Output:
Enter three numbers: 0 -1 4
The largest number is 4
2) C++ program to sort the elements in ascending or descending order

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

int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;

int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

int choice;
cout << "Enter 1 to sort in ascending order or 2 to sort in descending
order: ";
cin >> choice;

if (choice == 1) {
sort(arr, arr + n);
cout << "Sorted array in ascending order: ";
} else if (choice == 2) {
sort(arr, arr + n, greater<int>());
cout << "Sorted array in descending order: ";
} else {
cout << "Invalid choice! Please run the program again.";
return 0;
}

for (int i = 0; i < n; i++) {


cout << arr[i] << " ";
}
cout << endl;

return 0;
}

Output:
Enter the number of elements: 5
Enter the elements: 0 -1 -0 4 6
Enter 1 to sort in ascending order or 2 to sort in descending order: 1
Sorted array in ascending order: -1 0 0 4 6
(OR)
Enter 1 to sort in ascending order or 2 to sort in descending order: 2
Sorted array in descending order: 6 4 0 0 -1
3) C++ program using classes to display student name, roll number, marks
obtained in two subjects and total score of students.

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

class Student {
private:
string name;
int rollNumber;
int marksSubject1;
int marksSubject2;

public:
void setDetails(string studentName, int roll, int marks1, int marks2) {
name = studentName;
rollNumber = roll;
marksSubject1 = marks1;
marksSubject2 = marks2;
}

void displayDetails() {
cout << "Student Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Marks in Subject 1: " << marksSubject1 << endl;
cout << "Marks in Subject 2: " << marksSubject2 << endl;
cout << "Total Score: " << (marksSubject1 + marksSubject2) << endl;
}
};

int main()
{
Student student;
string name;
int roll, marks1, marks2;

cout << "Enter student name: ";


getline(cin, name);

cout << "Enter roll number: ";


cin >> roll;

cout << "Enter marks obtained in subject 1: ";


cin >> marks1;

cout << "Enter marks obtained in subject 2: ";


cin >> marks2;
student.setDetails(name, roll, marks1, marks2);
cout << endl;
cout << "Student Details:" << endl;
student.displayDetails();

return 0;
}

Output:
Enter student name: Abubakkar
Enter roll number: 4556
Enter marks obtained in subject 1: 25
Enter marks obtained in subject 2: 30

Student Details:
Student Name: Abubakkar
Roll Number: 4556
Marks in Subject 1: 25
Marks in Subject 2: 30
Total Score: 55
4) C++ program for a bank employee to print name of the employee,
account number and balance. Print invalid balance if amount<500.
Display the same, also display the balance after withdraw and deposit.

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

class BankEmployee {
private:
string name;
long accountNumber;
float balance;

public:
BankEmployee(string employeeName, long accNumber, float
initialBalance) {
name = employeeName;
accountNumber = accNumber;
if (initialBalance < 500) {
cout << "Invalid balance" << endl;
balance = 0;
} else {
balance = initialBalance;
}
}
void displayDetails() {
cout << "Employee Name: " << name << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Balance: " << balance << endl;
}

void withdraw(float amount) {


if (balance >= amount) {
balance -= amount;
cout << "Balance after withdrawal: " << balance << endl;
} else {
cout << "Insufficient balance" << endl;
}
}

void deposit(float amount) {


balance += amount;
cout << "Balance after deposit: " << balance << endl;
}
};

int main() {
string name;
long accountNumber;
float initialBalance, withdrawAmount, depositAmount;
cout << "Enter employee name: ";
getline(cin, name);

cout << "Enter account number: ";


cin >> accountNumber;

cout << "Enter initial balance: ";


cin >> initialBalance;

BankEmployee employee(name, accountNumber, initialBalance);


cout << endl;
cout << "Employee Details:" << endl;
employee.displayDetails();

cout << "Enter the amount to withdraw: ";


cin >> withdrawAmount;
employee.withdraw(withdrawAmount);

cout << "Enter the amount to deposit: ";


cin >> depositAmount;
employee.deposit(depositAmount);
return 0;
}
Output 1:
Enter employee name: Abubakkar
Enter account number: 47786
Enter initial balance: 300
Invalid balance
Employee Details:
Employee Name: Abubakkar
Account Number: 47786
Balance: 0
Enter the amount to withdraw: 200
Insufficient balance
Enter the amount to deposit: 600
Balance after deposit: 600

Output 2:
Enter employee name: Abubakkar
Enter account number: 59667
Enter initial balance: 600
Employee Details:
Employee Name: Abubakkar
Account Number: 59667
Balance: 600
Enter the amount to withdraw: 200
Balance after withdrawal: 400
Enter the amount to deposit: 50
Balance after deposit: 450
5) C++ program to demonstrate function overloading for the following
prototypes.
add(int a, int b)
add(double a, double b)

#include <iostream>
using namespace std;

int add(int a, int b) {


return a + b;
}

double add(double a, double b) {


return a + b;
}

int main() {
int intResult = add(5, 3);
double doubleResult = add(2.5, 3.7);

cout << "Result of adding two integers: " << intResult << endl;
cout << "Result of adding two doubles: " << doubleResult << endl;

return 0;
}
Output:
Result of adding two integers: 8
Result of adding two doubles: 6.2
6) C++ program using operator overloading for overloading unary minus
operator.
#include <iostream>
using namespace std;

class Number {
private:
int value;

public:
Number() : value(0) {}
Number(int val) : value(val) {}

Number operator-() {
Number result;
result.value = -value;
return result;
}

void display() {
cout << "Value: " << value << endl;
}
};

int main() {
Number num1(10);
Number num2 = -num1; // using the overloaded unary minus operator

cout << "Original Number: ";


num1.display();

cout << "After Unary Minus: ";


num2.display();

return 0;
}

Output:
Original Number: Value: 10
After Unary Minus: Value: -10

In this program, the Number class overloads the unary minus


operator - using the operator- method. When the unary minus
operator is applied to an object of the Number class, it returns a
new Number object with the negated value.
7) C++ program to implement Multiple inheritance for performing
arithmetic operation of two numbers.

#include <iostream>
using namespace std;

// First base class


class Addition {
public:
int add(int a, int b) {
return a + b;
}
};

// Second base class


class Subtraction {
public:
int subtract(int a, int b) {
return a - b;
}
};
// Derived class inheriting from two base classes
class Arithmetic : public Addition, public Subtraction {
public:
void display(int a, int b) {
cout << "Sum: " << add(a, b) << endl;
cout << "Difference: " << subtract(a, b) << endl;
}
};

int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
Arithmetic obj;
obj.display(num1, num2);
return 0;
}

Output:
Enter two numbers: 8 3
Sum: 11
Difference: 5
8) C++ program using constructor in derived classes r initialize
alpha, beta and gamma and display corresponding values.

#include <iostream>
using namespace std;

// Base class
class Alpha {
protected:
int alpha;

public:
Alpha(int a) : alpha(a) {}
};

// First derived class


class Beta : public Alpha {
protected:
int beta;

public:
Beta(int a, int b) : Alpha(a), beta(b) {}
};
// Second derived class
class Gamma : public Beta {
private:
int gamma;

public:
Gamma(int a, int b, int c) : Beta(a, b), gamma(c) {
// You can perform additional initialization if needed
}

void displayValues() {
cout << "Alpha: " << alpha << endl;
cout << "Beta: " << beta << endl;
cout << "Gamma: " << gamma << endl;
}
};

int main() {
// Create an object of the Gamma class and initialize values
Gamma obj(10, 20, 30);
// Display the initialized values
obj.displayValues();
return 0;
}

Output:
Alpha: 10
Beta: 20
Gamma: 30
9) C++ program to create a text file, check file created or not, if
created it will write some text into the file and then read the
text from the file.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
// Create a text file
ofstream outFile("sample.txt");
// Check if the file is created successfully
if (!outFile.is_open()) {
cout << "Error creating the file!" << endl;
return 1;
}
// Write text into the file
outFile << "Hello, this is some text written to the file.\n";
outFile << "This is another line in the file.";
// Close the file
outFile.close();
// Read text from the file
ifstream inFile("sample.txt");
// Check if the file is opened successfully
if (!inFile.is_open()) {
cout << "Error opening the file!" << endl;
return 1;
}
// Display the content of the file
cout << "Contents of the file:" << endl;
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
// Close the file
inFile.close();
return 0;
}

Output:
Contents of the file:
Hello, this is some text written to the file.
This is another line in the file.
10) C++ program to write and read time in / from binary file using
fstream
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;

int main() {
// Get the current time
time_t currentTime = time(0);

// Open a binary file for writing


ofstream outFile("time_data.bin", ios::binary);

// Check if the file is opened successfully


if (!outFile.is_open()) {
cout << "Error creating the file!" << endl;
return 1;
}

// Write the current time to the file


outFile.write(reinterpret_cast<char*>(&currentTime),
sizeof(currentTime));
// Close the file
outFile.close();

cout << "Time has been written to the file." << endl;

// Open the binary file for reading


ifstream inFile("time_data.bin", ios::binary);

// Check if the file is opened successfully


if (!inFile.is_open()) {
cout << "Error opening the file!" << endl;
return 1;
}

// Read the time from the file


time_t readTime;
inFile.read(reinterpret_cast<char*>(&readTime),
sizeof(readTime));

// Close the file


inFile.close();
// Display the read time
cout << "Time read from the file: " << ctime(&readTime);

return 0;
}

Output:
Time has been written to the file.
Time read from the file: Mon Nov 13 10:17:40 2023.
11) Develop a function which throws a division by zero exception
and catch it in catch block. write a C++ program to demonstrate
the usage of try, catch and throw to handle exception.

#include <iostream>
using namespace std;

// Function that throws a division by zero exception


double divide(int numerator, int denominator) {
if (denominator == 0) {
throw "Division by zero is not allowed.";
}
return static_cast<double>(numerator) / denominator;
}

int main() {
int numerator, denominator;

cout << "Enter numerator: ";


cin >> numerator;

cout << "Enter denominator: ";


cin >> denominator;
try {
// Attempt to perform division
double result = divide(numerator, denominator);
cout << "Result of division: " << result << endl;
} catch (const char* error) {
// Catch and handle the exception
cout << "Exception caught: " << error << endl;
}

return 0;
}

Output-1:
Enter numerator: 8
Enter denominator: 0
Exception caught: Division by zero is not allowed.

Output-2:
Enter numerator: 8
Enter denominator: 2
Result of division: 4
12) C++ program that handles array out of bounds exception
using C++.

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

// Function that throws an array out-of-bounds exception


int accessArrayElement(int arr[], int size, int index) {
if (index < 0 || index >= size) {
throw out_of_range("Array index out of bounds");
}
return arr[index];
}

int main() {
const int arraySize = 5;
int myArray[arraySize] = {1, 2, 3, 4, 5};
int index;

cout << "Enter the index to access in the array: ";


cin >> index;
try {
// Attempt to access the array element
int value = accessArrayElement(myArray, arraySize, index);
cout << "Value at index " << index << ": " << value << endl;
} catch (const out_of_range& e) {
// Catch and handle the array out-of-bounds exception
cout << "Exception caught: " << e.what() << endl;
}

return 0;
}

Output 1:
Enter the index to access in the array: 0
Value at index 0: 1

Output 2:
Enter the index to access in the array: 7
Exception caught: Array index out of bounds

You might also like