Jobsheet 9 - Looping 1

Loop is a block or group instruction (statement) that executed repeatedly. The purpose of loop or repetition to make the process more efficient. We can use three syntaxes to create loop in java. Please check the basic structure below.

// loop using for syntax
for (initialization; condition; update) {
  statement;
  ...
}

// loop using while syntax
while (condition) {
  statement;
  ...
}

// loop using do while syntax
do {
  statement;
  ...
} while (condition);

The loop syntaxes have condition that limit the repeat repetition. For and while works by check the condition first then execute the statement. Do while works by opposite way. You can check flowchart below to understand about the execution.

Flowchart For While

Flowchart Do While

Experiment

Experiment 1

  • Rewrite program below!

    • Looping using for

    Factorial For

    • Looping using while

    Factorial While

    • Looping using do-while

    Factorial Do While

  • Then check the result!

    Factorial Output

Experiment 2

  • Copy the looping program that using break below.

    • Looping using for

      Looping For Break

      Note for without condition is equals to infinite loop

    • Looping using while

      Looping While Break

    • Looping using do-while

      Looping Do While Break

  • Check the result of your program below!

    Looping Break Output

Experiment 3

  • Rewrite the looping program that using continue below.

    Looping Continue

  • Check the result of your program below!

    Looping Continue Output

Assignment

  1. (SumEven) Create a program that ask user positive number N (N > 0). Then program sum only even number. Example:

    • If user input N = 3, it means: 0 + 2 + 4 = 6
    • If user input N = 5, it means: 0 + 2 + 4 + 6 + 8 = 20

    Program only needs to display the result of sum

  2. (SumQuadrate) Create a program that ask user positive number N (N > 0). Sum operation use quadrate number {1, 4, 9, 16, 25, 36, ... N2}. Example:

    • If user input N = 2, it means: 1 + 4 = 5
    • If user input N = 3, it means: 1 + 4 + 9 = 14
  3. (OddDigit) Create a program that ask user positive number N (N > 0). Program checks the total odd digit from number. Example:

    • If user input N = 2345, the total odd digit = 2
    • If user input N = 993312, the total odd digit = 5

results matching ""

    No results matching ""