You are here:

C/algorithm confusing

Advertisement


Question
Hello!, 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.

Answer
Hi 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  

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Abhishek Kumar

Expertise

I can answer questions related to basic concepts , arrays , expressions , pointers and queries related to coding .

Experience

I have done my bachelors in Computer Science. For past 5 years i have been working in c , and i have good command over most of the areas of C Language.

Education/Credentials
I did my Bachelors in Computer Science and Engineerin .

Awards and Honors

©2012 About.com, a part of The New York Times Company. All rights reserved.