You are here:

C++/C++ Code to print the sum of the first 10 odd natural numbers

Advertisement


Question
Respected Sir,
Kindly help me Complete the following Incomplete Code,
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i,sum;
sum=
cout<<"The Sum of the first 10 odd natural numbers is"<<endl;
for(i= ;i<=20;i=i+
sum=sum+i;
cout<<sum;
getch();
}

Answer
Hello Moonfrost

I think you need to set sum to 0 before your loop starts and you need to fix the for loop statement.
In the for loop statement, i needs to be initialized to the first natural number, which is 1, and it needs to increment by 2 after each loop iteration. Why does it need to be incremented by 2? Because you want only odd values of i to be added to the sum.

That's all I see wrong with the program and I think you have enough clues now to do the assignment yourself.

Do you understand how the for loop works ? If not, I'll explain it.
It is written like this:

for(initialization ; condition ; change)
{
  /* loop body goes here */
}

The loop starts with the initialization expression running. After each loop iteration, the change expression is run. The condition expression is checked after the initialization expression and after each time the change expression is run. That means it is checked just before the loop body is run. The loop body will run as long as the condition expression is not zero.

Good luck. Let me know if you need more help.

Best regards
Zlatko

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

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