If you want to add together all the odd numbers between 1 and 10 you could do something like this.
1 2 3 4 5 6 7 8 9 10 11
|
#include <iostream>
int main()
{
int total (0);
for(int number (1); number < 10; number = number + 2)
{
total = total + number;
}
std::cout<<total<<std::endl;
}
|
Alternatively, you could use the following which is more of a extendible solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
int main()
{
int lowerBound(1);
int upperBound(10);
int total(0);
for(int number (lowerBound); number <= upperBound; ++number)
{
if(number%2 == 1)
{
total += number;
}
}
std::cout<<total<<std::endl;
}
|
A couple of other things about your example code:
using namespace std;
can be convenient, but it is a bad habit to get into as it can make things more confusing and actually more difficult in larger projects, it should only be used in small projects and never in header files.
Postfix increment is made for a very specific job, which is for the number to be operated upon, and then incremented. Prefix increment is more appropriate for for loops.
You say between 1 and 10, yet you start your for loop at 0 and end it at 9
You don't need to declare a variable before the for loop, if you are going to redeclare it in the start of the loop. Either declare numbers before the loop and just use
numbers = 0
, or preferably only declare it in the for statement.