I'm working on this loop where i can add all odd integers. (ex: 1 + 3 + 5 + 7 = 16) I have to make sure any input value from 1-10000 will work. I don't know the next step and any hints or advice would be helpful. Thanks!
#include <iostream>
#include <conio.h>
#include <cmath>
using namespace std;
int main ()
{
int i = 1;
int sum = 0;
int howmany;
cout << "How many odd integers do you want to add? ";
cin >> howmany;
while (i <= 10000)
{
sum = sum + i;
i++;
}
cout << "The sum of the first " << howmany << " odd integers is " << sum << endl;
I'm a beginner, and I haven't had a chance to compile this and test it, but try this instead of the while loop you have now:
1 2 3 4 5 6
if (howmany >= 1 && howmany <= 10000){
for (n = howmany; n > 0; n--){
sum += i;
i += 2;
}
}
EDIT: Tested it, appears to work. Interestingly enough, the sum of n odd numbers equals n^2. I'm sure there's a good mathematical explanation for it, but I was surprised to see it.
sum = i*(i+1)/2 + (i-1)*i/2;
//or simply
sum = i*i;
sum = i*i;
what??? so simple like this! XD
EDIT: here is the complete code for that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
int main(){
int howmany, sum;
while(true){
std::cout << "\nHow many odd integers do you want to add? ";
std::cin >> howmany;
if(howmany > 0 && howmany <= 1000)
break;
else
std::cout << "\nPlease enter number from 1 to 1000 only"<<std::endl;
}
sum = howmany*howmany;
std::cout << "The sum of the first " << howmany << " odd integers is " << sum << std::endl;
return 0;
}