-3

I just want to clarify what's the difference between these syntax of for loop.

for (int ctr = 0; ctr < x.length; ctr++)
    x[ctr] += 5;

for (int ctr = 0; ctr < x.length; ctr++) {
    x[ctr] += 5;
}
Turing85
  • 18,217
  • 7
  • 33
  • 58
  • 1
    Both will do the same thing in this case, but you should always use the brackets because it prevents from errors and it's more readable. – Alexis C. Apr 21 '15 at 17:48
  • No difference. But it's only recommended to omit the braces (and replace by `;`) in case the body of the statement is empty, otherwise they should be included. – Bubletan Apr 21 '15 at 17:51
  • @AlexisC. what will i do now? I'm sorry I didn't know this was asked already. Should i delete this? – matinik estugante Apr 21 '15 at 17:53
  • @matinikestugante No worries, you can either let your question or delete it if you wish. I marked it as duplicate so that it helps to "centralize" some common questions that have already been asked and that you didn't find it while searching :) – Alexis C. Apr 21 '15 at 17:55

3 Answers3

0

No difference. When you have only one instruction in the loop body, you can ommit the brackets.

Dici
  • 25,226
  • 7
  • 41
  • 82
0

There is no difference in this situation , since you have only one instruction inside that for loop , you can skip the brackets.

But its a good practice to always put the brackets to help making your code easier to read so you wouldn't get confused in more complex algorithms.

vlatkozelka
  • 909
  • 1
  • 12
  • 27
0

There is no difference as far as the output is concerned. Java (and may other languages) allow you to skip the braces if only one statement is to be executed inside the loop.

However, it is recommended to add the braces for readability & maintenance purposes.

mbsingh
  • 499
  • 10
  • 26