Dasar-dasar Pemrograman : Pengulangan I dalam Java dan Contoh Soal
Loops
With a loop, a part of a program is repeated over and over, until a specific goal is reached. There are two types of loops in computer programming :
- You know exactly how many times you have to repeat
- You know the specific condition when to stop the repetition, but you do not know how many times to repeat the action to achieve that particular condition
While
Syntax :
As long as the condition is true, the statements will always be repeated. while is the best choice to perform repetition when it does not know how many times it should be repeated ( but do know what the condition that should make the repetition to stop )
Examples of while
What does this program do ?
Exercise 1
- Wombat needs to write all numbers between 1 to n, in reversed order !
- Wombat needs to print the first ten number that is multiplication of 3 !
- Wombat needs to print the first ten number that is multiplication of 3 in reversed order !
- Wombat needs to check if a number is a prime number or not a prime number !
do-while
Syntax :
The statements inside the block will always be repeated as long as the condition is true. The do-while loop is appropriate when the loop body must be executed at least once.
for
Syntax :
- initialization : one or more statements which are executed only one time in the beginning of the iteration. The counter/iterator usually initialize in the initialization
- condition : decide whether the block statement will be executed or not. If the expression returns false, then the whole for statement is terminated and the program will evaluate the next statement.
- updater : statement which is executed after the block statement is executed. The counter/iterator’s value usually updated in the updater
Common Mistakes
- Forget the block statement
- Add a semicolon right behind the for statement
- The expression never returns a false value
- Modify the counter inside the block statement
Exercise 2
- Wombats need to know how many vocal character are there in their names. Write a program to help wombats to solve this problem! Assume that wombat’s name only consist of lowercase letters!
- Help the wombats to make a program to calculate the n factorial!
- Help the wombats to make a program to find the n-th of Fibonacci number!
- Given the value of n (positive integer), help the wombats to make a method to aproximate the value of π!
Sumber
Slide Daspro : Loops 1
Posting Komentar