S
somenath
Hello All,
I am very much confused with the output of the two following programs.
First program
==================
#include<stdio.h>
void printd(int n)
{
printf("\beginning n = %d\n",n);
if (n/10) {
// n = n/10;
printd(n/10);
}
printf("%c ",((n%10)+'0'));
}
int main(void)
{
printd(123);
putchar('\n');
return 0;
}
Output
../a.out
beginning n = 123
beginning n = 12
beginning n = 1
1 2 3
Second program
#include<stdio.h>
void printd(int n)
{
printf("\beginning n = %d\n",n);
if (n/10) {
n = n/10;
printd(n);
}
printf("%c ",((n%10)+'0'));
}
int main(void)
{
printd(123);
putchar('\n');
return 0;
}
Output
==============================
beginning n = 123
beginning n = 12
beginning n = 1
1 1 2
The only difference between the two program is as follows
In the first program printd is called with n/10 as argument but in the
latter after computing n=n/10 printd is being called recursively .
Then why the two program output differently?
So my understanding for this different behaviour as follows.
In case of second program the n=n/10 is changing the original n which
was pushed to stack . That is
For printd(123) n is modified to 12
For printd(12) n is modified to 1
so when if (n /10 ) fails it prints 1(1%10 = 1) , then for the call
printd(12) , prints 1 (as n which was 12 but latter modified to 1
so 1%10 =1 ) then similarly it print 12%10 2 for call printd(123)
Please let me know if my understanding is correct ? Please provide
some inputs.
I am very much confused with the output of the two following programs.
First program
==================
#include<stdio.h>
void printd(int n)
{
printf("\beginning n = %d\n",n);
if (n/10) {
// n = n/10;
printd(n/10);
}
printf("%c ",((n%10)+'0'));
}
int main(void)
{
printd(123);
putchar('\n');
return 0;
}
Output
../a.out
beginning n = 123
beginning n = 12
beginning n = 1
1 2 3
Second program
#include<stdio.h>
void printd(int n)
{
printf("\beginning n = %d\n",n);
if (n/10) {
n = n/10;
printd(n);
}
printf("%c ",((n%10)+'0'));
}
int main(void)
{
printd(123);
putchar('\n');
return 0;
}
Output
==============================
beginning n = 123
beginning n = 12
beginning n = 1
1 1 2
The only difference between the two program is as follows
In the first program printd is called with n/10 as argument but in the
latter after computing n=n/10 printd is being called recursively .
Then why the two program output differently?
So my understanding for this different behaviour as follows.
In case of second program the n=n/10 is changing the original n which
was pushed to stack . That is
For printd(123) n is modified to 12
For printd(12) n is modified to 1
so when if (n /10 ) fails it prints 1(1%10 = 1) , then for the call
printd(12) , prints 1 (as n which was 12 but latter modified to 1
so 1%10 =1 ) then similarly it print 12%10 2 for call printd(123)
Please let me know if my understanding is correct ? Please provide
some inputs.