software keeps suggesting I use a comma??

I have a question that asks to compute the sum of the squares of the first fifty numbers and store them in a variable integer called total using a for statement. This is what I am trying to use, but I don't understand why I keep getting the semicolon error.

 
  for (k = 1; total = 0; k <= 50; total += k*k; k++)
You have 4 semicolons - syntax for the for loop calls for 2. I pulled this from the tutorial page on this site - it shows how commas can be used in a for loop.

from http://www.cplusplus.com/doc/tutorial/control/

The for loop is designed to iterate a number of times. Its syntax is:

for (initialization; condition; increase) statement;


Because each of the fields is executed in a particular time in the life cycle of a loop, it may be useful to execute more than a single expression as any of initialization, condition, or statement. Unfortunately, these are not statements, but rather, simple expressions, and thus cannot be replaced by a block. As expressions, they can, however, make use of the comma operator (,): This operator is an expression separator, and can separate multiple expressions where only one is generally expected. For example, using it, it would be possible for a for loop to handle two counter variables, initializing and increasing both:


1
2
3
4
for ( n=0, i=100 ; n!=i ; ++n, --i )
{
   // whatever here...
}

Last edited on
Thanks, it was looking for this, with no brackets:

total = 0;
for (k = 1; k <= 50; k++)
total += k*k;
Topic archived. No new replies allowed.