ahmed nabil
ahmed nabil

Reputation: 11

Why does this recursive sum function not work correctly?

There is this Mario problem in the CS50 course and it's easy using the recursion method, except that when I try to add any arithmetic operation it shows (invalid operands to binary expression ('void' and 'int')). It's just for the sake of me to understand what I can do using recursion and what I can't; the problem is this line (sum(n-1)+n;)

Here is the code:

#include <cs50.h>
#include <stdio.h>

void sum(int n);

int main ()
{
    int u = get_int("f");
    sum (u);
}

void sum(int n)
{
  if (n==0)
  {
    return;
  }
  sum(n-1)+n;
  for(int i = 0 ; i < n; i++)
  {
    printf( "#");
  }
  printf("\n");
}

Upvotes: -1

Views: 218

Answers (3)

Michail
Michail

Reputation: 1

mario problem can be wrote recursive here is my solution

def main():
    while True:
        try:
            height = int(input("Height: "))
            if height > 8 or height < 1:
                raise ValueError
            else:
                break
        except ValueError:
            pass

    draw_pyramide(height, height)


def draw_pyramide(n, z):
    if n == 0:
        return

    draw_pyramide((n-1), z)
    print(" " * (z - n), end='')
    for i in range(n):
        print("#", end='')
    print(" " * 2, end='')
    for i in range(n):
        print("#", end='')
    print()


main()

Upvotes: 0

Ziv
Ziv

Reputation: 11

The error you are seeing is from this line:

sum(n-1)+n;

sum is a function that returns void, but you are trying to add it with an integer n.

I am not quite sure what that get_int("f") does, but I assume it's prompting to the user for an int input, and you are trying to sum from 0 to that number. Here is the solution:

int sum(int n) // Here is the critical change to your code, now it returns an int
{
  if (n == 1) // Root case that will stop the recursion, otherwise, it's endless
    return 1; // 1 = 1 + 0;

  return sum(n-1) + n; // Recursion
}

Think about what we are trying to achieve here. We want to add from 0 to n, or to say from n to 0 downwards. If n is 3, it's going to be 3+2+1+0, and you'll notice that 3 is just n, and 2 is n - 1, 1 is (n - 1) - 1, etc. To visualize it:

  1. before sum(3) could return anything, it calls sum(2) + 3;
  2. before sum(2) could return anything, it calls sum(1) + 2;
  3. 1 is our root case, and there is no more calls, so sum(1) is going to return 1;
  4. that 1 is returned to step 2, so sum(1) + 2 becomes 1 + 2, which is 3, and that is the value sum(2), and it returns its result to step 1, and step 1 becomes 3 + 3, which is 6, and the initial call to sum is then completed.

I hope that makes sense to you. Recursion is not an easy technique to master. Take your time, but you need to understand how function calls work in memory. Here is a video that illustrates how recursive calls in memory look like, Data Structures Using C++: Illustration of Recursive Function Calls (Call Stack).

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

It is because the return type of the function sum() is void.

You cannot add anything to void.

Anyway the result of the "addition" is thrown away, so you won't need addition.

This mean that sum ( n-1)+n; should be replaced with sum ( n-1);.

Upvotes: 0

Related Questions