wiz-icon
MyQuestionIcon
MyQuestionIcon
1
You visited us 1 times! Enjoying our articles? Unlock Full Access!
Question

Consider the following C- program
void foo (int n, int sum) {
int k = 0, j = 0;
if (n = = 0) return;
k = n% 10;
j = n/10;
sum = sum + k;
foo (j, sum);
printf("%d", k);
}
int main () {
int a = 2048, sum = 0;
foo (a, sum);
printf ('&d\n", sum);
}
What does the above program print?

A
2, 0, 4, 8, 14
No worries! We‘ve got your back. Try BYJU‘S free classes today!
B
8, 4, 0, 2, 0
No worries! We‘ve got your back. Try BYJU‘S free classes today!
C
8, 4, 0, 2, 14
No worries! We‘ve got your back. Try BYJU‘S free classes today!
D
2, 0, 4, 8, 0
Right on! Give the BNAT exam to get a 100% scholarship for BYJUS courses
Open in App
Solution

The correct option is D 2, 0, 4, 8, 0
void foo(int n, int sum) {
int k = 0, j = 0;
if (n = = 0) return ;
k = n%10; j = n/10;
sum = sum +k;
foo(j, sum);
printf ("%d", k);
}
int main( ) {
int a= 2048, sum = 0;
foo(a, sum);
printf ("%d\n", sum);
}
The function foo is recursive function
When we call foo(a, sum) =foo(2048,0)
k j sum
k = 2048%10 = foo(204,8) j =204 sum = 0+8=8
foo(204.8)
k = 204%10 = 4 j =20 sum = 8+4 =12
foo(20,12)
k = 20%10 = 0 j = 2 sum = 12+0=12
foo(2,12)
k = 2% 10 = 2 j = 0 sum = 12+ 2 =14
foo(0,14) function will be terminated and value of k will print in stack way i.e.. 2, 0, 4, 8 and sum = 0. Since sum is a local variable in the main function so the print sequence is 2, 0, 4, 8, 0

flag
Suggest Corrections
thumbs-up
1
Join BYJU'S Learning Program
similar_icon
Related Videos
thumbnail
lock
Fear of the Dark
QUANTITATIVE APTITUDE
Watch in App
Join BYJU'S Learning Program
CrossIcon