0% found this document useful (0 votes)
32 views38 pages

C++ Solution Full Paper-2

Uploaded by

Ranjeet Kumar
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)
32 views38 pages

C++ Solution Full Paper-2

Uploaded by

Ranjeet Kumar
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/ 38

Solutions for All Programming Tasks

Name – Shivani. Roll No.240651

Problem 1: Check if a given character is a vowel or consonant

C++ Code:

#include <iostream>

using namespace std;

void checkVowelOrConsonant(char c) {

if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {

if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||

c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {

cout << c << " is a vowel." << endl;

} else { cout << c << " is a

consonant." << endl;

} else { cout << c << " is not an

alphabet." << endl;

}
int main() { char c; cout <<

"Enter a character: "; cin >>

c;

checkVowelOrConsonant(c);

return 0;

Problem 2: Check Whether a Number is Positive, Negative, or Zero

C++ Code:

#include <iostream>

using namespace std;

int main() { double number;

cout << "Enter a number: ";

cin >> number;

if (number > 0) cout << "The number is

positive." << endl; else if (number < 0)

cout << "The number is negative." << endl;

else cout << "The number is zero." <<

endl;

return 0;

}
Problem 3: Check if an Input Character is an Alphabet, Digit, or Special Character C++ Code:

#include <iostream>

using namespace std;

int main() { char ch; cout

<< "Enter a character: "; cin

>> ch;

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))

cout << ch << " is an alphabet." << endl; else if (ch

>= '0' && ch <= '9') cout << ch << " is a digit." <<

endl; else cout << ch << " is a special

character." << endl;

return 0;

Problem 4: Create a Calculator Using the Switch Statement

C++ Code:

#include <iostream>

using namespace std;

int main() {

char op; double num1, num2;

cout << "Enter an operator (+, -, *, /): ";


cin >> op; cout << "Enter two

numbers: "; cin >> num1 >> num2;

switch (op) {

case '+':

cout << "Result: " << num1 + num2 << endl;

break;

case '-':

cout << "Result: " << num1 - num2 << endl;

break;

case '*':

cout << "Result: " << num1 * num2 << endl;

break;

case '/':

if (num2 != 0) cout << "Result: " <<

num1 / num2 << endl;

else cout << "Division by zero

error!" << endl; break; default:

cout << "Invalid operator!" << endl; break;

return 0;

Problem 5: Print a Half-Pyramid Using Numbers

C++ Code:
#include <iostream>

using namespace std;

int main() { int rows; cout <<

"Enter the number of rows: "; cin >>

rows;

for (int i = 1; i <= rows; ++i) {

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

cout << j << " ";

cout << endl;

return 0;

}
#include <iostream>

using namespace std;

// 6. Half-Pyramid Using *

void halfPyramid() {

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

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

cout << "* ";

cout << endl;

// 7(a). Alphabet Pyramid

void alphabetPyramid() {

char ch = 'A';

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

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

cout << ch << " ";

ch++;

cout << endl;

// 7(b). Reverse Half-Pyramid

void reverseHalfPyramid() {

for (int i = 5; i >= 1; i--) {


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

cout << "* ";

cout << endl;

// 7(c). Centered Pyramid

void centeredPyramid() {

int rows = 5;

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

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

cout << " ";

for (int j = 0; j < 2 * (rows - i) - 1; j++) {

cout << "* ";

cout << endl;

// 7(d). Number Pyramid

void numberPyramid() {

int num = 1;

for (int i = 1; i <= 4; i++) {

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

cout << num << " ";


num++;

cout << endl;

// 7(e). Repeated Number Pyramid

void repeatedNumberPyramid() {

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

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

cout << i << " ";

cout << endl;

} }

int main() {

cout << "6. Half-Pyramid Using *" << endl;

halfPyramid();

cout << endl;

cout << "7(a). Alphabet Pyramid" << endl; alphabetPyramid();

cout << endl;

cout << "7(b). Reverse Half-Pyramid" << endl;

reverseHalfPyramid();

cout << endl;


cout << "7(c). Centered Pyramid" << endl;

centeredPyramid();

cout << endl;

cout << "7(d). Number Pyramid" << endl;

numberPyramid();

cout << endl;

cout << "7(e). Repeated Number Pyramid" << endl;

repeatedNumberPyramid();

return 0;

C++ Program Solutions

1. Program to Find HCF/GCD

#include <iostream>

using namespace std;

int findHCF(int a, int b) {

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

}
return a;

int main() {

int num1, num2;

cout << "Enter two numbers: ";

cin >> num1 >> num2;

cout << "HCF/GCD of " << num1 << " and " << num2 << " is " << findHCF(num1, num2) <<

endl;

return 0;

2. Program to Find LCM

#include <iostream>

using namespace std;

int findHCF(int a, int b) {

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

return a;

int findLCM(int a, int b) {


return (a * b) / findHCF(a, b);

int main() {

int num1, num2;

cout << "Enter two numbers: ";

cin >> num1 >> num2;

cout << "LCM of " << num1 << " and " << num2 << " is " << findLCM(num1, num2) <<

endl;

return 0;

3. Program to Check if a Number is Palindrome

#include <iostream>

using namespace std;

bool isPalindrome(int num) {

int original = num, reversed = 0;

while (num > 0) {

reversed = reversed * 10 + (num % 10);

num /= 10;

return original == reversed;

int main() {
int num;

cout << "Enter a number: ";

cin >> num;

if (isPalindrome(num))

cout << num << " is a palindrome." << endl;

else

cout << num << " is not a palindrome." << endl;

return 0;

4. Program to Check if a Number is Armstrong

#include <iostream>

#include <cmath>

using namespace std;

bool isArmstrong(int num) {

int original = num, sum = 0, digits = 0;

while (num > 0) {

digits++;

num /= 10;

num = original;

while (num > 0) {

sum += pow(num % 10, digits);

num /= 10;

}
return sum == original;

int main() {

int num;

cout << "Enter a number: ";

cin >> num;

if (isArmstrong(num))

cout << num << " is an Armstrong number." << endl;

else

cout << num << " is not an Armstrong number." << endl;

return 0;

5. Program to Calculate Sum of Natural Numbers

#include <iostream>

using namespace std;

int main() {

int n;

cout << "Enter a positive integer: ";

cin >> n;

int sum = (n * (n + 1)) / 2;

cout << "Sum of first " << n << " natural numbers is " << sum << endl;

return 0;

}
6. Program for Sum of Series 1-2+3-4...n

#include <iostream>

using namespace std;

int sumSeries(int n) {

int sum = 0;

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

sum += (i % 2 == 0) ? -i : i;

return sum;

int main() {

int n;

cout << "Enter a positive integer: ";

cin >> n;

cout << "Sum of the series is " << sumSeries(n) << endl;

return 0;

}
*Question 1: Program to Compute the Sum of the First N Terms of the Series*

```

#include <iostream> using

namespace std;

double calculate_series_sum(int n) {

double sum = 0;

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

double sign = (i % 2 == 0) ? 1 : -1;

sum += sign / (i + 1);

return sum;

int main() {

int n;

cout << "Enter the number of terms: "; cin >> n; cout <<

"Sum of the series: " << calculate_series_sum(n) << endl; return

0;

```

*Question 2: Program to Remove Duplicates from an Array*

```
#include <iostream> using

namespace std;

void remove_duplicates(int arr[], int &n) {

int temp[100];

int j = 0; for (int i = 0; i <

n; i++) { bool found =

false; for (int k = 0; k < j;

k++) { if (arr[i] ==

temp[k]) { found =

true; break;

if (!found) {

temp[j++] = arr[i];

} for (int i = 0; i < j;

i++) { arr[i] =

temp[i];

} n

= j; }

int main() {

int arr[100];

int n;
cout << "Enter the size of the array: "; cin

>> n; cout << "Enter the elements of the

array: ";

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

cin >> arr[i];

remove_duplicates(arr, n); cout

<< "Array without duplicates: ";

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

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

cout << endl;

return 0;

```

*Question 3: Program to Print a Table Indicating the Number of Occurrences of Each


Alphabet*

```

#include <iostream>

#include <cstring> using

namespace std;

void count_alphabets(char text[]) {

int alphabet_counts[26] = {0}; for

(int i = 0; i < strlen(text); i++) {

char c = tolower(text[i]);
if (c >= 'a' && c <= 'z') {

alphabet_counts[c - 'a']++;

cout << "Alphabet Counts:" << endl;

for (int i = 0; i < 26; i++) { cout << (char)(i + 'a') << ": " <<

alphabet_counts[i] << endl;

int main() { char

text[100]; cout << "Enter

the text: ";

cin.getline(text, 100);

count_alphabets(text);

return 0;

```

*Question 4: Menu-Driven Program to Perform String Manipulation*

```

#include <iostream>

#include <cstring> using

namespace std;

void show_address_of_each_character(char string[]) {


for (int i = 0; i < strlen(string); i++) {

cout << "Address of '" << string[i] << "': " << (void*)&string[i] << endl;

char* concatenate_two_strings(char str1[], char str2[]) {

char* result = new char[strlen(str1) + strlen(str2) + 1];

strcpy(result, str1); strcat(result, str2); return

result;

// ... (rest of the functions remain the same

*Question 5: Program to Merge Two Ordered Arrays*

```

#include <iostream> using

namespace std;

void merge_ordered_arrays(int arr1[], int m, int arr2[], int n) {

int* result = new int[m + n]; int i = 0, j = 0, k = 0;

while (i < m && j < n) {


if (arr1[i] <= arr2[j]) {

result[k++] = arr1[i++];

} else { result[k++]

= arr2[j++];

while (i < m) {

result[k++] = arr1[i++];

while (j < n) {

result[k++] = arr2[j++];

cout << "Merged array: ";

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

cout << result[i] << " ";

cout << endl;

delete[] result;

int main() { int arr1[] = {1, 3, 5, 7};

int arr2[] = {2, 4, 6, 8}; int m =


sizeof(arr1) / sizeof(arr1[0]); int n =

sizeof(arr2) / sizeof(arr2[0]);

merge_ordered_arrays(arr1, m, arr2, n);

return 0;

```

*Question 6: Program to Search a Given Element Using Binary Search*

*(a) With Recursion*

```

#include <iostream> using

namespace std;

int binary_search_recursive(int arr[], int low, int high, int key) {

if (low > high) { return -1;

int mid = (low + high) / 2;

if (arr[mid] == key) {

return mid;

} else if (arr[mid] > key) { return

binary_search_recursive(arr, low, mid - 1, key);


} else {

return binary_search_recursive(arr, mid + 1, high, key);

int main() { int arr[] = {2, 5, 8, 12, 16, 23, 38,

56, 72, 91}; int n = sizeof(arr) /

sizeof(arr[0]); int key; cout << "Enter the

key to search: "; cin >> key;

int result = binary_search_recursive(arr, 0, n - 1, key);

if (result == -1) { cout << "Key not found in

the array." << endl;

} else { cout << "Key found at index " << result <<

"." << endl;

return 0;

```

*(b) Without Recursion*

```

#include <iostream> using

namespace std; int


binary_search_iterative(in

t arr[], int n, int key) {

int low = 0; int high = n

- 1;

while (low <= high) {

int mid = (low + high) / 2;

if (arr[mid] == key) {

return mid; } else if

(arr[mid] > key) { high

= mid - 1; } else {

low = mid + 1;

return -1;

int main() { int arr[] = {2, 5, 8, 12, 16, 23, 38,

56, 72, 91}; int n = sizeof(arr) /

sizeof(arr[0]); int key; cout << "Enter the

key to search: "; cin >> key;

int result = binary_search_iterative(arr, n, key);


if (result == -1) { cout << "Key not found in

the array." << endl;

} else { cout << "Key found at index " << result <<

"." << endl;

return 0;

```

*Question 7: Program to Calculate GCD of Two Numbers*

*(a) With Recursion*

```

#include <iostream> using

namespace std;

int gcd_recursive(int a, int b) {

if (b == 0) { return a;

return gcd_recursive(b, a % b);

int main() {
int num1, num2; cout << "Enter

the first number: "; cin >> num1;

cout << "Enter the second number: ";

cin >> num2;

int gcd = gcd_recursive(num1, num2);

cout << "GCD of " <<

_Question 8: Matrix Class and Operations_

```

#include <iostream>

#include <stdexcept>

class Matrix {

private: int

rows; int

cols; int**

data;

public:

Matrix(int rows, int cols) {

this->rows = rows; this-

>cols = cols; data = new

int*[rows]; for (int i =


0; i < rows; i++) {

data[i] = new int[cols];

~Matrix() { for (int i = 0; i

< rows; i++) { delete[]

data[i];

delete[] data;

void setElement(int row, int col, int value) { if (row < 0

|| row >= rows || col < 0 || col >= cols) { throw

std::out_of_range("Matrix indices out of range");

data[row][col] = value;

int getElement(int row, int col) { if (row < 0 || row >=

rows || col < 0 || col >= cols) { throw

std::out_of_range("Matrix indices out of range");

return data[row][col];

}
Matrix* add(Matrix* other) { if (rows !=

other->rows || cols != other->cols) { throw

std::invalid_argument("Matrices are not

compatible for addition");

Matrix* result = new Matrix(rows, cols); for (int i = 0; i < rows;

i++) { for (int j = 0; j < cols; j++) { result->setElement(i, j,

getElement(i, j) + other->getElement(i, j));

return result;

Matrix* multiply(Matrix* other) { if (cols != other->rows) { throw

std::invalid_argument("Matrices are not compatible for multiplication");

Matrix* result = new Matrix(rows, other->cols); for

(int i = 0; i < rows; i++) { for (int j = 0; j < other->cols;

j++) { int sum = 0; for (int k = 0; k < cols;

k++) { sum += getElement(i, k) * other-

>getElement(k, j);

result->setElement(i, j, sum);

return result;

}
Matrix* transpose() {

Matrix* result = new Matrix(cols, rows);

for (int i = 0; i < rows; i++) { for (int j = 0; j

< cols; j++) { result->setElement(j, i,

getElement(i, j));

return result;

};

int main() {

try {

Matrix* mat1 = new Matrix(2, 2); mat1-

>setElement(0, 0, 1); mat1->setElement(0, 1, 2);

mat1->setElement(1, 0, 3); mat1->setElement(1,

1, 4);

Matrix* mat2 = new Matrix(2, 2); mat2-

>setElement(0, 0, 5); mat2->setElement(0, 1, 6);

mat2->setElement(1, 0, 7); mat2->setElement(1,

1, 8);

Matrix* sum = mat1->add(mat2);

Matrix* product = mat1->multiply(mat2);

Matrix* transpose = mat1->transpose();


cout << "Sum:" << endl; for (int i = 0;

i < sum->rows; i++) { for (int j = 0; j <

sum->cols; j++) { cout << sum-

>getElement(i, j) << " ";

cout << endl;

cout << "Product:" << endl; for (int i = 0;

i < product->rows; i++) { for (int j = 0; j <

product->cols; j++) { cout << product-

>getElement(i, j) << " ";

cout << endl;

cout << "Transpose:" << endl; for (int i = 0;

i < transpose->rows; i++) { for (int j = 0; j <

transpose->cols; j++) { cout << transpose-

>getElement(i, j) << " ";

cout << endl;

delete mat1;

delete mat2; delete

sum; delete
product; delete

transpose;

} catch

_Question 9: Person, Student, and Employee Classes_

```

#include <iostream>

#include <string>

class Person { protected:

std::string name;

public:

Person(const std::string& name) : name(name) {}

virtual void display() const { std::cout <<

"Name: " << name << std::endl;

virtual ~Person() {}

};

class Student : public Person { private:

std::string course; int

marks;

int year;
public:

Student(const std::string& name, const std::string& course, int marks, int year)

: Person(name), course(course), marks(marks), year(year) {}

void display() const override {

Person::display(); std::cout << "Course: " <<

course << std::endl; std::cout << "Marks: " <<

marks << std::endl; std::cout << "Year: " <<

year << std::endl;

};

class Employee : public Person { private:

std::string department;

double salary;

public:

Employee(const std::string& name, const std::string& department, double salary)

: Person(name), department(department), salary(salary) {}

void display() const override { Person::display();

std::cout << "Department: " << department << std::endl;

std::cout << "Salary: " << salary << std::endl;

};
int main() {

Person* persons[] = {new Student("John Doe", "CS", 90, 2022),

new Employee("Jane Doe", "HR", 50000.0)};

for (Person* person : persons) {

person->display(); std::cout

<< std::endl;

for (Person* person : persons) {

delete person;

return 0;

```

_Question 10: Triangle Class_

```

#include <iostream>

#include <stdexcept>

class Triangle { private:

double side1;

double side2;

double side3;
public:

Triangle(double side1, double side2, double side3) { if (side1 <=

0 || side2 <= 0 || side3 <= 0) { throw std::invalid_argument("All

sides must be greater than 0");

if (side1 + side2 <= side3 || side2 + side3 <= side1 || side3 + side1 <= side2) {

throw std::invalid_argument("Sum of any two sides must be greater than the third
side");

this->side1 = side1; this-

>side2 = side2; this->side3 =

side3;

double calculateAreaRightAngled() const {

// Calculate area using formula: (base * height) / 2

// Assume side1 and side2 are the base and height

return (side1 * side2) / 2;

double calculateAreaHeron() const {

// Calculate semi-perimeter double s

= (side1 + side2 + side3) / 2; //

Calculate area using Heron's formula


return sqrt(s * (s - side1) * (s - side2) * (s

- side3));

};

int main() {

try {

Triangle triangle(3.0, 4.0, 5.0);

std::cout << "Area (Right Angled): " << triangle.calculateAreaRightAngled() << std::endl;

std::cout << "Area (Heron's Formula): " << triangle.calculateAreaHeron() << std::endl;

} catch (const std::exception& e) { std::cerr

<< "Error: " << e.what() << std::endl; return

1;

return 0;

_Question 11: Student Class and File Operations_

```

#include <iostream>

#include <fstream>

#include <string>
class Student { private:

int rollNo;

std::string name;

std::string className;

int year; double

totalMarks;

public:

Student(int rollNo, const std::string& name, const std::string& className, int year, double
totalMarks)

: rollNo(rollNo), name(name), className(className), year(year),


totalMarks(totalMarks) {}

void display() const { std::cout << "Roll No.: " <<

rollNo << std::endl; std::cout << "Name: " << name <<

std::endl; std::cout << "Class: " << className <<

std::endl; std::cout << "Year: " << year << std::endl;

std::cout << "Total Marks: " << totalMarks << std::endl;

friend std::ostream& operator<<(std::ostream& os, const Student& student) {

os << student.rollNo << " " << student.name << " " << student.className << " " <<
student.year << " " << student.totalMarks;

return os;

friend std::istream& operator>>(std::istream& is, Student& student) {


is >> student.rollNo >> student.name >> student.className >> student.year >>
student.totalMarks;

return is;

};

int main() {

// Create 5 Student objects

Student students[] = {

Student(1, "John Doe", "X", 2022, 90.0),

Student(2, "Jane Doe", "XI", 2023, 85.0),

Student(3, "Bob Smith", "XII", 2024, 95.0),

Student(4, "Alice Johnson", "X", 2022, 88.0),

Student(5, "Mike Brown", "XI", 2023, 92.0)

};

// Write Student objects to file

std::ofstream fileOut("students.txt"); if

(fileOut.is_open()) { for (const Student&

student : students) { fileOut <<

student << std::endl;

fileOut.close();

} else { std::cerr << "Unable to open file for writing." <<

std::endl; return 1;

}
// Read Student objects from file and display

std::ifstream fileIn("students.txt"); if

(fileIn.is_open()) { Student student;

while (fileIn >> student) {

student.display(); std::cout << std::endl;

fileIn.close();

} else { std::cerr << "Unable to open file for reading." <<

std::endl; return 1;

return 0;

```

_Question 12: Copy File Contents Without Whitespaces_

```

#include <iostream>

#include <fstream>

#include <string>

int main() { std::ifstream

fileIn("input.txt");

std::ofstream

fileOut("output.txt");
if (fileIn.is_open() && fileOut.is_open()) {

std::string line; while

(std::getline(fileIn, line)) { std::string

newline; for (char c : line) {

if (!std::isspace(c)) { newline +=

c;

fileOut << newline << std::endl;

fileIn.close(); fileOut.close(); } else {

std::cerr << "Unable to open file(s)." << std::endl;

return 1;

return 0;

```

You might also like