Skip to content
Solved Examples · Example 29

Q.Write a C program to find the sum of the first n integers. The textbook presents this worked program, transcribed exactly as printed (including its printed errors):
#include <stdio.h>  
void main()  
{  
int n, i, sum=0;  
printf("Enter the value of N\n");  
scanf("%d", &n);  
i=1;  
while (i<=n)  
{  
    sum=sum+i;  
    i++;  
}  
    /* End of while */  
Printf("sum=%6d\n", sum);  
}  
    /* End of main() */  
Sample output printed in the textbook:
Enter the value of N  
6  
Sum = 21  

Karnataka PUCTextbookLongImportance★★★★★est
86% · 132/154 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

[!TLDR]

Accumulate sum = 1 + 2 + ... + n in a while loop; n = 6 gives 21.

This is the accumulator pattern with a pre-test while loop. An accumulator variable is initialised once (sum = 0) and updated on every pass (sum = sum + i), while a counter i advances from 1 to n and the condition i <= n decides when to stop. The result is printed with %6d, which right-justifies the integer in a six-character field. …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.