3

I'm going through "C++ Primer 5th Edition" as recommended via this site. I'm stepping through For and While loops and have come to the conclusion that they're virtually the same. At least that's what I've gathered. I think someone explained it the best when they said "For loops are for when you know how many times you want to loop and while loops are for when you want to loop until a condition is met." But essentially, the compiler doesn't differentiate between the two and that they can be used interchangeably.

The book presented this code (which doesn't to even work the way the explained it):

<iostream>

int main()
{

int sum = 0, value = 0;
// read until end-of-file, calculating a running total of all values read

while (std::cin >> value)   {
sum += value; // equivalent to sum = sum + value
std::cout << "Sum is: " << sum << std::endl;
return 0;

    }
}

The attached exercise said to "Write your own version of a program that prints the sum of a set of integers read from cin." I'm assuming they want me to use the For loop. So I tried doing that. I am having a hard time though.

The book said "The For loop is made up of an initstatement, condition and an expression. In the while loop, "std::cin >> value" was my condition and there was no expression. So how am I supposed to use a for loop if all I have is an initstatement and a condition?

#include <iostream>


int main()

{
int sum = 0;

for (int value = 0; std::cin >> value; "EXPRESSION GOES HERE")
    sum += value;
std::cout << "The sum is: " << sum << std::endl;
return system("pause");
}
Bit Deception
  • 297
  • 1
  • 3
  • 7
  • Remember that *any* part of the `for` expressions can be empty. – Some programmer dude Jul 24 '13 at 18:00
  • Side note: practice is for loop we use when we know *number of iterations*, while we prefer where *break on certain condition*. – Grijesh Chauhan Jul 24 '13 at 18:00
  • 3
    @Grijesh: No, a for-loop is where you have a "initialization", "condition" and "update" step that you need in every loop. E.g. a linked list can be iterated over with `for(T *p = head; p; p = p->next) ...` - we don't know how many by some count, just that when it reaches zero is finished. Dividing down a number to get it's digits can be done as `for(int x = n; x; x /= 10) ...`, etc. – Mats Petersson Jul 24 '13 at 18:03
  • In case you are wondering why the supplied sample doesn't work (properly): the `return 0;` is inside the while-loop. Examples with glaring errors? Not very nice. – Jongware Jul 24 '13 at 20:33

4 Answers4

4

Err, you can write any while loop as a for loop by replacing while(...) with for(;...;)...

for (;std::cin >> value;)   {

}

Nothing about the code you posted suggests a for loop though. Generally you'll use a for loop when you actually want to count something, or iterate over a collection. Your intent is just to loop until a condition is met, so that pretty much screams while, not for.

I guess if I had to write this "correctly" with a for loop, I might use something like this:

int sum = 0;
for (int i = 0; std::cin >> i; sum += i); // empty loop body
std::cout << sum << std::endl;

Though, I'd be more likely to use a while loop which is more semantically correct.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • Oh, ok. I thought I was confined to using the "for (initstatement, condition, expression)" format. Thanks! – Bit Deception Jul 24 '13 at 18:02
  • You are, but any of the three parts can be empty. `for(;;)` is a common way of writing a "forever" loop that never terminates until something within the loop invokes a `break` or `return` or `throw`. – user229044 Jul 24 '13 at 18:03
  • 1
    I meant that I thought I had to use all three parts. The book wasn't specific on if I could leave parts out. Now I understand. – Bit Deception Jul 24 '13 at 18:06
1

The important thing to the answer is that you can leave every part of the for expression out, e.g.

for (;;) break;

Would be valid code.

Also I suggest putting a C++ book aside and going back to C in this case, as loop semantic basics are the same for both, and C is by far simpler.

Edit: Complete solution for your problem could be something like:

#include <iostream>


int main()

{
int sum = 0;

for (int value = 0; std::cin >> value; sum+= value); 

// alternative version, a bit easier to read probably:
// for (int value = 0; std::cin >> value;) sum+= value;

std::cout << "The sum is: " << sum << std::endl;
return system("pause");
}
griffin
  • 1,261
  • 8
  • 24
1

a while loop as a for

{
  int i = 0;
  while( i < limit){
         //do stuff
         i++;
   }
}

Keep the scope operators to trash out the iterating variable when the loop is done.

theta
  • 179
  • 11
0

Sometimes the code just looks neater with one rather than the other. Consider two scenarios;

std::vector<double> myVector;
typedef std::vector<double>::iterator dblIter;
dblIter curr = myVector.begin();
dblIter end = myVector.end();

while(curr != end)
{
    // do stuff
    ++curr;
}

Or;

std::vector<double> myVector;
typedef std::vector<double>::iterator dblIter;

for(dblIter curr = myVector.begin(); curr != myVector.end(); ++curr)
{
    // do stuff
}

I happen to prefer option 2, despite comments that say "use for when you know the number of iterations". I guess it applies as a general rule.

Steztric
  • 2,832
  • 2
  • 24
  • 43