2. Sejarah Bahasa C
Bersumber dari bahasa BCPL (Martin Richards -1967) dan B
(Ken Thompson -1970)
C diciptakan Dennis Ritchie dari Bell Laboratories pada tahun
1972 dan diimplementasikan pada komputer DEC PDP-11
Pada 1978 Dennis Ritchie dan Brian Kernighan kemudian
mempublikasikan buku The C Programming Language yang
semakin memperluas pemakaiannya dan dijadikan standar oleh
ANSI (American National Standard Institute) pada tahun 1989
C kemudian dikembangkan lagi oleh Bjarne Stroustrup menjadi
C++ (1986)
C dan/atau C++ banyak digunakan (sehingga menjadi standar)
sebagai bahasa pemrograman untuk membuat sistem operasi
PEDATI - Fasilkom UI 2005
2
4. Program sederhana I [1]
Contoh program untuk menampilkan sebaris teks
Selamat menggunakan bahasa C! pada layar:
1. /* Program pertama dalam bahasa C */
2. #include <stdio.h>
3. /* fungsi main mulai eksekusi program */
4. int main( void )
5. {
6.
printf( Selamat menggunakan bahasa C!n" );
7.
return 0; /* indikasi program berakhir dengan sukses */
8. } /* akhir fungsi main */
Program Output
Selamat menggunakan bahasa C!
PEDATI - Fasilkom UI 2005
4
5. Program sederhana I [2]
Komentar diawali dengan /* dan diakhiri dengan */ (seperti terdapat pada baris1,3,7,dan 8), komentar tidak dipedulikan/diproses oleh compiler. Bermanfaat
untuk memudahkan pembacaan dan pemahaman sebuah program.
Baris dengan awalan # (seperti pada baris-2) diproses oleh preprocessor C
sebelum program dikompilasi. Baris tersebut menunjukkan bahwa preprocessor
harus mengikutsertakan standard input/output header (stdio.h) pada
program.Header ini mengandung informasi yang digunakan compiler untuk
mengkompilasi pemanggilan fungsi standar input/output seperti printf (baris-6).
int main() merupakan fungsi utama program dan selalu merupakan bagian dari
program dalam C, karena berjalannya program/instruksi ditentukan oleh fungsi
ini. int berarti fungsi main mengembalikan nilai integer
Tanda kurung kurawal buka { dan tutup } merupakan penanda body dari sebuah
fungsi atau sering disebut juga block fungsi/program.
printf( Selamat menggunakan bahasa C!n" ); menghasilkan aksi yaitu
menampilkan teks Selamat menggunakan bahasa C!
return 0; selalu diikutsertakan pada akhir fungsi main. Keyword return untuk
menyatakan keluar dari suatu fungsi, dan angka 0 menunjukkan nilai yang
dihasilkan/dikembalikan oleh fungsi tersebut.
PEDATI - Fasilkom UI 2005
5
6. Program sederhana I [3]
1. /* Program pertama dalam bahasa C */
2. #include <stdio.h>
3. /* fungsi main mulai eksekusi program */
4. int main( void )
5. {
6.
printf( Selamat menggunakan bahasa C!n" );
7.
return 0; /* indikasi program berakhir dengan sukses */
komentar
preprocessor
main function
statement
function body
8. } /* akhir fungsi main */
PEDATI - Fasilkom UI 2005
6
7. Program sederhana I [4]
Karakter
escape
Karakter
Deskripsi
n
Pindah kursor ke baris baru
t
Horisontal tab, pindah kursor ke posisi tab berikutnya
a
Membunyikan bel sistem/beep
Mencetak/menampilkan (backslash)
Mencetak/menampilkan
PEDATI - Fasilkom UI 2005
7
8. Program sederhana I [5]
Modifikasi 1: mencetak 1 baris dengan 2 buah perintah printf
1
/* Fig. 2.3: fig02_03.c
2
3
Printing on one line with two printf statements */
#include <stdio.h>
4
5
/* function main begins program execution */
6
int main()
7
{
8
printf( "Welcome " );
9
printf( "to C!n" );
10
11
return 0; /* indicate that program ended successfully */
12
13 } /* end function main */
Program
Output
Welcome to C!
PEDATI - Fasilkom UI 2005
8
9. Program sederhana I [6]
Modifikasi 2: mencetak banyak baris dengan sebuah perintah printf
1
/* Fig. 2.4: fig02_04.c
2
3
Printing multiple lines with a single printf */
#include <stdio.h>
4
5
/* function main begins program execution */
6
int main()
7
{
8
printf( "WelcomentonC!n" );
9
10
return 0; /* indicate that program ended successfully */
11
12 } /* end function main */
Welcome
to
C!
Program
Output
PEDATI - Fasilkom UI 2005
9
10. Program sederhana II [1]
Membaca
2 buah bilangan bulat dari
keyboard dan menampilkan hasil
penjumlahannya
PEDATI - Fasilkom UI 2005
10
11. 1
/* Fig. 2.5: fig02_05.c
2
3
Addition program */
#include <stdio.h>
4
5
/* function main begins program execution */
6
int main()
7
{
8
int integer1; /* first number to be input by user
9
int integer2; /* second number to be input by user */
10
int sum;
*/
/* variable in which sum will be stored */
11
12
printf( "Enter first integern" );
/* prompt */
13
scanf( "%d", &integer1 );
/* read an integer */
14
15
printf( "Enter second integern" ); /* prompt */
16
scanf( "%d", &integer2 );
/* read an integer */
sum = integer1 + integer2;
/* assign total to sum */
printf( "Sum is %dn", sum );
/* print sum */
17
18
19
20
21
22
return 0;
/* indicate that program ended successfully */
23
24 } /* end function main */
Enter first integer
45
Enter second integer
72
Sum is 117
Program Output
PEDATI - Fasilkom UI 2005
11
12. Program sederhana II [2]
Baris ke-1 hingga ke-7 serupa dengan program I
int integer1, integer2, sum;
Pendefinisian variable-variabel
Variabel: lokasi di memori tempat sebuah nilai disimpan
int berarti variabel dapat menyimpan bilangan bulat (-1, 3, 0, 47)
Nama-nama variabel (identifier)
integer1, integer2, sum
Identifier: mengandung huruf,angka (tidak boleh dimulai dengan
angka) dan underscores( _ )
Case sensitive (huruf besar dan kecil dibedakan)
Deklarasi variabel harus muncul sebelum eksekusi statement yang
menggunakannya
Jika eksekusi statement mengacu kepada variabel yang belum
dideklarasikan maka akan menghasilkan syntax (compiler) error
PEDATI - Fasilkom UI 2005
12
13. Program sederhana II [3]
scanf( "%d", &integer1 );
Mengambil sebuah nilai dari user
scanf menggunakan standar input (biasanya keyboard)
scanf statement ini memiliki dua buah argumen
%d - menunjukkan data yang diambil adalah bilangan bulat desimal
&integer1 berlokasi di memori untuk menyimpan nilai variabel tsb
Tanda & dapat membingungkan di awal untuk saat ini sertakan
pada nama variabel pada statement scanf
Ketika program dieksekusi user merespon statement scanf dengan
mengetik sebuah bilangan kemudian menekan tombol enter (return)
= (assignment operator)
Assigns (memberi) sebuah nilai kepada sebuah variabel
Merupakan sebuah operator biner (memiliki dua buah operand)
sum = variable1 + variable2;
sum memperoleh hasil dari variable1 + variable2;
Variabel penerima nilai berada di sebelah kiri
PEDATI - Fasilkom UI 2005
13
14. Program sederhana II [4]
printf( "Sum is %dn", sum );
Serupa dengan pada scanf
%d berarti bilangan bulat desimal akan ditampilkan/dicetak
Nilai variabel sum menentukan bilangan bulat yang akan
ditampilkan/dicetak
Perhitungan dapat langsung dilakukan dalam statement printf
printf( "Sum is %dn", integer1 + integer2 );
PEDATI - Fasilkom UI 2005
14
15. Konsep Memori [1]
Variabel
Nama-nama variabel berkaitan dengan lokasi-lokasi di memori
komputer
Setiap variabel memiliki sebuah nama, sebuah tipe, sebuah
ukuran dan sebuah nilai
Ketika sebuah nilai baru diberikan pada sebuah variabel
(misalnya melalui scanf) maka nilai yang lama akan diganti
(dan hilang)
Membaca variabel dari memori tidak akan mengubah nilainya
Representasi visual:
integer1
45
PEDATI - Fasilkom UI 2005
15
17. Aritmatika [1]
Perhitungan Aritmatika
Gunakan * untuk perkalian dan / untuk pembagian
Pembagian bilangan bulat membuang sisa pembagian
7 / 5 dievaluasi menjadi 1
Operator Modulus (%) menghasilkan sisa pembagian
7 % 5 dievaluasi menjadi 2
Operator precedence
Beberapa operator aritmatika lebih diprioritaskan (dihitung lebih dahulu)
dibandingkan operator lainnya (misalkan perkalian dan pembagian
didahulukan dibandingkan penjumlahan dan pengurangan)
Gunakan tanda kurung jika diperlukan
Contoh: Hitung nilai rata-rata dari variabel-variabel a, b and c
Jangan gunakan: a + b + c / 3
Gunakan: (a + b + c ) / 3
PEDATI - Fasilkom UI 2005
17
18. Aritmatika [2]
Operator-operator aritmatika:
C operation
Arithmetic operator
Algebraic expression
C expression
Addition
+
f+7
f + 7
Subtraction
-
pc
p - c
Multiplication
*
bm
b * m
Division
/
x/y
x / y
Modulus
%
r mod s
r % s
Aturan precedence operator:
Operator(s)
Operation(s)
Order of evaluation (precedence)
()
Parentheses
Evaluated first. If the parentheses are nested, the expression in the innermost pair is
evaluated first. If there are several pairs of parentheses on the same level (i.e., not
nested), they are evaluated left to right.
*, /, or %
Multiplication,Division,
Modulus
Evaluated second. If there are several, they are
evaluated left to right.
Addition
Subtraction
Evaluated last. If there are several, they are
evaluated left to right.
+
or -
PEDATI - Fasilkom UI 2005
18
19. Aritmatika [3]
Step 1.
y = 2 * 5 * 5 + 3 * 5 + 7;
(Leftmost multiplication)
2 * 5 is 10
Step 2.
y = 10 * 5 + 3 * 5 + 7;
(Leftmost multiplication)
10 * 5 is 50
Step 3.
y = 50 + 3 * 5 + 7;
(Multiplication before addition)
3 * 5 is 15
Step 4.
y = 50 + 15 + 7;
(Leftmost addition)
50 + 15 is 65
Step 5.
(Last addition)
y = 65 + 7;
65 + 7 is 72
Step 6.
y = 72;
(Last operationplace 72 in y)
PEDATI - Fasilkom UI 2005
19
20. Pengambilan Keputusan: Persamaan
dan Operator Relasional [1]
Eksekusi statement
Menghasilkan aksi-aksi (penghitungan, input/output data)
Menghasilkan keputusan
Ingin menampilkan lulus" or gagal" berdasarkan suatu syarat
nilai tertentu
if control statement
Versi sederhana dahulu, lebih detail kemudian
Jika suatu kondisi true, maka body statement if dieksekusi
0 adalah false, non-zero adalah true
Kontrol terhadap perintah selanjutnya setelah struktur if
Keywords
Kata-kata khusus yang digunakan oleh bahasa C
Tidak dapat digunakan sebagai nama variabel atau identifier
PEDATI - Fasilkom UI 2005
20
21. Pengambilan Keputusan: Persamaan
dan Operator Relasional [2]
Standard algebraic equality
operator or relational operator
C equality or
relational operator
Example of C
condition
Meaning of C condition
=
==
x == y
x is equal to y
!=
x != y
x is not equal to y
>
>
x > y
x is greater than y
<
<
x < y
x is less than y
>=
>=
x >= y
x is greater than or equal to y
<=
<=
x <= y
x is less than or equal to y
Equality Operators
Relational Operators
PEDATI - Fasilkom UI 2005
21
22. 1
/* Fig. 2.13: fig02_13.c
2
Using if statements, relational
3
operators, and equality operators */
4
#include <stdio.h>
5
6
/* function main begins program execution */
7
int main()
8
{
9
int num1, /* first number to be read from user
10
int num2; /* second number to be read from user */
*/
11
12
printf( "Enter two integers, and I will tell youn" );
13
printf( "the relationships they satisfy: " );
14
15
scanf( "%d%d", &num1, &num2 ); /* read two integers */
16
17
18
19
if ( num1 == num2 ) {
printf( "%d is equal to %dn", num1, num2 );
} /* end if */
20
21
22
23
if ( num1 != num2 ) {
printf( "%d is not equal to %dn", num1, num2 );
} /* end if */
24
PEDATI - Fasilkom UI 2005
22
23. 25
26
27
if ( num1 < num2 ) {
printf( "%d is less than %dn", num1, num2 );
} /* end if */
28
29
30
31
if ( num1 > num2 ) {
printf( "%d is greater than %dn", num1, num2 );
} /* end if */
32
33
34
35
if ( num1 <= num2 ) {
printf( "%d is less than or equal to %dn", num1, num2 );
} /* end if */
36
37
38
39
if ( num1 >= num2 ) {
printf( "%d is greater than or equal to %dn", num1, num2 );
} /* end if */
40
41
return 0;
/* indicate that program ended successfully */
42
43 } /* end function main */
Enter two integers, and I will tell you
the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7
Program Output
PEDATI - Fasilkom UI 2005
23
24. Enter two integers, and I will tell you
the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
Enter two integers, and I will tell you
the relationships they satisfy: 7 7
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7
Program Output
(lanjutan)
PEDATI - Fasilkom UI 2005
24
25. Pengambilan Keputusan: Persamaan
dan Operator Relasional [3]
Operators
*
/
+
-
<
<=
==
Associativity
%
!=
left to right
left to right
>
>=
left to right
left to right
=
right to left
Precedence dan associativity dari operator-operator
PEDATI - Fasilkom UI 2005
25
26. Pengambilan Keputusan: Persamaan
dan Operator Relasional [4]
Keywords
auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
const
float
short
unsigned
continue
for
signed
void
default
goto
sizeof
volatile
do
if
static
while
Reserved keywords pada bahasa C
PEDATI - Fasilkom UI 2005
26
27. Algoritma dan Pseudocode
Algoritma: urutan langkah-langkah yang dapat
digunakan untuk memecahkan suatu masalah
Pseudocode:
Bahasa buatan yang bersifat informal yang dapat
membantu untuk mengembangkan algoritma
Serupa dengan bahasa sehari-hari
Membantu mempermudah penulisan program; dengan
menggunakan statement-statement yang dapat dieksekusi,
mempermudah konversi ke bahasa pemrograman
PEDATI - Fasilkom UI 2005
27
28. Struktur Kontrol
Semua program ditulis dalam 3 macam bentuk struktur kontrol:
Sequence atau berturutan: struktur ini tersedia secara built-in. Secara
default program dieksekusi secara berturutan sesuai urutan perintah
Selection atau pilihan: ada 3 macam dalam bahasa C: if, ifelse,
dan switch
Repetition atau pengulangan: ada 3 macam dalam bahasa C: while,
dowhile, dan for
Flowchart
Representasi grafis dari algoritma
Menggunakan simbol-simbol khusus yang dihubungkan dengan garis
beranak panah
Simbol kotak melambangkan aksi
Simbol oval melambangkan awal dan akhir suatu program atau blok
program
Simbol berlian melambangkan keputusan/pilihan
PEDATI - Fasilkom UI 2005
28
29. Selection Control [1] (if)
Statement if:
Digunakan untuk seleksi suatu kondisi
Contoh pseudocode:
If students grade is greater than or equal to 60
Print Passed
Contoh Flowchart:
grade >= 60
true
print Passed
false
PEDATI - Fasilkom UI 2005
29
30. Selection Control [2] (if)
Jika kondisi true
Statement Print dieksekusi dan program dilanjutkan ke statement
berikutnya
Jika kondisi false
Statement Print diabaikan dan program dilanjutkan ke statement
berikutnya
Dalam bahasa C:
if ( grade >= 60 )
printf( "Passedn" );
PEDATI - Fasilkom UI 2005
30
31. Selection Control [3] (if
else)
Statement ifelse:
Menspesifikasikan aksi baik untuk kondisi true maupun untuk kondisi
false
Contoh pseudocode:
If students grade is greater than or equal to 60
Print Passed
else
Print Failed
Contoh Flowchart:
false
grade >= 60
print Failed
true
print Passed
PEDATI - Fasilkom UI 2005
31
32. Selection Control [4] (if
else)
Dalam C :
if ( grade >= 60 )
printf( "Passedn");
else
printf( "Failedn");
Ternary conditional operator (?:)
Memerlukan tiga argumen (kondisi, nilai jika true, nilai jika false)
Contoh di atas dapat ditulis sbb:
printf( "%sn", grade >= 60 ? "Passed" : "Failed" );
Atau dapat ditulis sbb:
grade >= 60 ? printf( Passedn ) :
printf( Failedn );
PEDATI - Fasilkom UI 2005
32
33. Selection Control [5] (if
else)
Statement ifelse bertingkat/bersarang:
Digunakan untuk menguji banyak kondisi dimana menempatkan
statement seleksi ifelse di dalam statement ifelse
Sekali kondisi terpenuhi, sisa statement lainnya dilewatkan/diabaikan
Contoh pseudocode:
If students grade is greater than or equal to 90
Print A
else
If students grade is greater than or equal to 80
Print B
else
If students grade is greater than or equal to 70
Print C
else
If students grade is greater than or equal to 60
Print D
else
Print F
PEDATI - Fasilkom UI 2005
33
34. Selection Control [6] (if
else)
Compound statement
Ada lebih dari satu statement/aksi yang harus dieksekusi setelah suatu
kondisi dipenuhi
Sering disebut juga blok karena ditandai dengan pasangan { dan }
Contoh:
if ( grade >= 60 )
printf( "Passed.n" );
else {
printf( "Failed.n" );
printf( "You must take this course
again.n" );
}
Tanpa tanda kurung kurawal, statement
printf( "You must take this course
again.n" );
Akan dieksekusi secara otomatis.
PEDATI - Fasilkom UI 2005
34
35. Selection Control [7] (switch)
Multiple-Selection Statement switch:
Berguna pada waktu sebuah variabel atau ekspresi diuji terhadap
semua nilai yang mungkin dan masing-masing mengambil aksi yang
berbeda
Format penulisan:
Sederetan label case dan opsional default case
switch ( value ){
case '1':
actions
case '2':
actions
default:
actions
}
break; keluar dari statement
PEDATI - Fasilkom UI 2005
35
36. Selection Control [8] (switch)
Flowchart statement switch:
case a
true
case a action(s)
break
case b action(s)
break
case z action(s)
break
false
case b
true
false
.
.
.
case z
true
false
default action(s)
PEDATI - Fasilkom UI 2005
36
37. Repetition Control [1] (while)
Struktur pengulangan structure
Programmer menentukan aksi yang akan diulang selama kondisi tetap
true
Psuedocode:
While there are more items on my shopping list
Purchase next item and cross it off my list
while loop diulang hingga kondisi menjadi false
Contoh:
int product = 2;
while ( product <= 1000 )
product = 2 * product;
PEDATI - Fasilkom UI 2005
37
39. Repetition Control [3] (while)
Pengulangan yang dikontrol sebuah counter
Loop diulang hingga counter mencapai angka tertentu
Disebut juga definite repetition karena jumlah pengulangan dapat kita
ketahui
Contoh: Sebuah kelas dengan 10 orang mahasiswa mengikuti kuis.
Nilai kuis adalah bilangan bulat dari 0 hingga 100. Tentukan nilai ratarata kuis tersebut.
Pseudocode:
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average
PEDATI - Fasilkom UI 2005
39
40. 1
/* Fig. 3.6: fig03_06.c
2
3
Class average program with counter-controlled repetition */
#include <stdio.h>
4
5
/* function main begins program execution */
6
int main()
7
{
8
int counter; /* number of grade to be entered next */
9
int grade;
/* grade value */
10
int total;
/* sum of grades input by user */
11
int average; /* average of grades */
12
13
/* initialization phase */
14
total = 0;
15
counter = 1; /* initialize loop counter */
/* initialize total */
16
17
/* processing phase */
18
while ( counter <= 10 ) {
/* loop 10 times */
19
printf( "Enter grade: " ); /* prompt for input */
20
scanf( "%d", &grade );
/* read grade from user */
21
total = total + grade;
/* add grade to total */
22
counter = counter + 1;
23
/* increment counter */
} /* end while */
24
PEDATI - Fasilkom UI 2005
40
41. 25
/* termination phase */
26
average = total / 10;
/* integer division */
27
28
/* display result */
29
printf( "Class average is %dn", average );
30
31
return 0; /* indicate program ended successfully */
32
33 } /* end function main */
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Class
grade: 98
grade: 76
grade: 71
grade: 87
grade: 83
grade: 90
grade: 57
grade: 79
grade: 82
grade: 94
average is 81
PEDATI - Fasilkom UI 2005
41
42. Repetition Control [4] (while)
Pengulangan yang dikontrol sebuah sentinel
Sentinel: tanda berhenti untuk keluar dari suatu loop, biasanya berupa
karakter, angka, atau tombol di keyboard sebagai tanda. Misalnya Q
untuk exit.
Loop diulang hingga mencapai sentinel tersebut
Jumlah pengulangan belum dapat kita ketahui secara pasti
PEDATI - Fasilkom UI 2005
42
43. 1
/* Fig. 3.8: fig03_08.c
2
3
Class average program with sentinel-controlled repetition */
#include <stdio.h>
4
5
/* function main begins program execution */
6
int main()
7
{
8
int counter;
/* number of grades entered */
9
int grade;
/* grade value */
10
int total;
/* sum of grades */
11
12
float average; /* number with decimal point for average */
13
14
/* initialization phase */
15
total = 0;
/* initialize total */
16
counter = 0;
/* initialize loop counter */
17
18
/* processing phase */
19
/* get first grade from user */
20
printf( "Enter grade, -1 to end: " );
/* prompt for input */
21
scanf( "%d", &grade );
/* read grade from user */
22
23
/* loop while sentinel value not yet read from user */
24
while ( grade != -1 ) {
25
total = total + grade;
/* add grade to total */
26
counter = counter + 1;
/* increment counter */
27
PEDATI - Fasilkom UI 2005
43
44. 28
printf( "Enter grade, -1 to end: " ); /* prompt for input */
29
scanf("%d", &grade);
30
/* read next grade */
} /* end while */
31
32
/* termination phase */
33
/* if user entered at least one grade */
34
if ( counter != 0 ) {
35
36
/* calculate average of all grades entered */
37
average = ( float ) total / counter;
38
39
/* display average with two digits of precision */
40
printf( "Class average is %.2fn", average );
41
} /* end if */
42
else { /* if no grades were entered, output message */
43
44
printf( "No grades were enteredn" );
} /* end else */
45
46
return 0; /* indicate program ended successfully */
47
48 } /* end function main */
PEDATI - Fasilkom UI 2005
44
45. Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Class
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
grade, -1 to end:
average is 82.50
75
94
97
88
70
64
83
89
-1
Enter grade, -1 to end: -1
No grades were entered
PEDATI - Fasilkom UI 2005
45