Thursday, January 15, 2009

3rd- Learnings of the Week 6 [Caligdong]

SAMPLE PROBLEMS:

EXAMPLE 1 (INDIRECT RECURSION)
Give the output of the ff. program when the value entered for a=5.

#include
main()
{
int a, b; clrscr();
printf(“Enter a value:”); scanf(“%d”, &a);
b= solve (a); printf(“The new value is %d”, b);
getch();
}

solve (int a)
{
int b;
if ( a==1)
{
b=2; printf (“%d” , b); return b;
}
else {
b=solve2 (a-1) + 2;
printf (“%d”, b);
return b;
} }
solve2 (int a)
{
int b;
if (a == 1)
{
b=2;
printf (“%d”, b);
return b;
}
else
{
b=solve (a-1) +2;
printf (“%d “, b);
return b;
}


SAMPLE RUN(EXAMPLE 1):

Enter a value:5
2 4 6 8 10


By tracing the program when a=5…

a=5, solve2 (5-1) + 2 general case
a=4, solve (4-1) + 2 general case
a=3, solve2 (3-1) + 2 general case
a=2, solve (2-1) + 2 general case
a=1 2 base case

By simplifying the program when a=5…

a=5, solve2 (5-1) + 2 = 10 general case
a=4, solve (4-1) + 2 = 8 general case
a=3, solve2 (3-1) + 2 = 6 general case
a=2, solve (2-1) + 2 = 4 general case
a=1 2 base case

Therefore, when a=5 the values 2 4 6 8 10 will be printed on screen.



EXAMPLE 2(PASS BY VALUE):
Example:
#include
main()
{
clrscr();
x=10;
y=5;
printf(“%d %d\n”, x,y);
pass (&x,&y);
printf(“%d %d\n”,x,y);
getch();
}
pass (int *a, int *b)
{ *a=*a+5;
*b=*b*2;
printf(“%d %d \n”,*a,*b);}

Sample Output:

10 5
15 10
15 10

No comments: