Algoritma & Pemrograman – Pertemuan 4 (Review)

PROGRAM CONTROL: REPETITION

> Basically, repeats a command or set of one for a certain amount of time.

> Number of repetition depends on the user, whether it’s defined during coding or during run-time.

> There are several repetition/looping operation:

  • for
  • while (Check first, then run)
  • do-while (Run first, check later)

Syntax:

1. for

              for(exp1; exp2; exp3) statement;

or

              for(exp1; exp2; exp3){

                statement1;

                statement2;

               …….

               }

              exp1 :  initialization

              exp2 :  conditional

              exp3 :  increment or decrement

exp1, exp2 and exp3 are optional

> exp1 & exp3 may consist of several expressions, separatedd with comma.

> Example:

             void reverse(char ss[])

{

int c,i,j;

for(i=0, j=strlen(ss)-1; i<j; i++, j–){

c=ss[i];

ss[i]=ss[j];

ss[j]=c;

}

}

> Infinite Loop: Basically, it’ll run forever, since there’s no stop condition. To end the loop, use “break”.

> Nested Loop: Basically, it’s like Inception, a.k.a loop in a loop. The repetition operation will start from the inner loop.

 

2. While

               while (exp) statements;

               or

               while(exp){

                 statement1;

                 statement2;

                  …..

               }

> exp is a Boolean expression. The result from executing this expression will either be true (not zero) or false (equal to zero).

> The evaluation of exp is done before the statements are executed.

 

3. do-while

                  do{

                      < statements >;

                  } while(exp);

> exp will continuously be executed while still true.

> The evaluation of exp is done after executing the statement(s).

 

In while operation, if exp value is false, the statement(s) may not be executed at all.

On the other hand, in do-while, the statement(s) will be executed at least once.

 

Difference between break & continue:

1. break

> Ends looping operation (for, while, do-while).

> Ends switch operation

 

2. continue

Skips the rest of the statements (subsequent to the skip statement)  inside a loop, and continue normally to a next loop.

 

For more info or examples, please search at Google.com . I’m too lazy to give one. It’s a pain.

This entry was posted in BINUS University, Lessons, Review. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *