C/algorithm confusing
Expert: Abhishek Kumar - 1/2/2012
QuestionHello!, I need some help from you, this is my c coding:
main()
{
int n;
int sumn=0;
for(n=3; n<=15; )
{printf("%d\n",n);
n=n+3;
sumn=sumn+n;}
printf("%d\n",sumn);
return 0;
}
I want the sumn to be 45 as 3+6+9+12+15 is 45 but the display is sumn is 60. Can you give a clue why?
Thanks in advance.
AnswerHi Nia,
If you see closely you will see that your program is doing something like :
sum=6 n=6
sum=15 n=9
sum=27 n=12
sum=42 n=15
sum=60 n=18
60
Initially,
n=3
1.It checks this condition n<=15 => True
so n becomes 6 and sumn= 0 + 6 =6
2. again 6 <= 15 (n<=15) => True
so n becomes 9 and sumn = 6 + 9 = 15
3. again 9 <=15
so n becomes 12 and sumn = 15 + 12 = 27
4. again 12 <=15
so n becomes 15 and sumn = 27 + 15 = 42
3. again 15 <=15
so n becomes 18 and sumn = 42 + 18 = 60
And that is why you are getting 60
And if you change your for loop to something like this:
for(n=3; n<15; ) in this case your answer will be 42 and not 45 because you are increasing n first and after that you are adding it to sumn. So, you n becomes 6 when you add it for the first time to sumn.
To get the desired result you have to change the order of incrementing n and adding it to sumn.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
int sumn=0;
for(n=3; n<=15; )
{
sumn=sumn+n;
n=n+3;
}
printf("%d\n",sumn);
system("pause");
return 0;
}
This program will return 45.
sum=3 n=6
sum=9 n=9
sum=18 n=12
sum=30 n=15
sum=45 n=18
Answer=45
Regards,
Abhishek Kumar