Write a C++ program to do the following: Define a function called \"difference\"
ID: 3688044 • Letter: W
Question
Write a C++ program to do the following:
Define a function called "difference" that can accept two integer values as arguments and returns an integer (which is the obtained by subtracting the first the second argument from the first argument.
Declare two variables in the main function and assign them values 7 and 10.
Call the difference function with the above created variables as arguments. Print the returned difference in the main function.
Call the function again with 11 and 5 as arguments and print the obtained difference.
Print the two differences on separate lines.
Explanation / Answer
main.cpp
#include <stdio.h>
int main()
{
int number1; // the first number input
int number2; // the second number input
// Calculate the difference (regular subtraction) of two numbers
// number1 - the first number
// number2 - the second number
// Return the difference of the two numbers.
int difference(int number1, int number2);
// Ask the user to input two numbers.
printf("Please input two numbers in the following format: number1 number2 ");
if (scanf("%d %d", &number1, &number2))
{
// If the user inputs two numbers, call minus() to get the difference of the two numbers.
// Print the result on screen.
printf("%d difference %d equals to %d", number1, number2, difference(number1, number2));
}
else
{
// If the user fails to input two numbers, send error message and exit.
printf("Input Error.");
}
return 0;
}
int difference(int number1, int number2)
{
// Return the result of regular subtraction.
return number1 - number2;
}
sample output
Please input two numbers in the following format: number1 number2
10 7
10 difference 7 equals to 3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.