Skip to main content

Posts

Write a program using the algorithm count() to count how many elements in a container have a specified value.

 Here's an example program using the count() algorithm to count the number of occurrences of a specific value in a vector container: #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() {     vector<int> numbers = { 2, 5, 3, 7, 8, 5, 1, 5, 4 };          // count the number of occurrences of the value 5 in the vector     int count = count(numbers.begin(), numbers.end(), 5);          cout << "The number of occurrences of 5 in the vector is: " << count << endl;          return 0; } Output: The number of occurrences of 5 in the vector is: 3 Explanation: The program starts by creating a vector named numbers that contains several integer values. The count() algorithm is used to count the number of occurrences of the value 5 in the numbers vector. The function takes three arguments: the beginning and end iterators of...

Write a program in C++ using the find() algorithm to locate the position of a specified value in a sequence container.

  here's an example program using the find() algorithm to locate the position of a specified value in a vector: #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() {     // Create a vector of integers     vector<int> vec = { 5, 2, 7, 9, 1, 8 };     // Find the position of the value 7 in the vector     auto it = find(vec.begin(), vec.end(), 7);     // Check if the value was found and print the position     if (it != vec.end()) {         cout << "The position of the value 7 is: " << distance(vec.begin(), it) << endl;     } else {         cout << "The value 7 was not found in the vector." << endl;     }     return 0; } Output: The position of the value 7 is: 2 In this program, we first create a vector of integers with some random values. We then use the find() algor...

Write a main program that calls a deeply nested function containing an exception. Incorporate necessary exception handling mechanism.

 Here's an example program that demonstrates a deeply nested function containing an exception, and incorporates exception handling: #include <iostream> using namespace std; void functionC() {     // A divide-by-zero exception will be thrown here     int x = 10, y = 0, z = x/y; } void functionB() {     functionC(); } void functionA() {     functionB(); } int main() {     try     {         functionA();     }     catch(const exception& e)     {         cerr << "Exception caught: " << e.what() << '\n';     }     return 0; } In this program, functionC() performs a divide-by-zero operation, which throws an exception. functionC() is called by functionB(), which is called by functionA(), which is called from main(). The try block in main() calls functionA(), which may throw an exception. If an exception is thrown, ...

Write a program to demonstrate the concept of rethrowing an exception.

 In C++, an exception can be rethrown to be caught by another catch block. This allows for more fine-grained handling of exceptions in a program. Here is an example program that demonstrates rethrowing an exception: #include <iostream> using namespace std; void divide(int a, int b) {     try {         if (b == 0) {             throw "Division by zero error";         }         else {             cout << "a/b = " << a/b << endl;         }     }     catch (const char* e) {         cout << "Exception caught in divide(): " << e << endl;         throw;  // rethrowing the same exception     } } int main() {     int x = 10, y = 0;     try {         divide(x, y);     }   ...

Write a program that demonstrates how certain exception types are not allowed to be thrown.

 In C++, there are certain types of exceptions that are not allowed to be thrown. These include void, function type, reference type, and array of non-zero bound with elements of these types. Let's see an example program that demonstrates this: #include <iostream> using namespace std; int main() {    try {       // Attempt to throw an exception of type void       throw void();    }    catch (...) {       cout << "Caught an exception of type void!" << endl;    }    try {       // Attempt to throw an exception of type function type       throw int(int);    }    catch (...) {       cout << "Caught an exception of type function type!" << endl;    }    try {       // Attempt to throw an exception of type reference type       int a = 10;     ...

Write a program that illustrates the application of multiple catch statements.

 Here's an example program that uses multiple catch statements to handle different types of exceptions: #include <iostream> #include <string> using namespace std; int main() {     try {         int num1, num2, result;         cout << "Enter two numbers to divide: ";         cin >> num1 >> num2;         if (num2 == 0) {             throw string("Cannot divide by zero!");         }         result = num1 / num2;         cout << "Result: " << result << endl;     } catch (string errorMessage) {         cout << "Error: " << errorMessage << endl;     } catch (...) {         cout << "Unknown error occurred." << endl;     }     return 0; } In this program, we...

Write a program containing a possible exception. Use a try block to throw it and a catch block to handle it properly.

 Here is an example program that demonstrates the use of try and catch block to handle an exception: #include <iostream> #include <string> using namespace std; void divide(int a, int b) {     if (b == 0) {         throw "Divide by zero exception";     }     cout << "a/b = " << a/b << endl; } int main() {     int a, b;     cout << "Enter two numbers: ";     cin >> a >> b;     try {         divide(a, b);     }     catch (const char* msg) {         cerr << "Exception caught: " << msg << endl;     }     return 0; } In this program, we define a function divide that takes two integers as arguments and throws an exception if the second argument is zero. The main function reads two integers from the user and calls the divide function within a try block. If a...

