Reputation: 11
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
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
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:
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
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