Compiler Errors including initializer before '<' token

61 views Asked by At

I am writing this piece of code for one of the Project Euler puzzles to practice coding and I am having trouble with what I think are a couple syntax errors. What am I doing wrong here?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int smallestMultiple = 10000;
    int sum = 1;

    for (int i = 100, i < smallestMultiple, i+2)
    {
        for (int j = 20, j >=10, j--)
        {
            sum = sum + (i % j);

        }

        if (sum == 1)
        {
            smallestMultiple = i;
        }

        else 
        {
            sum = 1;
        }
    }

    cout<< "The smallest number easily divisible by the numbers 1 to 20 is " << smallestMultiple << "." << endl;
}

I received the below errors when I tried to compile this code. What type of syntax am I missing?

smallMultiple.cpp:6: error: expected ‘;’ before ‘int’
smallMultiple.cpp: In function ‘int main()’: 
smallMultiple.cpp:12: error: expected initializer before ‘<’ token
smallMultiple.cpp:32: error: expected primary-expression at end of input
smallMultiple.cpp:32: error: expected ‘;’ at end of input
smallMultiple.cpp:32: error: expected primary-expression at end of input
smallMultiple.cpp:32: error: expected ‘)’ at end of input
smallMultiple.cpp:32: error: expected statement at end of input
smallMultiple.cpp:32: error: expected ‘}’ at end of input
2

There are 2 answers

1
Miguel Hernando On BEST ANSWER

The sintaxis of for uses ; to differentiate the three expressions (initialization, condition, and update) therefore you should write:

for (int i = 100; i < smallestMultiple; i+=2)

instead of:

for (int i = 100, i < smallestMultiple, i+2)

if you wanted to iterate i from 100 to smallestMultiple with increments of 2

0
Mureinik On

There are several issues here:

  1. The parts of a for loop should be delimited by a semi-colon (;), not a comma (,)
  2. In the first for loop, i + 2 is not stored anywhere. Assuming you meant to add 2 to i's value, you should use i+=2.

So, in conclusion, your for loops should look like:

for (int i = 100; i < smallestMultiple; i+=2)
{
    for (int j = 20; j >=10; j--)
    {
        // rest of the code