Write a function template to perform linear search in an array in C++ program.

  here's an example program in C++ that uses a function template to perform linear search on an array: #include <iostream> using namespace std; template <typename T> int linearSearch(T arr[], int size, T key) {     for (int i = 0; i < size; i++) {         if (arr[i] == key) {             return i; // Return the index where key was found         }     }     return -1; // Key not found in array } int main() {     int intArr[] = { 1, 2, 3, 4, 5 };     int intSize = sizeof(intArr) / sizeof(intArr[0]);     int intKey = 3;     cout << "Index of " << intKey << " in intArr: " << linearSearch(intArr, intSize, intKey) << endl;     double doubleArr[] = { 1.2, 2.3, 3.4, 4.5, 5.6 };     int doubleSize = sizeof(doubleArr) / sizeof(doubleArr[0]);     double doubleKey = 4.5;   ...

Write a function template for finding the minimum value contained in an array in C++ program.

 here's an example of a function template for finding the minimum value contained in an array in C++: #include <iostream> using namespace std; template<typename T> T findMin(T arr[], int size) {     T minVal = arr[0];     for(int i = 1; i < size; i++) {         if(arr[i] < minVal) {             minVal = arr[i];         }     }     return minVal; } int main() {     int intArr[] = {4, 8, 2, 10, 5};     double doubleArr[] = {2.5, 6.7, 1.2, 4.5};          cout << "Minimum value in intArr: " << findMin(intArr, 5) << endl;     cout << "Minimum value in doubleArr: " << findMin(doubleArr, 4) << endl;     return 0; } In this example, we define a function template findMin that takes an array of any type (T) and its size as parameters. The function iterates through th...

Write a program that reads a text file and creates another file that is identical except that every sequence of consecutive blank spaces is replaced by a single space.

 To solve this problem, we can follow these steps: Open the input file for reading and the output file for writing. Read the input file line by line. For each line, replace every sequence of consecutive blank spaces with a single space using the std::regex_replace function from the regex library. Write the modified line to the output file. Here is the code: #include <iostream> #include <fstream> #include <regex> using namespace std; int main() {     // Open the input file for reading and the output file for writing     ifstream infile("input.txt");     ofstream outfile("output.txt");     if (!infile) {         cerr << "Error: Could not open input file.\n";         return 1;     }     if (!outfile) {         cerr << "Error: Could not open output file.\n";         return 1;     }     string lin...

Write a program which reads a text from the keyboard and displays the following information on the screen: a) Number of lines b) Number of words c) Number of characters Strings should be left-justified and numbers should be right-justified in suitable field width.

 To solve this problem, we can read the text input from the keyboard using the getline function and then process the text to count the number of lines, words, and characters. We can use the istringstream class to separate the text into words. Here's the program: #include <iostream> #include <sstream> #include <string> using namespace std; int main() {     string text;     int num_lines = 0, num_words = 0, num_chars = 0;     // Read text from keyboard     cout << "Enter text: " << endl;     getline(cin, text);     // Process text     istringstream iss(text);     string word;     while (iss >> word) {         num_words++;         num_chars += word.length();     }     // Count lines     for (char c : text) {         if (c == '\n') {           ...

Write a program to find the value of e in the following series: e=1+1/1!+1/2!+......... upto acc = 0.0001

 To find the value of e in the given series, we need to sum up the terms until the accuracy reaches 0.0001. We can use a loop to add the terms and check for the accuracy. Here's the program to find the value of e: #include <iostream> #include <cmath> using namespace std; int main() {     double e = 1.0, term = 1.0;     int i = 1;     const double acc = 0.0001; // desired accuracy     while (fabs(term) > acc) {         term /= i; // i! = i * (i-1)!, so divide by i to get (i-1)!         e += term;         i++;     }     cout << "The value of e is: " << e << endl;     return 0; } In this program, we initialize the value of e and term to 1.0 and i to 1. We also set the desired accuracy acc to 0.0001. The loop continues until the absolute value of term is less than or equal to acc . In each iteration, we divide term b...

Write a program to read a list containing item name, item code, and cost interactively and produce a three column output. Note that the name and code are left-justified with a precision of two digits.

 Here's a program to read a list containing item name, item code, and cost interactively and produce a three column output: #include <iostream> #include <iomanip> #include <string> using namespace std; int main() {     string name, code;     double cost;     cout << "Enter item name, code, and cost: " << endl;     cin >> name >> code >> cost;     cout << setw(20) << left << "Item Name" << setw(10) << left << "Item Code" << setw(10) << left << "Cost" << endl;     cout << setw(20) << left << name << setw(10) << left << code << setprecision(2) << fixed << cost << endl;     return 0; } Example output: Enter item name, code, and cost: Shirt SH-01 25.99 Item Name           Item Code Cost Shirt        ...

