What is the output of the following program? #include <iostream> using namespace
ID: 3556047 • Letter: W
Question
What is the output of the following program?
#include <iostream>
using namespace std;
int myFunction(int);
int main() {
int x = 10;
cout << myFunction(x)<<endl;
return 0;
}
int myFunction(int num) {
if (num < 0)
{
cout<< Error: myFunction called with invalid argument;
return 0;
}
else if (num = = 0)
return 0;
else
return myFunction(num - 1) + num;
}
Explanation / Answer
#include <iostream>
using namespace std;
int myFunction(int);
int main() {
int x = 10;
cout << myFunction(x)<<endl;
return 0;
}
int myFunction(int num) {
if (num < 0)
{
cout<< "Error: myFunction called with invalid argument";
return 0;
}
else if (num == 0)
return 0;
else
return myFunction(num - 1) + num;
}
myFunction(10) = 10 + myFunction(9)
= 10 + 9 + myFunction(8)
= 10 + 9 + 8 + myFunction(7)
= 10 + 9 + 8 + 7+ myFunction(6)
= 10 + 9 + 8 + 7+ 6 + myFunction(5)
= 10 + 9 + 8 + 7+ 6 + 5 + myFunction(4)
= 10 + 9 + 8 + 7+ 6 + 5 + 4 + myFunction(3)
= 10 + 9 + 8 + 7+ 6 + 5 + 4 + 3 + myFunction(2)
= 10 + 9 + 8 + 7+ 6 + 5 + 4 + 3 + 2 + myFunction(1)
= 10 + 9 + 8 + 7+ 6 + 5 + 4 + 3 + 2 + 1 + myFunction(0) now myFunction(0) returns 0 recursion breaks;
= 10 + 9 + 8 + 7+ 6 + 5 + 4 + 3 + 2 + 1 + 0
= 55 IS ANSWER.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.