0

I am having difficulty solving this question by using for loop (I am a beginner).

#include<stdio.h>

int main()
{    
    int a = 0, sum = 0;
    for(a=0;a<=10;sum+=a)
    {
        a++;
    }
    printf("The sum of no. from 1 to 10 is--->>%d", sum);

    return 0;
}
5
  • Did you compile this program? What output did it give? What output did you expect? Could you post the full code, including all the directives at the top of the file? Commented Oct 31, 2021 at 17:04
  • It looks like it does what you expect. Do you need help compiling and linking it? Commented Oct 31, 2021 at 17:06
  • 1
    @Neil OP's code gives 66; correct answer is 55. Commented Oct 31, 2021 at 17:15
  • Although it doesn't matter, the natural numbers start at 1, so your for loop should be 1 to 10, not 0 to 10. Commented Oct 31, 2021 at 17:23
  • Carl Gauss says not to use a loop for this. Commented Oct 31, 2021 at 17:28

1 Answer 1

3

The problem in your code is that you're adding a to sum at the end of each loop (in the iteration-statement, or the third part of the for statement). Thus, at the end of the last loop that you want to run, a will be 11 – but you add that to sum before the next a <= 10 comparison is made, preventing further iterations. So, your answer is 11 to high.

This confusion arises primarily because of your unconventional placements of the sum += a and a++ statements. Normally, in a for loop, you would have the iteration/increment expression (a++, in your case) in the for statement and the action that you want to occur each time (sum += a) inside the loop.

Thus, a slight rearrangement to the code, as follows, will solve your issue:

int main()
{
    int sum = 0;
    for (int a = 1; a <= 10; a++) { // Start at a = 1 because adding zero is pointless!
        sum += a;
    }
    printf("The sum of no. from 1 to 10 is--->>%d", sum);
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.