C++/C++ Code to print the sum of the first 10 odd natural numbers
Expert: Zlatko - 6/29/2010
QuestionRespected 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();
}
AnswerHello 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