Why is my for loop giving a ‘;’ expected error?

0
28
Asked By CuriousCoder99 On

I'm a complete beginner and I'm having trouble compiling my program because I'm getting an error that says a semicolon is expected on my for loop statement. Here's the code I'm working with:

```cpp
#include
using namespace std;

int main() {
for (int i = 0, i < 10, i++) { // VS wants ; on this line
cout << i << endl;
}
}
```

I've learned from w3schools that there shouldn't be a semicolon at the end of the parentheses. Can someone help me understand what's going wrong?

2 Answers

Answered By CodeExplorer86 On

You're definitely not alone in this! Just to clarify, the semicolon is needed to separate the initialization, condition, and increment in the for loop. Using commas will lead to a syntax error. Here’s a breakdown:
- The first part initializes your variable.
- The second part is the condition.
- The third part is the increment.

Properly formatted, it should look like this:
```cpp
for (int i = 0; i < 10; i++) {
cout << i << endl;
}
```
This way, your code will compile just fine!

Answered By SyntaxSleuth42 On

It looks like the compiler is correct, and the syntax of your for loop needs some tweaking. You should actually use semicolons to separate the different parts of the for loop. The format should look like this:

```cpp
for (int i = 0; i < 10; i++) {
cout << i << endl;
}
```

So, replace the commas in your for statement with semicolons, and that should fix your problem!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.