4. What does the following program do (by observation)? To be more precise, what
ID: 3927668 • Letter: 4
Question
4. What does the following program do (by observation)? To be more precise, what is the underlying meaning of the program? #include int mystery(int a, int b); // function prototype int main(void) { int x; //first integer int y; //second integer printf("Enter two integers: "); scanf("%d%d", &x, &y); printf("The result is %d ", mystery(x, y)); return 0; } /*Parameter b must be a positive integer to prevent infinite recursion*/ int mystery( int a, int b) { if (b == 1) return a; else return a + mystery (a, b-1); }
Explanation / Answer
#include <stdio.h>
int mystery(int a, int b); // function prototype
int main(void)
{
int x; //first integer
int y; //second integer
printf("Enter two integers: "); //Prompts to enter 2 integers.
scanf("%d%d", &x, &y); //Reads the values into the variables x, and y.
printf("The result is %d ", mystery(x, y)); //Prints the returned value from the function mystery(x, y).
return 0;
}
/*Parameter b must be a positive integer to prevent infinite recursion*/
int mystery( int a, int b)
{
if (b == 1) //If the second variable entered is 1.
return a; //Return the first value.
else //If not.
return a + mystery (a, b-1); //Return the value returned by mystery(a, b-1) added to a.
}
//The mystery method will keep adding the values of a repeatedly for b times, and the result will be printed.
//Which means, the multiplication of a * b will be returned and printed to the screen.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.