Define a recursive function named add-nums that adds up the numbers N, N-1, N-2, and so on,
down to 0, and returns the sum. (add-nums 4) should compute 4 + 3 + 2 + 1 + 0 which is 10.
Solution
#include
int add_nums(int n){
if(n == 0){
return 0;
}
else{
return n + add_nums(n - 1);
}
}
int main()
{
int result = add_nums(4);
printf("Result is %d ", result);
return 0;
}
Output:
sh-4.2$ gcc -o main
*.c
sh-4.2$
main
Result is 10

Define a recursive function named add-nums that adds up the numbers N.pdf

  • 1.
    Define a recursivefunction named add-nums that adds up the numbers N, N-1, N-2, and so on, down to 0, and returns the sum. (add-nums 4) should compute 4 + 3 + 2 + 1 + 0 which is 10. Solution #include int add_nums(int n){ if(n == 0){ return 0; } else{ return n + add_nums(n - 1); } } int main() { int result = add_nums(4); printf("Result is %d ", result); return 0; } Output: sh-4.2$ gcc -o main *.c sh-4.2$ main Result is 10