0

i have this code and its output is 54. my question is, can someone please explain to me the process of getting this certain output, which is said to be 54. thank you. :)

#include<stdio.h>
#include<conio.h>

int sumS (int n, int m);

void main ()
{
	int x=2, y=5;
	clrscr();
	printf("%d", sumS(x, y));
	getch();
}

int sumS (int n, int m)
{
	if (n==m)
		return n*m;
	else
		return (n*n) + sumS (n+1, m)
}

Edited by Nick Evan: Added CODE-tags

3
Contributors
7
Replies
9
Views
6 Years
Discussion Span
Last Post by Shankye
0

if you understand Recursion then it's quite easy to understand this program..

return n*n + n*n + n*n + n*m
or
return 2*2 + 3*3 + 4*4 + 5*5

0

@vinitmittal2008 but where did you get those? (the idea of the formula)

0

Those are not formula ..
U need to understand program flow, how actually program runs and how decisions are made in its way ..
Hope Vinit 'll agree with me ...

0

Yup ..
Go on checking step by step how the program flows..

See your values are
x=2 and y=5

When main calls sumS
n=2 and m=5
which are not equal
so else block executed
which returns n*n + again call to sumS with 3 and 5
3 and 5 are not equal so (n+1)*(n+1) + again call to sumS with 4 and 5 and so on
Which ends when 5=5 with returning only 5*5

so finally your result will contain

n*n + (n+1)*(n+1) + (n+2)*(n+2) and so on till n=m ...

2*2 + 3*3 + 4*4 + 5*5 = 54 ...

Hope its clear

0

Yup ..
Go on checking step by step how the program flows..

See your values are
x=2 and y=5

When main calls sumS
n=2 and m=5
which are not equal
so else block executed
which returns n*n + again call to sumS with 3 and 5
3 and 5 are not equal so (n+1)*(n+1) + again call to sumS with 4 and 5 and so on
Which ends when 5=5 with returning only 5*5

so finally your result will contain

n*n + (n+1)*(n+1) + (n+2)*(n+2) and so on till n=m ...

2*2 + 3*3 + 4*4 + 5*5 = 54 ...

Hope its clear

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.