# while loop

• 05-03-2006
newbie101
while loop
i am trying to write a while loop that computes the total of the odd numbers between 1 and 99 inclusive. i wrote this but it just lists the numbers doesnt compute them. can somebody help?

Code:

```#include <iostream> using std::cout; using std::cin; using std::endl; int main() {   int x = -1;   while ( x < 100 )   {                                     x = x + 2;                   cout << x << endl;     }   }```
• 05-03-2006
SlyMaelstrom
Quote:

Originally Posted by newbie101
i am trying to write a while loop that computes the total of the odd numbers between 1 and 99 inclusive. i wrote this but it just lists the numbers doesnt compute them. can somebody help?

Well, what in your code would make you think it would compute them?
Code:

```while(x < 100) {   x += 2;   cout << x;   total += x; } cout << total;```
• 05-03-2006
newbie101
i tried inputting this in the code but i keep getting errors. i declared total as an int but it still doesnt compute
• 05-03-2006
Quantum1024
Code:

`total += x;`
This won't compute the number of odd numbers it will add them. To get the number of Odd Numbers Just increment total each time thrugh the loop.

You could also do this without a loop.
Code:

```Odds=N/2; Odds+=N%2;```
• 05-03-2006
newbie101
ok and how do i do that? i will continue to input stuff in the code to try and figure it out.
• 05-03-2006
Quantum1024
Code:

```#include <iostream> using std::cout; using std::cin; using std::endl; int main() {   int x = -1;   int Total=0;   while ( x < 100 )   {                                     x = x + 2;           Total++;           cout << x << endl;     }   cout << Total << " Odd numbers" << endl; }```
• 05-03-2006
SlyMaelstrom
Ah my bad, I took it to mean the sum. If you want a total iteratively (for whatever reason), just increment a counter each time you loop.

Of course I don't see the point of this, since it's about the simplest thing to figure out arithmetically. If this was an assignment, tell your teacher it was a bad one.
• 05-03-2006
newbie101
thanks i almost had it right before you replied. i gave total the value of 0 and i put in total++ but i forgot the ; after the total++. thanks for the help.

now if i wanted to make this a for loop do i just change the file to for or is there more to it?
• 05-03-2006
SlyMaelstrom
Code:

```int x, total; for(x = 1, total = 1; x < 100; x += 2, total++)   cout << x << '\n'; cout << "Total: " << total << endl;```
Alot more compact, but I personally don't like multi-variable for loops, like this.
• 05-03-2006
newbie101
thanks got it, i was close but i didnt have the right syntax for the for loop. thanks again