P
t
P
Pengantar Pemrograman
Materi:
Variabel type dan
Materi:
Variabel, type dan
konstanta Ekspresi
& assignment
Struktur Program C++
// my first program in C++
#include <iostream.h>
#include iostream.h
int main () {
cout << "Hello World!";
cout << Hello World! ;
return 0;
Struktur Program C++
g
// my first program in C++
Ini adalah komentar. Semua baris yang dimulai dengan // atau dikurung oleh pasangan /*
…. */ adalah komentar yang tidak akan diproses oleh kompiler. Komentar sangat berguna untuk dokumentasi program
untuk dokumentasi program
// Baris komentar /* Komentar block */
#include <iostream.h>
Perintah yang dimulai dengan tanda (#) adalah pengarah preprocessor. Bagian ini bukan
perintah yang bisa dieksekusi, tetapi merupakan indikasi kepada kompiler. Dalam kasus ini #include <iostream.h> meminta preprocessor untuk menyertakan standard header
file iostream yang berisi deklarasi input-output standard
int main ()
Baris ini merupakan tempat mulainya eksekusi program (program utama). Isi perintah
untuk program utama terletak didalam sepasang kurung kurawal ({}).
t << "H ll W ld" cout << "Hello World";
Ini perintah untuk mencetak. Perhatikan (;) sebagai akhir setiap satu baris perintah.
return 0;
Perintah return meminta main() untuk berhenti dan mengembalikan code yang
Variabel dan Jenis DATA
Beberapa jenis data dasar:
Karakter: char
Bilangan bulat, integer:
•
int
•
long int: bilangan bulat dengan range lebih
besar dari int
Bilangan riil:
Bilangan riil:
•
float
•
double: bilangan riil dengan presisi dan
g
g
p
range lebih besar dari float
Boolean:
nilai True atau Falsebool
KONSTANTA
KONSTANTA
Yang paling sederhana adalah angka
bilangan bulat seperti: 0 1 2 123
bilangan bulat seperti: 0, 1, 2, 123 .
Konstanta dengan titik desimal atau
dengan huruf e (atau keduanya) adalah
dengan huruf e (atau keduanya) adalah
konstanta bilangan riil, seperti: 3.14, 10.,
.01, 123e4, 123.456e7.
Huruf e menyatakan perkalian dengan
pangkat 10. Contoh:
123.456e7 adalah 123.456 * 10 pangkat 7 =
1,234,560,000. (konstanta bilangan riil
berjenis dobel)
KONSTANTA KARAKTER DAN STRING
KONSTANTA KARAKTER DAN STRING
Konstanta karakter: memakai tanda petik tunggal 'A' ' ' '%' Konstanta karakter: memakai tanda petik tunggal A , . , % . Nilai numerik konstanta karakter adalah nilai karakter tersebut
sesuai (dalam ASCII, contohnya, 'A' mempunyai nilai 65.)
String adalah array karakter (detail nanti). Konstanta string g y ( ) g
memakai tanda petik ganda. "apple", "hello, world", "this is a test".
Arti karakter \ didalam konstanta karakter atau string:
\n a ``newline'' character \b a backspace
\r a carriage return (without a line feed)
\' a single quote (e.g. in a character constant) \" a double quote (e.g. in a string constant) \\ a single backslash
Contoh: "he said \"hi\"" Contoh: he said \ hi\
DEKLARASI Variabel
DEKLARASI Variabel
variabel (objek) dipakai untuk menyimpan
suatu nilai
suatu nilai
Variabel harus dideklarasikan sebelum
dipakai
p
Deklarasi menyatakan nama dan jenis
variabel
h char c; int i; float f;
int i1, i2; /* boleh beberapa variabel dalam satu baris */
Deklarasi boleh diikuti pemberian harga
awal
awal
ALASAN DEKLARASI
k
hi
h
i
h
il
It makes things somewhat easier on the compiler;
it knows right away what kind of storage to
allocate and what code to emit to store and
manipulate each variable; it doesn't have to try to
manipulate each variable; it doesn t have to try to
intuit the programmer's intentions.
It forces a bit of useful discipline on the
programmer: you cannot introduce variables
programmer: you cannot introduce variables
willy-nilly; you must think about them enough to pick
appropriate types for them. (The compiler's error
messages to you, telling you that you apparently
g
y
,
g y
y
pp
y
forgot to declare a variable, are as often helpful as
they are a nuisance: they're helpful when they tell
you that you misspelled a variable, or forgot to
thi k b
t
tl h
i
t it )
NAMA VARIABEL
Nama variabel terdiri dari huruf, angka
,
g
dan garis bawah (under score).
Untuk kita, nama harus dimulai dengan
huruf
huruf
Nama boleh sangat panjang
Huruf besar dan kecil dibedakan
Dodol, DoDol dan dodol adalah tiga variabel
yang berbeda
Nama variabel tidak boleh sama dengan
Nama variabel tidak boleh sama dengan
kata-kata kunci (keywords) & fungsi
pustaka (library function)
Int if for sin cos dll Tidak boleh dipakai
Int, if, for, sin, cos, dll. Tidak boleh dipakai
Kata-kata Kunci
ata ata u c
JANGAN dipakai untuk nama Variabel
asm, auto, bool, break, case, catch, char,
class, const, const_cast, continue, default,
delete, do, double, dynamic_cast, else,
enum, explicit, extern, false, float, for,
friend, goto, if, inline, int, long, mutable,
namespace, new, operator, private,
p
,
, p
, p
,
protected, public, register, reinterpret_cast,
return, short, signed, sizeof, static,
static_cast, struct, switch, template, this,
_
,
,
,
p
,
,
throw, true, try, typedef, typeid, typename,
union, unsigned, using, virtual, void,
OPERATOR ARITMATIKA
+ addition
-
subtraction
subtraction
* multiplication
/
division
/
division
% modulus
(remainder)
++ increment
--
decrement
OPERATOR ARITMATIKA
UTAMA
operator – untuk mengurangi dua angka (a - b),
atau memberi tanda negatif
( -a + b atau a + -b).
( a + b atau a + b).
Pembagian dua bilangan bulat menghasilkan
bilangan bulat dengan membuang sisa
pembagian: 7 / 4 adalah 1
pembagian: 7 / 4 adalah 1.
Apabila salah satu atau semua operand adalah
bilangan riil hasil pembagian adalah bilangan riil :
7 0 / 4 d l h 1 75
7.0 / 4 adalah 1.75.
Operator modulus % memberikan sisa dari
PRECEDENCE
l i li
i
di i i
d
d l
ll h
Multiplication, division, and modulus all have
higher precedence than addition and subtraction.
1 + 2 * 3 ekivalen dengan 1 + (2 * 3).All f th
t
``
'' f
l ft t
All of these operators ``group'' from left to
right, which means that when two or more of
them have the same precedence and participate
next to each other in an expression the
next to each other in an expression, the
evaluation conceptually proceeds from left to
right.
1 - 2 - 3 is equivalent to (1 - 2) - 3 1 2 3 is equivalent to (1 2) 3
Whenever the default precedence or associativity
doesn't give you the grouping you want, you can
always use explicit parentheses.
y
p
p
if you wanted to add 1 to 2 and then multiply the result
OPERATOR ‘=‘
OPERATOR
operator “=“ memberi nilai kepada variabel
x = 1 sets x to 1, and a = b sets a to whatever b's
value is.
i = i + 1 this expression takes i's old value, adds 1 to
it, and stores it back into i.
c = a = b ekivalen dengan c = (a = b) untuk
Pemberian Harga Awal
Pemberian Harga Awal
Variabel dapat diberikan harga awal pada saat
dideklarasikan, ada dua cara:
type identifier = initial_value ; // C dan C++ type identifier (initial_value) ; // C++
Contoh:
int a = 0; int a (0); ( );
tidak ada bedanya: Variabel diberikan harga awal pada saat
dideklarasikan atau pada saat pertama kali dipakai
int a = 10; int a = 10; Atau int a; /* lalu */ a = 10; / lalu... / a = 10;
OPERATOR ‘++‘ DAN ‘- -’
Operator ++; menambah satu ke variabel
Int x = 10;
x ++; /* sama artinya dengan x = x + 1; */
O
t
i
t
k
i b l
Operator --; mengurangi satu ke variabel
Int x = 10;
x ;
/* sama artinya dengan x = x 1; */
OPERATOR RINGKAS
O
Operator +=
X += 10; /* sama artinya dengan x = x + 10; */
Operator -=
X -= 10; /* sama artinya dengan x = x - 10; */
Operator *=
X *= 10; /* sama artinya dengan x = x * 10; */
Operator /=
X /= 10; /* sama artinya dengan x = x / 10; */ Apa artinya?: a *= b + c;
OPERATOR RELASIONAL
O
i
Operator Meaning
== equal
to
!= not
equal
q
< less
than
<=
less than or equal to
>
greater than
>
greater than
>=
greater than or equal to
R t
1 (TRUE) t
0 (FALSE)
Return 1 (TRUE) atau 0 (FALSE)
OPERATOR LOGIK
&&
and
||
or
||
or
PEMANGGILAN FUNGSI
PEMANGGILAN FUNGSI
Fungsi akan dipelajari lebih mendalam pada kuliah
selanjutnya. Disini akan ditunjukkan bagaimana memakai fungsi fungsi yang sudah disediakan oleh Kompiler
fungsi-fungsi yang sudah disediakan oleh Kompiler.
Fungsi dipanggil dengan menyebut namanya diikuti oleh
sepasang tanda kurung. Kalau fungsi mengambil argumen, kita letakkan argumen didalam kurung.g g
getchar();
Banyak fungsi mengembalikan suatu nilai. Nilai yang
dikembalikan bisa disimpan variabel atau bisa langsung dipakai dalam suatu operasi
c = sqrt(a * a + b * b); x = r * cos(theta);
CONTOH ASSIGNMENT
#i l d i h #include < iostream.h > main() { int sum; float money; h l tt char letter; double pi;sum = 10; // assign integer value 2 21 // i fl t l money = 2.21; // assign float value
Letter = 'A'; // assign character value pi = 2.01E6; // assign a double value
t " l f “ “\ ” cout << "value of sum = “ << sum << “\n”;
cout << "value of money = “ << money << “\n”; cout "value of letter = “ << letter << “\n”;
cout << "value of pi = “ << pi << “\n”; }
#include <iostream.h> main() { int sum; float money; char letter; double pi;
sum = 10; // assign integer value money = 2.21; // assign float value
letter = 'A'; // assign character value pi = 2.01E6; // assign a double value cout << "value of sum = " << sum << "\n"; cout << "value of money = " << money << "\n"; cout << "value of letter = " << letter << "\n"; cout << "value of pi = " << pi << "\n";
return 0; }
CONTOH Bekerja dengan
Variabel dan Operator
// operating with variables
#include <iostream.h>
// print out the result:
cout << result; int main () {
// declaring variables:
int a, b; int result;
// terminate the program:
return 0; } // process: a = 5; ; b = 2; a = a + 1; result = a - b; ;
CONTOH Bekerja dengan
Variabel dan Operator
// Variabel dan Operators #include <iosteream.h> main()
f = 1.0;
g = 2.0;
e = f/g;
{ int a, b, c, d = 3; float e, f, g;e = f/g;
cout << f/g <<
f*g << e;
c = 10; a = c + d; b = c * d;a = 2147483648;
b = 4294967295;
cout << a << b;
; e = c/d; cout << a << b << c/d << c%d << d%c << e;cout << a << b;
return 0;
}
PREPROCESSOR
STATEMENTS
Statemen define dipergunakan untuk membuat program lebih p g p g
mudah dibaca
/* Tanpa titik-koma ‘;’ */
/* karakter pertama dalam baris harus # */ / karakter pertama dalam baris harus # / #define TRUE 1
#define FALSE 0 #define NULL 0 #d fi AND & #define AND & #define OR | #define EQUALS == Contoh: #define PI 3.14159265 #define NEWLINE '\n' // di k i d b i l j t d i
// dipakai pada baris selanjutnya dari program
Keliling_lingkaran = 2 * PI * r;
Konstanta yang
Dideklarasikan
Bisa diberikan “jenis data” seperti
Bisa diberikan jenis data seperti
layaknya variabel
B d
d
i bl
il i
Bedanya dengan variable, nilainya
tidak bisa diubah
Umumnya dipakai untuk
memudahkan membaca program
const int width = 100;
INPUT DAN OUTPUT KE LAYAR
// Output (cout) #include <iostream.h> main() { int number; int number;cout << "Type in a number \n"; cin >> number;
cout << "The number you typed was“ << number<< “\n”; }
}
Contoh Run
Type in a number yp
23
Mencetak Baris Baru
Mencetak Baris Baru
Contoh:
cout << "First sentence.\n "; cout << First sentence.\n ;
cout << "Second sentence.\nThird sentence."; Hasilnya:
First sentence. First sentence. Second sentence. Third sentence.
Cara lain dengan memakai endl manipulator. Contoh:
cout << "First sentence." << endl; cout << "Second sentence." << endl; Hasilnya:
First sentence. Second sentence.
KARAKTER KHUSUS Untuk FORMAT
KARAKTER KHUSUS Untuk FORMAT
\b backspace \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \“ double quote \‘ single quote \‘ single quote
\<enter> line continuation
\nnnnnn = octal character value
\0xnnnn = hexadecimal value (some compilers only) \0xnnnn = hexadecimal value (some compilers only) printf("\007Attention, that was a beep!\n");
Contoh MEMBACA DAN MENCETAK
#include < iostream.h > main() { int sum; char letter; float money;cout << "Please enter an integer value "; cin >> sum;
cout << "Please enter a character "; cin >> letter;
cin >> letter;
cout << "Please enter a float variable "; cin >> money;
cout << "\nThe variables you entered were\n";y ; cout << "value of sum = “ << sum << “\n”; cout << "value of letter = “ << letter << “\n”; cout << "value of money = “ << money << “\n”; }
GAYA MENULIS PROGRAM (1)
#i l d di h #include<stdio.h>
main() {
int sum loop kettle job; int sum,loop,kettle,job; char Whoknows; sum=9; sum=9; loop=7; whoKnows='A';
cout "Whoknows = “ << whoknows << “ kettle = “ << kettle << “\n”; }
GAYA MENULIS PROGRAM (2)
GAYA MENULIS PROGRAM (2)
#include <iostream.h> #include <iostream.h>
main() {
{
int sum, loop, kettle = 0, job; char whoknows;
sum = 9; loop = 7;
whoknows = 'A';
o t "Whokno s “ << hokno s << cout "Whoknows = “ << whoknows <<
“ kettle = “ << kettle << “\n”; }
GAYA MENULIS PROGRAM(3)
GAYA MENULIS PROGRAM(3)
the { and } braces directly line up underneath each other
This allows us to check ident levels and ensure that This allows us to check ident levels and ensure that statements belong to the correct block of code. This becomes vital as programs become more complex
spaces are inserted for readability
We as humans write sentences using spaces between We as humans write sentences using spaces between words. This helps our comprehension of what we read (if you dont believe me, try reading the following sentence. wishihadadollarforeverytimeimadeamistake. The insertion of spaces will also help us identify mistakes quicker
of spaces will also help us identify mistakes quicker.
good indentation
Indent levels (tab stops) are clearly used to block
statements, here we clearly see and identify functions, d th t t t hi h b l t h { }
and the statements which belong to each { } program body.
initialization of variables
The first example prints out the value of kettle, a variable p p , that has no initial value. This is corrected in the second example.