Anda di halaman 1dari 38

DASAR

PEMROGRAMAN
Fundamental C++

1
Operator
› Simbol atau karakter digunakan untuk melakukan sesuatu
operasi atau manipulasi.
› Misal: menjumlahkan, mengurangi, membandingkan,
memberikan nilai, dll.
› Jenis operator:
– Operator Aritmatika
– Operator Increment dan Decrement
– Operator penugasan
– Operator kombinasi

2
Operator Aritmatika
› Terdiri dari dua jenis:
– Operator Binary
Operator Fungsi
* Perkalian
/ Pembagian
% Sisa Bagi
+ Pertambahan
- Pengurangan
– Operator Unary
› Tanda Minus (-)
› Tanda Plus (+)

3
Contoh
› Masalah 2 (M2)
– Buatlah Kalkulator sederhana untuk penjumlahan, pengurangan,
pembagian dan perkalian dari dua buah bilangan dimana
masukan sudah ditetapkan.
› Solusi
– Program kalkulatorV1
{program kalkulator sederhana dari dua buah bilangan yang
sudah ditetapkan}
– Deklarasi
int bil1 <- 5, bil2 < - 3
float jumlah, kurang, kali, bagi, modulus

4
Contoh.
› Kalkulator
read bil1, bil2
jumlah <- bil1 + bil2
kurang <- bil1 + bil2
kali <- bil1 * bil2
bagi <- bil1 / bil 2
modulus <- bil1 mod bil2
display (jumlah,kurng,kali,bagi,modulus)

5
6
Operator Increment dan Decrement
› Operator increment: ‘++’
› Operator decrement: ‘--’

7
Prioritas Operator Aritmatika
› Bentuk unary + dan unary – memiliki prioritasyang lebih
tinggidaripadabentuk binary + dan binary -

8
Operator Penugasan (assignment)
› Digunakan untuk memindahkan nilai dari suatu ungkapan
(expression) ke suatu pengenal.
› Operator pengerjaan yang umum digunakan dalam
Bahasa pemrograman, termasuk Bahasa C adalah
operator sama dengan(=).
pengenal1 = pengenal2 = …= ungkapan
Contoh : a=(b=1)+5;

9
Operator Kombinasi
› Digunakan untuk memendekkan penulisan operasi
penugasan.
› Contoh:
x = x + 2;
y = y * 4;
Dapat dipendekkan menjadi:
x += 2;
y *= 4;

10
Operator Kombinasi

11
Input / Output Stream
Fundamental C++

12
Stream
› Di C++ urutan byte disebut stream dari sumber ke tujuan
› 2 type stream
– Input stream : urutan karakter dari sebuah input device computer
– Output stream: urutan karakter dari computer ke output device
› Untuk menerima data dari keyboard dan kirim output ke layar,
setiap program C ++ harus menggunakan file header iostream
(istream & ostream). Berisi variable cin (common input) &
cout (common output)
› extraction operator >>
› cin >> payRate >> hoursWorked;
› cin >> payRate
› cin >> hoursWorked;
13
Contoh cin
› int a;
› double z;
› char ch;

› int a, b;
› double z;
› char ch, ch1, ch2;

14
cin and the get Function
› Deklarasi : char ch1, ch2; int num;
› Input : A 25
› Statement : cin >> ch1 >> ch2 >> num;
› Alternatif :
– cin.get(ch1); // cin >> ch1;
– cin.get(ch2);
– cin >> num;

› Gunakan fungsi getline(cin,variable) untuk menerima string


dengan blank space.

