display sum of odd number between 1 and 10 using a FOR loop

display sum of odd number between 1 and 10 using a FOR loop

1
2
3
4
5
6
7
8
9
10

#include <iostream>
using namespace std;
int main()

{
	int numbers;
	for (int numbers = 0; numbers < 10; numbers++)



i stucked here , what should i do . just got in c++ about 1-2 weeks . not very good on it , can anyone explain too ?

thanks
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.
hi , i taking programming so our lecturer told us to add using namespace std;
alright , thanks for the help .
will post again if i meet some question .

i found out i did wrong as i read the question wrongly .

should be : number <=10 .
Topic archived. No new replies allowed.