Dasar-dasar Pemrograman : Pengulangan I dalam Java dan Contoh Soal

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

  1. Wombat needs to write all numbers between 1 to n, in reversed order ! 
  2. Wombat needs to print the first ten number that is multiplication of 3 ! 
  3. Wombat needs to print the first ten number that is multiplication of 3 in reversed order ! 
  4. 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


  1. Forget the block statement 
  2. Add a semicolon right behind the for statement 
  3. The expression never returns a false value 
  4. Modify the counter inside the block statement

Exercise 2


  1. 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! 
  2. Help the wombats to make a program to calculate the n factorial! 
  3. Help the wombats to make a program to find the n-th of Fibonacci number! 
  4. Given the value of n (positive integer), help the wombats to make a method to aproximate the value of π!


Sumber


Slide Daspro : Loops 1

Post a Comment

Lebih baru Lebih lama