Minggu, 23 Maret 2014

Identify and correct the errors in each of the following. [Note: There may be more than one error in each piece of code.]

a) if ( age >= 65 );
     printf( "Age is greater than or equal to 65\n" );
        else
     printf( "Age is less than 65\n" );
Kesalahan: tanda titik koma (;) setelah “if ( age >= 65 )” seharusnya dihilangkan.

Correct:
if ( age >= 65 )
     printf( "Age is greater than or equal to 65\n" );
        else

     printf( "Age is less than 65\n" );

b) int x = 1, total;
     while ( x <= 10 ) {
         total += x;
         ++x;
     }    
     Kesalahan : variable total harus mempunyai nilai awal untuk operasi menggunakan “+=”

     Correct:
     int x = 1, total = 0;
     while ( x <= 10 ) {
        total += x;
        ++x;
      }

c) While ( x <= 100 )
        total += x;
        ++x;
     Kesalahan: 
     - Nilai awal dari variable x dan total harus di deklarasikan terlebih dahulu untuk perulangan.
     - Perulangan while tidak boleh di awali dengan huruf kapital, karena pemrograman C bersifat case sensitive. 
     - Jika ada 2 statement yang ingin dilakukan di dalam perulangan while, harus di tandai didalam sebuah blok.

     Correct:
     int x = 1, total = 0;
     while ( x <= 100 ){
        total += x;
        ++x;
     }

d) while ( y > 0 ) {
      printf( "%d\n", y );
      ++y;
     }  
     Kesalahan: 
     - Nilai dan type dari variable y harus di deklarasikan terlebih dahulu, karena untuk menampilkan nilai dari variable y dengan perintah “printf” harus diketahui type dari variable tersebut.

     Correct:
     int y = -10;
     while ( y > 0 ) {
        printf( "%d\n", y );
        ++y;
     }

0 komentar:

Posting Komentar