While and For Loops


Collapse Content

As mentioned in How Computers Calculate, computers ultimately just do a few very simple operations. They have so much power because they can do the same operation any number of times. A programmer can get a computer to do repeated tasks by using loops.

While Loop

The While Loop is the only loop you really need, the other loops just make things more convenient. A while loop will repeatedly execute a block of code while a condition is true. The syntax is like an If-Statement, but with a while instead of an if:

while(condition){
 //then do stuff
}

For example, you might want to run a game as long as a player still has lives:

 while(lives > 0){
  runGame();
 }

Let's say you wanted to doSomething 10 times. You could use a While Loop to keep track:

int index = 1;
while(index <= 10){
  doSomething();
  index = index + 1;
}

The above loop will increase index and call doSomething() 10 times, but then stop once index is greater than 10.

The algorithm to get the largest number in a list (seen in Ways to show Algorithm) can also be coded with a while loop:

Click for Complex While Loop
This works fine, but if you forget to increase the index or make some mistake in the condition, the loop can go on forever and you will need to stop the running of the program.

For Loop

Many while loops involve setting up a variable and updating its value until a certain condition is reached, when the loop will terminate. Such loops can be replaced with For Loops, which is more compact and helps prevent eternal looping errors. It does this by combining the index, condition and updater in the header of the loop.

This is the general form of the for loop:

for(initial setup; condition; update after each loop iteration){
  //do stuff
}

The for loop header consists of 3 parts:

  1. setup - it usually declares and assigns a variable here (to use as an index).
  2. condition - the for loop will continue looping until this condition is false.
  3. update - usually, this is where the index variable is incremented.

For example, let's say you wanted to improve the above while loop to doSomething 10 times. Its used an index variable that it incremented each loop until it reached a certain value, so it could be replaced with a for loop:

for(int index = 1; index <= 10; index=index+1){
doSomething();
}

(hover above for more info)

This will call the method doSomething 10 times.

The while loop to find the Largest Number can be shortened by using a for loop instead:

Click for Complex Loop

Note that the action in the for loop can increase or decrease the index by any amount. Although you never need a for loop, you should use it instead of a while loop when possible, since it helps avoid errors.

Challenge

When the following loop terminates, what will num equal?

int num = 0;
while(num < 10){  // loop condition
  num = num + 3;  //loop body
}

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

You will be given two numbers a and b. Print out every number from a to b (inclusive). a will always be less than b.

Since we haven't covered printing yet, you can use the included printNum() method to print a number. Just pass it whatever number or variable you want to print. For example,this code will print 5:
printNum(5);

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • this is crazy hard to me..

  • how do i remove the cheat mark my submission was the exact answer :/

  • @Jason, sorry there's no way (currently) to remove the cheat once the cheat button has been clicked.

  • yes this course is very good idea but is should be motivated by java tutorials like beginner ,intermediate,advanced

  • hey im sorry but im still stuck in this on challenge everything looks perfect but i'm still getting errors please help..

  • @Jason, you want to increase the iterator each time. For example, to print the numbers from 1 through 10, you could create a loop like this:

    for(int i=1; i<= 10; i=i+1){
       printNum(i);
    }
    

    You need to do that to go from a to b instead.

  • I love the random quotes ♥

  • why is mine not working!!!

  • @Robert, make sure to declare any variable you use, even if it's just used as a loop index.

  • I do understand the While Loop and the example about wanting to repeat something 10 times, but I have a question ( quite stupid really but I just wanna make sure even though I know what is correct xD )
    So If we have
    { int index = 1;
    while(index <= 10){
    doSmth();
    index = index + 1
    }
    }
    so now after executing this program the index will at sometime be 2 3 4 5 6 7 8 9 and in the end 10.
    Does this mean that after every time the code is executed the { int index = 1 } changes to 2 3 4 5 6 7 8 9 or 10 from the "index = index + 1" ?
    I know it does but does that appear in the "int index = ?"

    cont...
  • @Adhurim, "int index=1" is outside the while loop, so it is executed only 1 time.

  • I really was tempted to click the hint for this one but I sat there and thought about the ways to make it work. I still have trouble with the for loop but by just setting int i = a would have been so simple. Oh well I'm glad I got it to work with the while loop but I should avoid it because of the possibility of errors.

    cont...
  • I did that and although it is correct but I should think of simpler way as the model answer :D :
    public static void doStuff(int a, int b){
    int tmp = a;
    for (int i = 0 ; i< b-a+1;i++)
    {

            printNum(tmp);
            tmp= tmp+1;
    
        }
    }
    
  • Yeah this one is tough. There should be an explanation of how to include multiple indexes in the first part of the for condition. Do you just use the & and also there is no explanation on how to printout inclusive information i.e. 1-5

  • Are we supposed to solve with the while loop or the "for" loop?

  • it says error:for(int i=a;i<=b;i+1){
    not a statement ^

  • it says error:for(int i=a;i<=b;i+1){
    not a statement ^

  • you have to put: i = i+1; or you can do an abreviation, like i++;

  • This is a great course. I am more comfortable with Java now, and it has only been 30 minutes.

  • int kq=0;
        for(int i=0;kq<b;i=i+1){
            kq=a+i;
            printNum(kq);
        }
    
  • Here's the easiest solution:

    for (a=a, b=b; a <= b; a++){
    printNum(a);
    }

  • yeah i have the same thing but different variables ( i used n) and it's not working.

  • while (a <= b) {
    printNum(a++);
    }

  • import java.util.Scanner;
    public class Main {
    public static void main(String[] args){

        Scanner input = new Scanner (System.in);
    
        System.out.print("Enter 1st number: ");
    
    cont...
  • for the for loop challenge:

    for (int i=a; i<=b;i++) {
    printNum (i);
    }

    this basically assigns i as being a for the first time since a is less than b; the condition is to display including

    cont...
  • for (int i = a; i <= b; i++){
    System.out.println(i);
    }

  • just replace all the code with:
    import java.util.Scanner;
    public class Main {

    public static void doStuff(int a, int b){
    

    long x= a;
    while(x<b+1){
    System.out.print(x+" ");
    x = x + 1;
    }

    cont...
  • Can I use While loop for the problem code above?

All Node Comments
Contact Us
Sign in or email us at [email protected]