What is the output of the following program? #include <iostream> using namespace
ID: 3556046 • 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) = myFunction(9) +10
= myFunction(8) + 9 + 10
= myFunction(7) + 8 + 9 + 10
= myFunction(6) + 7 + 8 + 9 + 10
= myFunction(5) + 6 + 7 + 8 + 9 + 10
= myFunction(4) + 5 + 6 + 7 + 8 + 9 + 10
= myFunction(3) + 4 + 5 + 6 + 7 + 8 + 9 + 10
= myFunction(2) + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
= myFunction(1) + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
= myFunction(0) + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 now myFunction(0) returns 0 recursion breaks;
= 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
= 55 IS ANSWER.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.