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.

Sunday, March 12, 2023

Write a program that ask user to enter two numbers, calculate and display their sum, difference and product. Calculate each of above using different user defined functions.

 Here's a program in C++ that asks the user to enter two numbers, calculates their sum, difference, and product using user-defined functions, and then displays the results:

#include <iostream>
using namespace std;

int sum(int a, int b) {
    return a + b;
}

int difference(int a, int b) {
    return a - b;
}

int product(int a, int b) {
    return a * b;
}

int main() {
    int num1, num2;
    cout << "Enter the first number: ";
    cin >> num1;
    cout << "Enter the second number: ";
    cin >> num2;

    int result_sum = sum(num1, num2);
    int result_diff = difference(num1, num2);
    int result_prod = product(num1, num2);

    cout << "The sum of the numbers is: " << result_sum << endl;
    cout << "The difference of the numbers is: " << result_diff << endl;
    cout << "The product of the numbers is: " << result_prod << endl;

    return 0;
}

In this program, we define three user-defined functions named sum, difference, and product, which take two arguments a and b, and return the sum, difference, and product of the two numbers respectively.

int sum(int a, int b) {
    return a + b;
}

int difference(int a, int b) {
    return a - b;
}

int product(int a, int b) {
    return a * b;
}

In the main function, we prompt the user to enter two numbers, and then read them in using the cin statement. We then call each of the user-defined functions to calculate the sum, difference, and product of the two numbers, and store the results in separate variables.

int num1, num2;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;

int result_sum = sum(num1, num2);
int result_diff = difference(num1, num2);
int result_prod = product(num1, num2);

Finally, we display the results using cout statements.

cout << "The sum of the numbers is: " << result_sum << endl;
cout << "The difference of the numbers is: " << result_diff << endl;
cout << "The product of the numbers is: " << result_prod << endl;

When the program runs, it will output something like this:

Enter the first number: 10
Enter the second number: 5
The sum of the numbers is: 15
The difference of the numbers is: 5
The product of the numbers is: 50

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget