Learn Programming

This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, March 23, 2023

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

March 23, 2023 0

 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 the container to search, and the value to count.
  • The count is then stored in an integer variable named count.
  • Finally, the program outputs the count using the cout statement.

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

March 23, 2023 0

  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() algorithm from the <algorithm> header to find the position of the value 7 in the vector.

The find() algorithm returns an iterator pointing to the first occurrence of the value in the range [first, last]. If the value is not found, it returns an iterator pointing to the end of the range.

We then check if the value was found by comparing the iterator to the end of the vector. If the value was found, we use the distance() function to calculate the position of the iterator from the beginning of the vector, which gives us the position of the value in the vector. If the value was not found, we simply print a message stating that it was not found.

Friday, March 17, 2023

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

March 17, 2023 0

 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, it is caught by the catch block, which prints an error message to the console. In this case, the error message will indicate that a divide-by-zero exception was caught.

If we run the program, we will see the following output:

Exception caught: integer division or modulo by zero

This indicates that the exception was caught and handled properly.

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

March 17, 2023 0

 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);
    }
    catch (const char* e) {
        cout << "Exception caught in main(): " << e << endl;
    }
    return 0;

}

In this program, the divide() function takes two integers as arguments and performs a division operation. If the second argument is 0, it throws a "Division by zero error" exception.

The main() function calls divide() with x=10 and y=0, which should trigger the exception. The catch block in main() catches the exception and prints an error message.

However, before the exception is caught in main(), it is caught in the divide() function's catch block. Instead of handling the exception, the divide() function rethrows the same exception using the throw statement. This allows the exception to be caught by the main() function's catch block.

The output of this program is:

Exception caught in divide(): Division by zero error
Exception caught in main(): Division by zero error

As we can see, the exception is caught first by the divide() function's catch block and then by the main() function's catch block. This demonstrates the concept of rethrowing an exception.

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

March 17, 2023 0

 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;
      throw a;
   }
   catch (...) {
      cout << "Caught an exception of type reference type!" << endl;
   }

   try {
      // Attempt to throw an exception of type array of non-zero bound with elements of these types
      int arr[0];
      throw arr;
   }
   catch (...) {
      cout << "Caught an exception of type array of non-zero bound with elements of these types!" << endl;
   }

   return 0;
}

Output:

Caught an exception of type void!
Caught an exception of type function type!
Caught an exception of type reference type!
Caught an exception of type array of non-zero bound with elements of these types!

As we can see from the output, the program catches exceptions of the types that are not allowed to be thrown, demonstrating this restriction in C++.

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

March 17, 2023 0

 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 ask the user to enter two numbers and attempt to divide them. If the second number is zero, we throw a string exception with an appropriate error message. We then use two catch statements to handle exceptions: the first catches any string exception and prints the error message, while the second catches any other type of exception (or even no exception at all) and prints a generic error message.

Here's an example output of the program:

Enter two numbers to divide: 10 0
Error: Cannot divide by zero!

And another example output where the division is successful:

Enter two numbers to divide: 12 4
Result: 3

As you can see, when an exception is thrown, the program jumps immediately to the catch block that can handle it. If no catch block can handle the exception (such as in the case of an unexpected type of exception), the program will terminate and print an error message.

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

March 17, 2023 0

 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 an exception is thrown, the catch block catches the exception and prints an error message.

Sample Output:

Enter two numbers: 10 0
Exception caught: Divide by zero exception

In this case, the user tried to divide 10 by 0, which is not allowed, so the program threw an exception and the catch block caught it and displayed the error message.

Slider Widget