-6

This is example for my looping code:

int outsideLoop = 0;
for (int i = 1; i < 11; i++)
{
    outsideLoop += i;
    System.out.println("Count is: " + i);
}
System.out.println("Outside loop is: " + outsideLoop);

My friend is said that using int i = 1; i < 11; i++ is a primitive ways. is there any quick way to looping than to use this code?

Dita Aji Pratama
  • 710
  • 1
  • 12
  • 28
  • What do you mean by "primitive"? There is nothing wrong with using `int` but your variable `outsideLoop` is confusing me, you should rename it to something like `loopCount`. – px06 Oct 12 '16 at 08:24
  • 2
    I am not sure what the deal is. Maybe you should ask your "friend" what is so bad about "primitive" ... – Fildor Oct 12 '16 at 08:24
  • 4
    Don't talk to this friend ever again. – AhmadWabbi Oct 12 '16 at 08:24
  • as far as i am concerned, I feel that the way you are doing it is the fastest and the best way – Blip Oct 12 '16 at 08:25
  • 3
    That is how a for loop works. Maybe you friend is referring to for-each loop syntax, like `String someArray[] = ... ; for (String str : someArray)` which doesnt need a loop counter any more. But when you want a **for** loop to count something, then you have to use a for loop that counts something. Other languages might have more elegant ways to write that down, but not Java. – GhostCat Oct 12 '16 at 08:25
  • If your "friend" was aiming towards Bathsheba's closed-form solution, then you should demand that he stops talking in riddles. "Your solution is crap" is not particularly helpful. – Fildor Oct 12 '16 at 08:29
  • @GhostCat did you have a example to use `for (String str : someArray)`? – Dita Aji Pratama Oct 12 '16 at 08:39
  • The example is already there. someArray is well, some array, that you somehow need to initialize. And hint: there are *search* engines out there. You go there, and you type words like "java for each loop"; and guess what, there will be tons and tons and tons of links with examples. – GhostCat Oct 12 '16 at 08:40
  • @GhostCat Thanks, it's helping. I think this is an answer. http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work – Dita Aji Pratama Oct 12 '16 at 08:47

1 Answers1

3

A good friend would tell you that there is a closed-form solution for outsideLoop. In other words, there's no need to use a for loop at all, which saves computation time.

outsideLoop = n * (n + 1) / 2, where, in your case, n is 10.

This comes from the sum of an arithmetic progression.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483