Recursion Printing Natural Numbers from 1 to N

preview_player
Показать описание
Link to Lecture Slides

Link to Code
Рекомендации по теме
Комментарии
Автор

As u said that stack is building on the top so in reverse code we should have 5 at the top then 4, 3, 2, 1 respectively but it wasn't like that.

lakshaymittal
Автор

sir if we try the same logic as u told us in the above program then the output of this program that i have written down should be 1 2 but the actual output is 1 1 but why
#include<stdio.h>
int n=3;
int main()
{
static int num=3;
if(--num)
{

main(--n);
printf("%d", n);
}
return 0;
}

rachitbadoni
Автор

Sir we can also use,
Int seq (int n)
{
if (n==6)
return 0;
else
printf("%d\n", n) ;
seq(n+1) ;
}
Here ?

AmanYadav-ouxi
Автор

I am bit confused about how to do obtain reverse and normal output

lakshaymittal
Автор

Sir,
When i m printing recursive functions like below:

printf("Inside main %d\n", seq(n)) ;

Its giving output as:

1
2
3
4
5
Inside main 3

I am not able to understand the above output sir.
My queries are:

1.why natural numbers are printed before inside main?
2. From where the value '3' came after inside main?

gurmindersingh
Автор

Sir when the pointer goes to the else part then it calls seq(n-1) till n becomes zero
As soon as seq (n-1) is called it goes back to function definition and does not go to the printf statement
Then why every activation record contains printf statement

malvikakunwarsen