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");
}