-3

why do we not have multiple initialization in for loop? we do have multiple increment statements.

code:

for(int i=1,int c=4;i<1;i++)
  System.out.println(c);

This code shows a compile time error.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
CoderBrain
  • 103
  • 1
  • 11
  • 3
    Wrong syntax: `for (int i=1, c=4; i < 1; i++)` – sp00m Aug 14 '14 at 09:47
  • 1
    Yes, you can have multiple increment statements like `i++, c++` but not `i + 1, c + 1` which lies in the nature of transforming a for loop into "normal" code. – Smutje Aug 14 '14 at 09:48
  • possible duplicate of [Java: Initialize multiple variables in for loop init?](http://stackoverflow.com/questions/3542871/java-initialize-multiple-variables-in-for-loop-init) – Tom Jonckheere Aug 14 '14 at 09:49
  • WHAT error? Your compiler usually gives a detailed error message, it is very helpful for others if you copy and paste these error messages verbatim when asking a question! (And sometimes, you may even answer the question yourself...) – Gyro Gearless Aug 14 '14 at 09:49
  • but it's sad that `for (int i, char c; ...` is not working, in such cases I use `while`... – Betlista Aug 14 '14 at 09:54

2 Answers2

6

You are using wrong syntax. You can use this way

  for(int i=1, c=4;i<1;i++)
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
2

If by "have multiple increment statements" you mean e.g.

for(int i=1, c=4;i<1;i++,c++)
//                   ^   ^
//                   |   |
// Multiple increment expressions

First of all, they are expressions and not statements. Secondly, i++,c++ is one expression, using the comma operator to separate two sub-expressions.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621