In general, in a recursive and non-recursive implementation of a problem (program) :
Both time and space complexities are better in non-recursive than in recursive program.
Every recursive call pushes an activation record (parameters, return address, locals) on the stack, which costs extra memory proportional to the recursion depth.
The calls and returns also add time overhead, while an iterative loop reuses the same frame.
So in general the non-recursive version is better in both time and space, although recursion may be simpler to write.
Hence, Both time and space complexities are better in non-recursive than in recursive program.
Consider the function in C code :
Cal(a, b) {
if (b != 1) {
if (a != 1) {
printf("*");
Cal(a/2, b);
}
else {
b=b-1;
Cal(10, b);
}
}}
How many times * is going to be printed, if the function is called with Cal(10, 10); ?
Consider the following C code :
#include<stdio.h>
int temp=0;
int fun(int x, int y)
{
int z; temp++;
if (y==3) return(x*x*x);
else {
z=fun(x, y/3);
return(z*z*z);
}
}
int main()
{
fun(4, 81);
printf("%d", temp);
}
What will be the output of the above code ?
#include <stdio.h>
int foo(int S[], int size){
if(size == 0) return 0;
if(size == 1) return 1;
if(S[0] != S[1]) return 1 + foo(S + 1, size - 1);
return foo(S + 1, size - 1);
}
int main(){
int A[] = {0, 1, 2, 2, 2, 0, 0, 1, 1};
printf("%d", foo(A, 9));
return 0;
}
The value printed by the given C program is _______ . (Answer in integer)
int func(int start, int end){
int length=end+1-start;
if((length < 1)||(start < 0)||(end < 0)){ return(0); }
if(length%3==0){
return(func(start+1, end));
} else if(length%3==1){
return(1+func(start, end-1));
} else {
return(func(start+2, end));
}
}What is the output of the given C language code snippet?
#include<stdio.h>
void f(int n)
{
if(n==0)
return;
printf("%d ",n);
f(n-1);
}
int main()
{
f(3);
return 0;
}
int bar(int n){
if (n == 1) return 0;
else return 1 + bar(n/2);
}
int foo(int n){
if (n == 1) return 1;
else return 1 + foo(bar(n));
}