Can anybody explain below method 👇🏽
for (int i=0; i <3; i++)
Don't think taught something like this till now..
Pls explain this
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
proegg123
29 September 2021, 08:59
This is a "for loop" - basically you create a loop where you want something to happen multiple times. In this case you want whatever you have in the loop to happen 3 times.
In the brackets you initialise a variable (int i = 0), then you put a condition that will be evaluated at every new loop run (in this case i < 3) and then you increment i by one (i++).
If you want to print "Hello" three times and use a for loop to achieve that it would work like this :
for (int i = 0; i < 3; i++) {
System.out.println("Hello!");
}
What happens is:
- i = 0;
- i < 3 is evaluated as true, thus "Hello" is printed the first time
- i++;
- i =1;
- i < 3 is evaluated as true, thus "Hello" is printed again
- i++;
- i = 2;
- i < 3 is evaluated as true, thus "Hello" is printed again
- i++;
- i = 3;
- i < 3 is evaluated as false, thus the loop ends here
0
Guadalupe Gagnon
28 September 2021, 17:21
Who taught it to you? It isn't necessary to solve this task and it will be explained in the section about loops.
0
Nashid Kp
4 October 2021, 16:56
Ok.. thank you...
0