Skip to content
Solved Examples · Example 30

Q.Write a C program to print the sum of all odd integers between 1 and 40. The textbook presents this worked program, transcribed exactly as printed (including its printed errors):
# include <stdio.h>  
void main()  
{  
int odnum, sum=0;  
odnum=1;  
do  
{  
    sum=sum+odnum;  
    odnum=odnum+2;  
} while (odnum<=40);  
printf("sum=%4d\n", sum);  
} /*End of main()*/  
Sample output printed in the textbook:
Sum = 404  

Karnataka PUCTextbookLongImportance★★★★★est
88% · 136/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]

A do-while loop adds the odd numbers 1, 3, 5, ..., 39; their sum is 400.

The do-while is a post-test loop: the body runs once and only then is the condition tested, so the statements always execute at least once. Here odnum begins at 1 and increases by 2 each pass, generating consecutive odd numbers; the loop stops once odnum exceeds 40, after having added every odd value up to 39. A neat check is the identity that the sum of the first n odd numbers equals n squared, so 20 odd numbers sum to 400. …

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.