Find accurate and reliable answers to your questions on IDNLearn.com. Ask your questions and receive detailed and reliable answers from our experienced and knowledgeable community members.

Exercise 6.3.7: Add, Subtract, or Multiply



A program that asks the user for two numbers. Then ask them if they would like to add, subtract, or multiply these numbers. Perform the chosen operation on the values, showing the operation being performed (use numbers in order even if a negative value is produced!)

Write three functions, one for each mathematical operation.

For example, if this was the input given:

What is the first number?: 3
What is the second number?: 5
Choose an operation (add, subtract, multiply): multiply
The following output should be given:

3 * 5 = 15
Note: Be sure to print a notice if an invalid operation is chosen!


Sagot :

In programming, a function is a block of code that performs a specific task or computation.

How to write 3 separate functions?

Here is an example of how the program can be implemented using three separate functions for the mathematical operations:

#include <iostream>

#include <string>

// Function to add two numbers

int add(int a, int b) {

   return a + b;

}

// Function to subtract two numbers

int subtract(int a, int b) {

   return a - b;

}

// Function to multiply two numbers

int multiply(int a, int b) {

   return a * b;

}

int main() {

   // Get the first and second numbers from the user

   std::cout << "What is the first number?: ";

   int a;

   std::cin >> a;

   std::cout << "What is the second number?: ";

   int b;

   std::cin >> b;

   // Get the operation to perform from the user

   std::cout << "Choose an operation (add, subtract, multiply): ";

   std::string op;

   std::cin >> op;

   // Call the appropriate function based on the operation chosen by the user

   int result = 0;

   if (op == "add") {

       result = add(a, b);

   } else if (op == "subtract") {

       result = subtract(a, b);

   } else if (op == "multiply") {

       result = multiply(a, b);

   } else {

       // Invalid operation was chosen

       std::cout << "Invalid operation" << std::endl;

       return 0;

   }

   // Print the result of the operation

   std::cout << a << " " << op << " " << b << " = " << result << std::endl;

   return 0;

}

In this program, the add(), subtract(), and multiply() functions are defined to perform the corresponding mathematical operations on two given numbers.

The main() function prompts the user for two numbers and the operation to perform, and then calls the appropriate function based on the operation chosen by the user.

Finally, the result of the operation is printed to the output.

To Know More About Mathematical operations, Check Out

https://brainly.com/question/20628271

#SPJ1