A small correction, you want it to return from N to 0 and not from 0 to N, since you are decreasing recursively, if you really want to go from 0 to N I change the code.
Another thing you forgot is that you’re not printing the numbers, you’re just giving Return, IE, it performs all the calculation but does not print.
Another observation is that if you want to start from 0 then you have to change 1 for zero in your first if:
#include<stdio.h>
int imprimenumeros(int n){
printf("%d\n", n );
if (n==0){
return 0;
}
else {
return imprimenumeros(n-1);
}
}
void main (){
int n;
int y;
printf("digite um numero\n");
scanf("%d", &n);
imprimenumeros (n);
}
Now if you really want to increment from 0 to a given N, just pass your initial variable "in this case is 0" along with your terminal variable "which in this case is N" and increment recursively:
#include<stdio.h>
int imprimenumeros(int n, int y){
printf("%d\n", y);
if (n>y){
return imprimenumeros(n, y+1);
}
else {
return 0 ;
}
}
void main (){
int n;
int y = 0;
printf("digite um numero\n");
scanf("%d", &n);
imprimenumeros (n, y);
return 0;
}
first puts the code, then selects it all and presses Ctrl+k that it formats for you, at first I would curl up to put code here but this way is the simplest.
– Raul Sena Ferreira
Thanks for the tip!
– Lucy
I’m already writing the answer for you, it’s very simple, you missed one small detail
– Raul Sena Ferreira
I didn’t understand, because when I type 1 the result is 0 and 1, when I type 2 the result is 0, 1 and 2. The exercise asked you to tell me if the number is prime or not.
– André