15
cin and the ignore Function
› cin.ignore(intExp, chExp);
› cin.ignore(100, '\n’); // artinya mengabaikan 100 karakter
dibaris pertama
› cin.ignore(100, 'A’); // artinya mengabaikan 100 karakter
sampai char A ditemukan.
› cin.ignore(); // skip new line character

16
putback and peek Functions
› Digunakan untuk proses data campuran (numeric &
character), kita tidak tahu input selanjutnya karakter atau
numerik
› Contoh Program : FunctionPeekPutback.cpp

17
Input Failure & Clear Function
› cin.clear(); // restore input stream
› Contoh : InputFailureandClearFunction.cpp

18
Output and Formatting Output
(manipulator)
› insertion operator << and the manipulator endl to display results on the
standard output device.
› setprecision Manipulator, sintax setprecision(n).
› You use the manipulator setprecision to control the output of floating-point
numbers. Include header file iomanip. #include <iomanip>
› cout << setprecision(2);
› fixed Manipulator; sintax cout << fixed
› Disable fixed pakai perintah cout.unsetf(ios::fixed);
› cout<<scientific – format dalam scientific number
› On some compilers, the statements cout<< fixed;and cout<<scientific;
might not work. In this case, you can use cout.setf(ios::fixed);in place of
cout<<fixed;and cout.setf(ios::scientific);in place of cout<<scientific;.

19
PEMAKAIAN SETIOFLAG()
› Manipulator setiosflag() merupakan manipulator yang
dapat dipakai untuk mengontrol sejumlah tanda format:

20
Manipulator2.cpp
› showpoint Manipulator; digunakan untuk menampilkan
(titik)
› cout << showpoint; cout << fixed << showpoint;

21
Manipulator setw(n)
› Digunakan untuk output pemberian nilai expresi dalam
jumlah kolom tertentu. Nilai expresinya bisa angkat/string.
› Bermanfaat untuk mangatur lebar dari suatu tampilan data.
› Contoh : setw2.cpp

22
Manipulator setfill()
› Pada setw, output ditampilkan format righ-justified, dan
kolom yang tidak digunakan disebelah kiri ditandai dengan
blank space.
› cout << setfill('#’);
› Contoh : setfill.cpp

23
Debugging: Understanding Logic Errors
and Debugging with cout Statements
› Ilustrasi konversi dari Fahrenheit ke celcius
› Celsius = 5 / 9 * (Fahrenheit – 32)
› See program : ftoc.cpp

24
File Input/Output
› File: An area in secondary storage used to hold
information.
› The standard I/O header file, iostream, contains data types
and variables that are used only for input from the standard
input device and output to the standard output device.
› In addition, C++ provides a header file called fstream,
which is used for file I/O. Among other things, the fstream
header file contains the definitions of two data types:
ifstream, which means input file stream and is similar to
istream, and ofstream, which means output file stream
and is similar to ostream.

25
File I/O is a five-step process:
1. Include the header file fstream in the program.
2. Declare file stream variables.
3. Associate the file stream variables with the input/output
sources.
4. Use the file stream variables with >>, <<, or other
input/output functions.
5. Close the files.

26
27
Case Study
› Movie Tickets Sale and Donation to Charity
› “Sebuah studio film local sangat diminati, Untuk membantu donasi, maka pemilik
studio memutuskan untuk menyumbangkan sebagian dari pendapatan kotornya
kepada lembaga amal.”
› Buat programnya yang memasukan nama film, harga tiket dewasa, harga tiket anak-
anak, jumlah tiket orang dewasa yang terjual, jumlah tiket anak yang terjual dan
presentase dar pendapatan kotor yang disumbangkan kelembaga amal.
› Catatan : String movie name letaknya disebelah kiri, dan number diformat disebelah
kanan, dan number decimal dengan 2 angkat dibelakang titik.
› Output programnya :

28
Problem Analisis dan Algoritma Design
› Untuk menghitung jumlah donasi yang diberikan dan jumlah
pendapatan bersih (net sale), dilakukan perhitungan untuk
menentukan jumlah pendapatan kotor (gross amount). Untuk
menghitung gross amount, anda harus mengkalikan tiket
dewasa yang terjual dengan harga tiketnya ditambah dengan
mengkalikan tiket anak-anak yang terjual dengan harga
tiketnya.
grossAmount = noOfAdultTicketSold * adultTicketPrice +
noOfChildTicketSold * childTicketPrice
› Kemudian, anda tentukan persentase yang akan didonasikan
dan hitung jumlah pendapatan bersih (net sale) dengan
mengurangi pendapatan kotor dengan donasi.

29
Analisis Algoritma
1. Get the movie name.
2. Get the price of an adult ticket.
3. Get the price of a child ticket.
4. Get the number of adult tickets sold.
5. Get the number of child tickets sold.
6. Get the percentage of the gross amount donated to the charity.
7. Calculate the gross amount using the following formula:
grossAmount = adultTicketPrice * noOfAdultTicketsSold + childTicketPrice *
noOfChildTicketsSold;
8. Calculate the amount donated to the charity using the following formula:
amountDonated = grossAmount * percentDonation / 100;
9. Calculate the net sale amount using the following formula:
netSaleAmount = grossAmount – amountDonated;

30
Variable yang dideklarasikan
› string movieName;
› double adultTicketPrice;
› double childTicketPrice;
› int noOfAdultTicketsSold;
› int noOfChildTicketsSold;
› double percentDonation;
› double grossAmount;
› double amountDonated;
› double netSaleAmount;

31
Formatting Output
› Pada output, kolom pertama terletak disebelah kiri, kolom kedua (number) terletak
disebelah kanan. Oleh karena itu, saat mencetak nilai di kolom pertama, maka
manipulator left digunakan, dan saat mencetak nilai number disebelah kanan,
maka manipulator right digunakan. Ruang kosong antara kolom pertama dan
kedua diisi dengan titik, program menggunakan manipulator setfill(). Space antara
tanda $ dengan amount dikasih space dengan manipulator setfill()

32
Main Algoritma
1. Declare the variables.
2. Set the output of the floating-point numbers to two decimal places in a fixed decimal format with a
decimal point and trailing zeros. Include the header file iomanip.
3. Prompt the user to enter a movie name.
4. Input (read) the movie name. Because the name of a movie might contain more than one word (and,
therefore, might contain blanks), the program uses the function getline to input the movie name.
5. Prompt the user to enter the price of an adult ticket.
6. Input (read) the price of an adult ticket.
7. Prompt the user to enter the price of a child ticket.
8. Input (read) the price of a child ticket.
9. Prompt the user to enter the number of adult tickets sold.
10.Input (read) the number of adult tickets sold.
11.Prompt the user to enter the number of child tickets sold.
12.Input (read) the number of child tickets sold.
13.Prompt the user to enter the percentage of the gross amount donated.
14.Input (read) the percentage of the gross amount donated.
15.Calculate the gross amount.
16.Calculate the amount donated.
17.Calculate the net sale amount.
18.Output the results.
33
Case Study: Student Grade
› Tulis sebuah program yang membaca nama siswa diikuti
lima nilai tes. Program harus menampilkan nama siswa,
lima nilai tes, dan nilai rata-rata tes. Keluarkan nilai tes
rata-rata dengan dua angka desimal. Data yang akan
dibaca disimpan dalam file bernama test.txt. Keluarannya
harus disimpan dalam sebuah file Bernama testavg.out
› A sample input is: Andrew Miller 87.50 89 65.75 37
98.50
› Output : The student name, the five test scores, and
the average of the five test scores, saved to a file.

34
Problem Analisis dan Algoritma Design
1. Read the student name and the five test scores.
2. Output the student name and the five test scores.
3. Calculate the average.
4. Output the average.

35
Variable
› ifstream inFile; //input file stream variable
› ofstream outFile; //output file stream variable

› double test1, test2, test3, test4, test5; //variables to read


the five test scores
› double average; //variable to store the average test score
› string firstName; //variable to store the first name
› string lastName; //variable to store the last name

36
Main Algoritma
1. Declare the variables.
2. Open the input file.
3. Open the output file.
4. To output the floating-point numbers in a fixed decimal format with a decimal point
and trailing zeros, set the manipulators fixed and showpoint. Also, to output the
floating-point numbers with two decimal places, set the precision to two decimal
places.
5. Read the student name.
6. Output the student name.
7. Read the five test scores.
8. Output the five test scores.
9. Find the average test score.
10. Output the average test score.
11. Close the input and output files.

37
Notes:
› Because this program reads data from a file and outputs
data to a file, it must include the header file fstream.
› Because the program outputs the average test score to two
decimal places, you need to set the precision to two
decimal places. Therefore, the program uses the manipulator
setprecision, which requires you to include the header file
iomanip.
› Because firstName and lastName are string variables, we
must include the header file string.
› The program also includes the header file iostream to print a
message on the screen so that you will not stare at a blank
screen while the program executes.

38

Anda mungkin juga menyukai