How computers solve problems

  • Computers often solves problems by:

    • Repeatedly executing the same sequence of instructions

  • A commonly used problem solving techniques in Computer Science is:

      • The brute force search technique where the computer program check every possible solution...


  • The programming language construct to make a computer program repeat a series of instructions is:

    • A loop

  • Warning:

    • You can make a loop that never ends (a.ka. an infinite loop)

    • In that case, you computer program will never stop

Making a computer program execute some statements repeatedly

  • The while-statement is one of the 3 types of loop statements in Java.

    Example: this Java program will print "Hello World" 4 times:

    public class While 
    {
       public static void main(String[] args) 
       {
          int i;
    
          i = 0;
          while ( i < 4 )
          {
             System.out.println("Hello World");
             i++;
          }
       }
    } 

DEMO: demo/05-loops/01-intro/While.java      (step in BlueJ)

Overview of the loop statements in Java

  • There are 3 different loop statements in Java:

      1. The while-statement

      2. The do-while-statement

      3. The for-statement

    Each type of loop statement is designed for some special situation (problem)

  • We will study all of them in this chapter