Write a program to compute the area of a triangle and a circle by overloading the area() function.

 Here's an example program that overloads the area() function to calculate the area of a triangle and a circle: #include <iostream> using namespace std; // Function to calculate area of triangle float area(float base, float height) {     return 0.5 * base * height; } // Function to calculate area of circle float area(float radius) {     return 3.14 * radius * radius; } int main() {     float base, height, radius;     // Read input for triangle     cout << "Enter base and height of the triangle: ";     cin >> base >> height;     // Calculate and display area of triangle     float tri_area = area(base, height);     cout << "Area of triangle: " << tri_area << endl;     // Read input for circle     cout << "Enter radius of the circle: ";     cin >> radius;     // Calculate and display area of circle ...

Write a program to read a matrix of size m x n from the keyboard and display the same on the screen using functions.

  here's a program that reads a matrix of size m x n from the keyboard and displays it on the screen using functions: #include <iostream> using namespace std; // Function to read matrix of size m x n from the keyboard void read_matrix(int m, int n, int matrix[][]) {     cout << "Enter the elements of the matrix:" << endl;     for (int i = 0; i < m; i++) {         for (int j = 0; j < n; j++) {             cin >> matrix[i][j];         }     } } // Function to display matrix of size m x n on the screen void display_matrix(int m, int n, int matrix[][]) {     cout << "The matrix is:" << endl;     for (int i = 0; i < m; i++) {         for (int j = 0; j < n; j++) {             cout << matrix[i][j] << "\t";         }        ...

Write a function to read a matrix of size m x n from the keyboard.

Write a function to read a matrix of size m x n from the keyboard. here's an example program to read a matrix of size m x n from the keyboard: #include <iostream> using namespace std; int main() {     int m, n;     cout << "Enter the size of matrix (m x n): ";     cin >> m >> n;     int matrix[m][n];     cout << "Enter the elements of matrix:" << endl;     for (int i = 0; i < m; i++) {         for (int j = 0; j < n; j++) {             cin >> matrix[i][j];         }     }     cout << "The matrix is:" << endl;     for (int i = 0; i < m; i++) {         for (int j = 0; j < n; j++) {             cout << matrix[i][j] << " ";         }         cout << endl; ...

An election is contested by five candidates. The candidates are numbered 1 to 5 and the voting is done by making the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast for each candidate using an array variable count. In case, a number read is outside the range 1 to 5, the ballot should be considered as a 'spoilt ballot', and the program should also count the number of spoilt ballots.

 Here is a C++ program that reads the ballots and counts the votes cast for each candidate and the number of spoilt ballots: #include <iostream> using namespace std; int main() {    int count[5] = {0}; // initialize count array with 0s    int spoilt_ballots = 0;    int candidate;    // read ballots until -1 is entered    cout << "Enter the candidate number (1-5) on the ballot paper (-1 to stop):\n";    cin >> candidate;    while (candidate != -1) {       if (candidate >= 1 && candidate <= 5) {          count[candidate-1]++;       } else {          spoilt_ballots++;       }       cin >> candidate;    }    // display the results    for (int i = 0; i < 5; i++) {       cout << "Candidate " << i+1 << " recei...

Print format using C++ program

 Write a program to print the following output using for loops. 1 22 333 4444 55555 Here's a program in C++ to print the pattern using nested for loops: #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 << i;         }         cout << endl;     }     return 0; } Output for the pattern with 5 rows: 1 22 333 4444 55555 Explanation: We first prompt the user to enter the number of rows they want to print for the pattern. We use nested for loops to iterate through each row and column of the pattern. The outer for loop runs from 1 to the number of rows input by the user. The inner for loop runs from 1 to the current row number. For each in...

Write a function that creates a vector of user-given size M using new operator in a program

  here's an example program that creates a vector of user-given size M using the new operator: #include <iostream> #include <vector> using namespace std; // Function to create a vector of given size using new operator vector<int>* createVector(int size) {     return new vector<int>(size); } int main() {     int M;     cout << "Enter the size of vector: ";     cin >> M;     // Create vector using new operator     vector<int>* myVector = createVector(M);     // Display vector size     cout << "Vector size: " << myVector->size() << endl;     // Deallocate memory used by vector     delete myVector;     return 0; } In this program, we define a function called createVector that takes an integer argument size and returns a pointer to a new std::vector<int> object created using the new operator with the specified ...

Write a function using reference variables as arguments to swap the values of a pair of integers in a program

 here's an example program that swaps the values of two integers using a function with reference variables: #include <iostream> using namespace std; // function to swap two integers using reference variables void swap(int& x, int& y) {     int temp = x;     x = y;     y = temp; } int main() {     int num1 = 10, num2 = 20;          // before swapping     cout << "Before swapping: " << endl;     cout << "num1 = " << num1 << ", num2 = " << num2 << endl;          // swap the values of num1 and num2     swap(num1, num2);          // after swapping     cout << "After swapping: " << endl;     cout << "num1 = " << num1 << ", num2 = " << num2 << endl;          return 0; } Output: Before swapping: num1 = 10, ...