Algoritma Part II
Budi. S.Kom
Struktur Kendali Percabangan
• AnalisisSatuKasus(IF- TH E N )Notasi algoritmik : IF- TH E N
if <kondisi> then
aksiaksi
Endif
• Contoh:
if x > 100 then
x ← x + 1
endif
Analisis Dua Kasus• Notasi algoritmik : IF- TH E N - E LSE
if <kondisi> then
aksi 1
else
aksi 2
endifendif
Contoh:if a > 0 then
write (‘bilangan positif’)
else
write (‘bilangan bukan positif’)
endif
Contoh:
if a > 0 then
write (‘bilangan positif’)
elseelse
write (‘bilangan bukan positif’)
endif
• N otasi C+ +
#include “stdio.h”Void main(){int a;printf(“Masukkan Angka :\n”);scanf(“%i”,&a)if (a > 0)
{{printf(“bilangan positif”);
}Else{printf(“bilangan bukan positif”)
}}
Analisis Tiga Kasus atau Lebih
Notasi algoritmik : IF- TH E N - E LSE
Tiga Kasusif <kondisi 1> then
aksi 1
else
if <kondisi 2> then
aksi 2
else
if <kondisi 3> then
aksi 3
endif
endif
endif
Contoh:if nilai >= 81 thengrade=‘A’;
elseif nilai >= 61 then
grade=‘B’;else
if nilai >= 41 thengrade=‘C’;
elseelseif nilai >= 21 then
grade=‘D’;else
grade=‘E’;endif
endifendif
endif
N otai dalam C+ +
#include "stdio.h"void main() {
int grade, nil;printf("Masukan Nilai Angka Anda : ");scanf("%i", &grade);
if(grade >= 81)x = 'A';
else if(grade >= 61)x = 'B';x = 'B';
else if(grade >= 41)x = 'C';
else if(grade >= 21)x = 'D';
elsex = 'E';
}
Note: perhatikanpadaekspresi if. Terdapat “= = “, artinyamembandingkanduabuahnilai
STRU KTU R CASEStruktur ini untukpermasalahanduakasusataulebih.Struktur :
case (nama) of<kondisi 1> : aksi 1<kondisi 2> : aksi 2<kondisi 3> : aksi 3<kondisi 3> : aksi 3.................................<kondisi N> : aksi N[ otherwhise aksi X ]endcase
• Contoh:
case (NoHari) ofNoHari = 1 : write (‘Ahad’)NoHari = 2 : write (‘Senin’)NoHari = 3 : write (‘Selasa’)NoHari = 4 : write (‘Rabu’)NoHari = 5 : write (‘Kamis’)NoHari = 6 : write (‘Jumat’)NoHari = 6 : write (‘Jumat’)NoHari = 7 : write (‘Sabtu’)otherwise write (‘bukan nama hari yangbenar’)
endcase
• Notasi C++#include "stdio.h"
void main()
{
int a;
scanf("%i",&a);
switch (a)
{{
case 1: printf("satu");break;
case 2: printf("dua");break;
case 3: printf("tiga");break;
case 4: printf("empat");break;
case 5: printf("lima");break;
default : printf("salah");
}
}