Lab Book C Programming
Lab Book C Programming
Editors:
Masitah Ghazali
Dayang Norhayati Abang Jawawi
Edited with permission from the original material by Norazah Yusof, Dayang
Norhayati Abang Jawawi, Noraniah Mohd Yassin, Radziah Mohamad, Paridah
Samsuri and Rohayanti Hassan, Programming Technique I (C++), First Edition,
2007.
Copyright © 2010
Disclaimer
This workbook and its contents are intended solely for the use of the subject Basic
Programming C to be taught at Fakulti Sains Komputer dan Sistem Maklumat,
Universiti Teknologi Malaysia, Skudai. The algorithms and programs in this
workbook have been included for their instructional value. They have been tested but
are not guaranteed for any particular purpose. The authors do not offer any warranties
or representations nor do they accept any liabilities with respect to their use. The
authors reserve the right to revise this publication and make changes from time to
time in its content without notice.
First Edition
November 2010
CONTENTS
INTRODUCTION v
TERMS vii
ii
5 WORKING WITH DATA 44
7 SELECTION OR DECISION 57
8 LOOP STATEMENTS 68
iii
Exercise 10 79
9 NESTED LOOP 82
10 PREDEFINED FUNCTIONS 88
11 USER-DEFINED FUNCTION 91
iv
INTRODUCTION
OBJECTIVE
Programming is an activity that requires problem solving skill. This activity requires
logical thinking, attention to detail, careful planning and elements of creativity and
arts. Basic Programming C subject needs the students to put in some 200 hours’
effort. 26 of these hours will be lectures and 26 in laboratory or tutorial. That leaves
148 hours split between reading the textbook and lectures notes, working on
programming assignments in their own time, and preparing for the practical and
written examinations. After the forth week or so, they need to work in developing
programs independently. In order to ensure their skill at an acceptable stage a short
assessment on problem solving will be given to them after the forth week. It is
expected that the students can achieve certain level of problem solving skill before
they can pursue to more complex programming techniques. Special workshop will be
set for the students who cannot meet the standard.
LABORATORY RESOURCES
The FSKSM laboratories are equipped with the C programming language which
Borland C++ software of version 5.02 is used for developing programs. This Borland
C++ version 5.02 software have integrated development environment (IDE), which
consists of a text editor, compiler, debugger, and other utilities integrated into one
package with a single set of menus. Preprocessing, compiling, linking, and even
executing a program is done with a single click of a button, or by selecting a single
item from a menu.
v
LABORATORY SESSION AND ASSESSMENT
For the Laboratory works, the students are expected to attempt a specified number of
small exercises in each lab. Do note that, some of the lab exercises are expected to be
submitted at the end of the session through UTM e-learning system. Normally, no
allowance will be made for absence. At least four of the lab works (as assigned by the
lecturer) will be assessed and counted 10% to the overall marks.
Further details about the assessment will be announced by the lecturer in the class.
ACKNOWLEDGEMENT
The authors gratefully acknowledge all contributors to this workbook in term of ideas,
selected questions and comments. Thanks to the Software Engineering Department
and Faculty of Computer Science and Information Systems for their support in
preparing this material.
REFERENCES
1. Tony Gaddis, Barret Krupnow, (2007), Starting out with C++, 5th edition
Brief version. Pearson Addison-Wesley.
2. W. Savitch, (2006), Problem Solving with C++. 6th Edition. Addison
Wesley.
3. H.M Deitel, P.J Deitel, (2005), C++ How to Program. 5th edition.
Prentice Hall.
4. Behrouz A.Forouzan, Richard F.Gilberg, (2004) Computer Science: A
Structured Approach Using C++, 2nd edition. Brooks/Cole Thomson
Learning.
vi
TERMS
ENGLISH MALAY
Algorithm Algoritma
Argument Argumen
Arithmetic operation Operasi aritmetik
Array Tatasusunan
Assembly stage Peringkat penghimpun
Assign Umpuk
Backup Bakup
Boot But atau memulakan
Buffer Penimbal
Character Aksara
Code segment Segmen aturcara
Column Lajur
Command Arahan
Compile Kompil
Constant Pemalar
Control structure Struktur kawalan
Copy Salin
Current directory Direktori semasa
Cursor Kursor
Cut Potong
Decision Keputusan
Declare Isytihar
Decrement Susutan
Define Takrif
Demonstrate Menunjuk cara
Device Peranti
Directory Direktori
Directory tree Pepohon direktori
Disk Cakera
Distance Jarak
Download Muat turun
Drive C Pemacu C
Editor Penyunting
Error Ralat
Executable file Fail boleh-laksana
Expression Ungkapan
Extension Sambungan
Field Medan
vii
File Fail
File operation Operasi fail
File stream object Objek aliran fail
File system path Laluan fail sistem
Floppy drive Pemacu liut
Flowchart Carta alir
Folder Direktori
Function Fungsi
Function prototype Prototaip fungsi
Global variable Pembolehubah sejagat
Hardware Perkakasan
Increment Tokokan
Index Indeks
Inline function Fungsi dalam baris
Invalid Tidak sah
Keyboard Papan kekunci
Load Muat
Local variable Pembolehubah setempat
Logic error Ralat logik
Loop Gelung
Main function Fungsi utama
Memory layout Hamparan ingatan
Menu bar Bar menu
Multiple Berbilang
Nested Tersarang
Nested loop Gelung tersarang
One dimensional array Tatasusunan satu dimensi
Open source Sumber terbuka
Operand Operan
Operating system Sistem pengoperasian
Overloaded function Fungsi sarat
Parameter Parameter
Pass by reference Hantar secara rujukan
Pass by value Hantar secara nilai
Paste Tampal
Pen drive Pemacu pen
Personal Computer (PC) Komputer peribadi
Pointer Penuding
Predefined function Fungsi takrifan piawai
Pre-processor Prapemproses
Program Aturcara
Program header Kepala aturcara
Program segment Segmen aturcara
Prompt Penggesa
Pseudo code Kod sudo
viii
Random Access Memory (RAM) Ingatan capaian rawak
Read Baca
Read Only Memory (ROM) Ingatan baca sahaja
Repetition Pengulangan
Return Memulangkan
Row Baris
Run Laksanakan
Runtime error Ralat masa larian
Save Simpan
Search text Carian teks
Selection Pilihan
Semantic Semantik
Shortcuts Capaian ringkas
Software Perisian
Statement Pernyataan
Stream Aliran
String Rentetan
Structured chart Carta berstruktur
Structured data Data berstruktur
Subscript Subskrip
Syntax Sintaksis
Syntax error Ralat sintaks
Text file Fail teks
Trace Jejak
Two-dimensional array Tatasusunan dua dimensi
Upload Muat naik
User defined function Fungsi takrifan pengguna
Valid Sah
Variable Pembolehubah
Velocity Halaju
Write Tulis
ix
LAB 1: RUNNING THE C PROGRAM
1. To use the Borland C++ software version 5.02 to enter C source code, compile,
link and run the C program.
[Untuk menggunakan perisian Borland C++ versi 5.02 untuk memasukkan
kod sumber C, mengkompil, memaut, dan melaksanakan aturcara C]
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
ii. Next, the ROM BIOS checks to see if there is a system disk in drive A.
If it is not found, it then checks to see if the system files are on drive C.
1
BASIC PROGRAMMING C
Once the system disk is found, a short set of instructions called the
boot record is loaded into RAM. The boot record contains the
information necessary to load the I/O handler into RAM.
[Seterusnya, ROM BIOS memeriksa sama ada terdapat cakera sistem
pada pemacu A. Jika ia tidak dijumpai, ia akan memeriksa sama ada
fail sistem berada di pemacu C. Sebaik sahaja cakera sistem ditemui,
satu set arahan pendek yang dinamakan rekod but dimuatkan ke dalam
RAM. But rekod ini mengandungi maklumat penting untuk memuatkan
pengendali I/O ke dalam RAM.]
iii. After the I/O handler is loaded, the system disk is then checked for the
presence of the operating system files (i.e. CONFIG.SYS,
COMMAND.COM and AUTOEXEC.BAT) and loads them into RAM.
[Setelah pengendali I/O dimuatkan, cakera system akan diperiksa bagi
kehadiran fail-fail sistem pengoperasian (seperti CONFIG.SYS,
COMMAND.COM and AUTOEXEC.BAT) dan memuatkannya ke
dalam RAM.]
iv. The PC that uses Windows 98, 2000 or XP, needs the user to enter a
password in order to access any program/files in the computer. For the
computer in the FSKSM lab, please get the password from the
technician in charge.
[Komputer peribadi yang menggunakan sistem pengoperasian
Windows 98, 2000 atau XP, memerlukan penggunanya memasukkan
kata laluan tertentu sebelum boleh mencapai mana-mana aturcara/fail
yang terdapat di dalam komputer tersebut. Bagi komputer di makmal
FSKSM, sila dapatkan kata laluan daripada juruteknik yang bertugas.]
vii. Wait until a dialog box appears for you to enter the password.
[Tunggu sehingga kekotak dialog dipaparkan untuk anda masukkan
kata laluan.]
2
LAB 1: RUNNING THE C++ PROGRAM
a. Click on the Start menu that is located at the bottom left of your
screen.
[Klik pada menu Start yang berada di bahagian bawah sebelah
kiri skrin.]
iii. The Borland C++ software version 5.02 will be presented as below:
[Perisian Borland C++ versi 5.02 akan dipamerkan seperti berikut:]
Figure 1.1 :
ii. To write a new program, click on the File menu, choose New, and
Text Edit option as follows:
3
BASIC PROGRAMMING C
[Untuk menulis aturcara yang baru, klik pada menu File, pilih New
dan Text Edit seperti berikut:]
Figure 1.2 :
Figure 1.3 :
iv. Type the following C statements. Do not type the line number.
[Taipkan pernyataan C seperti berikut. Jangan taipkan nombor baris.]
1 //Program 1.1
2 //Nama: Masitah Ghazali
3
4 #include <stdio.h>
5 #include <conio.h>
6
7 int main(void)
8 {
9 printf ("Hai!! Apa khabar?");
10 getch();
11 return 0;
}
4
LAB 1: RUNNING THE C++ PROGRAM
i. The program that you just wrote using the C editor is called the source
program. This source program resides in the computer’s main memory
(RAM). You need to save the source program into the secondary
storage (such as the hard disk, diskette, or pen drive) as a backup so
that you can use the program file at other time.
[Aturcara yang telah ditulis menggunakan editor C dikenali sebagai
aturcara sumber. Aturcara sumber ini berada di dalam ingatan utama
computer (RAM). Anda perlu menyimpan aturcara sumber ini ke
dalam storan sekunder (seperti cakera keras, disket, atau pemacu pen)
sebagai sokongan supaya anda boleh menggunakan fail aturcara ini
pada masa yang lain.]
ii. To save a source program into a new folder in the hard disk.
[Untuk menyimpan aturcara sumber ke dalam folder baru di cakera
keras:]
Figure 1.4 :
5
BASIC PROGRAMMING C
Figure 1.5 :
c. In the New Folder, type the folder name keep all of your
program files in that folder.
[Di bahagian New Folder, taipkan nama folder yang akan
menyimpan fail-fail aturcara anda]
d. Click twice at your folder and type the name of your source
program at the File name input box, as Hello1.c.
[Klik dua kali pada folder anda itu dan kemudian taipkan nama
fail aturcara sumber anda sebagai Hello1.c dan kekotak input
File Name]
Figure 1.6 :
i. After you created a program, you can compile it so that the source code
will be translated into object code. The C compiler will try to detect
any syntax errors in your program.
6
LAB 1: RUNNING THE C++ PROGRAM
Figure 1.7 :
7
BASIC PROGRAMMING C
Figure 1.8 :
i. The program that has successfully been compiled, can be executed (run)
so that the result will appear.
[Aturcara yang telah berjaya dikompil perlu dilaksanakan (run)
supaya boleh menghasilkan keputusan.]
ii. However, if error occurs, an error message will be displayed and the
programmer need to edit and recompile, as well as rerun the program
to produce the output.
[Bagaimanapun, jika terdapat ralat, mesej ralat akan dipamerkan dan
pengaturcara perlu membaikinya dan mengkompil semula serta
melaksana semula aturcara tersebut untuk menghasilkan output.]
a. Click on the Debug menu and choose Run, or press the Ctrl
and the F9 function key simultaneously.
[Klik pada menu Debug dan pilih Run, atau tekan pada
bebutang Ctrl dan kekunci fungsi F9 secara serentak]
8
LAB 1: RUNNING THE C++ PROGRAM
Figure 1.9 :
Figure 1.10 :
a. Click the File menu and chose Close, or click the cross image
at the top right hand corner the window.
[Klik pada menu File dan pilih Close, ataupun klik pada tanda
pangkah di bahagian atas sebelah kanan tetingkap aturcara
sumber tersebut.]
9
BASIC PROGRAMMING C
EXERCISE 2:
[LATIHAN 2]
Often you need to load existing C source file, edit the content and compile it.
[Seringkali anda perlu memuatkan fail sumber C sedia ada, mengedit kandungannya
serta menkompilnya.]
1. Load the Borland C++ software as in Exercise 1 Part 2 (see page 3).
[Muatkan perisian Borland C++ seperti Latihan 1 Bahagian 2. (Lihat
halaman 3)]
i. Click on the File menu and choose Open or click on the Open a file
icon as shown in figure 1.11 below.
[Buka fail sumber C sedia ada seperti berikut pada menu File dan
memilih Open atau dengan mengklik pada ikon Open a file seperti
yang ditunjukkan oleh rajah 1.11 berikut:]
Ikon
Open a File
Figure 1.11 :
ii. Once the dialog box appears, type the appropriate file name as shown
in figure 1.12 below.
[Apabila kekotak dialog dipamerkan, taipkan nama fail seperti tertera
dalam tajah 1.12 berikut.]
Figure 1.12 :
10
LAB 1: RUNNING THE C++ PROGRAM
1 //Program 1.2
2 //Nama pengaturcara: Masitah Ghazali
3
4 #include <stdio.h>
5 #include <conio.h>
6
7 int main(void)
8 {
9 printf ("Hai!! Apa khabar?\n");
10 printf ("Ucapan dari Masitah Ghazali\n");
11 getch();
12 return 0;
}
ii. Click on the Start menu and choose Turn Off Computer.
[Klik pada menu Start dan pilih Turn Off Computer.]
11
BASIC PROGRAMMING C
Figure 1.13 :
EXERCISE 3:
[LATIHAN 3]
1 //Program 1.1
2 //Nama: Masitah Ghazali
3
4 #include <stdio.h>
5 #include <conio.h>
6
7 int main(void)
8 {
9 printf ("Hai!! Apa khabar?\n");
10 getch();
11 return 0;
}
ii. Lines 4 and 5 are the preprocessor directive #include that include the
contents of the library file, namedly stdio.h and conio, in the
program. stdio.h is a standard C header file and contains
definitions for input and output, such as printf and scanf. While
12
LAB 1: RUNNING THE C++ PROGRAM
iii. Line 7 defines a function called main that begins the program
execution. The brackets without any word indicate the main function
has no parameters. The return type for main is int (i.e., an integer
number).
[Baris 7 menakrifkan satu fungsi bernama main yang memulakan
perlaksanaan aturcara. Tanda dua kurungan tanpa sebarang
perkataan di antaranya menunjukkan fungsi main tidak mempunyai
sebarang parameter. Jenis data yang dikembalikan oleh fungsi main
ialah int (iaitu, suatu nombor integer)]
iv. Line 8 is an open brace that marks the beginning of the body of main
function.
[Baris 8 merupakan pembuka kurungan berkeluk yang menandakan
permulaan badan fungsi main.]
13
BASIC PROGRAMMING C
vii. Line 11 is the return statement that the control of the program to the
operating system. It also determines the value of the return type that
match the main function.
[Baris 11 ini ialah pernyataan return yang akan mengalihkan kawalan
daripada aturcara kepada sistem pengoperasian. Ia juga akan
menentukan nilai bagi fungsi yang akan dipulangkan dan perlu
berpadanan dengan jenis data pulangan bagi fungsi main.]
viii. Line 12 is a close brace that marks the end of the body of main.
[Baris 12 merupakan penutup kurungan berkeluk yang menandakan
akhir bahagian badan fungsi main.]
1 /* Program 1.3
2 Nama pengaturcara: Masitah Ghazali
3 Tujuan aturcara : Masukkan nama dan tahun lahir
4 serta kira usia pengguna pada tahun ini */
5
6 #include <stdio.h> //Pre-processor directive
7 #include <conio.h> //Pre-processor directive
8
9 int main()
10 {
11 const int TahunIni=2010;
12 char nama[20];
13 int tahunlahir, umur;
14
15 printf ("Masukkan nama anda: ");
16 scanf ("%s", &nama);
17
18 printf ("Masukkan tahun anda dilahirkan: ");
19 scanf ("%d", &tahunlahir);
20
21 umur = TahunIni - tahunlahir;
22
23 printf ("Nama anda: %s", nama);
24 printf ("\nUsia anda: %d", umur, "tahun.");
25 getch();
26 return 0;
27 }
i. Type, save, compile, and run program 1.3 above. What will be the
output of the program for the given input?
14
LAB 1: RUNNING THE C++ PROGRAM
1 //Program 1.4
2 //Nama pengaturcara: Masitah Ghazali
3
4 #include <stdio.h>
5 #include <conio>
6
7 int main (void)
8 {
9 int workDays;
10 float workHours, payRate, weeklyPay;
11
12 workDays = 5;
13 workHours = 6.5;
14 payRate = 20.50;
15 weeklyPay = workDays * workHours * payRate;
16 printf ("Weekly Pay = %f", weeklyPay);
17 printf ("\n");
18 getch();
19 return 0;
20 }
i. Type, save, compile, and run the program. What will be the output of
the program?
[Taip, simpan, kompil, dan laksanakan aturcara tersebut. Apakah
output bagi aturcara di atas?]
15
LAB 2: DESIGNING PSEUDOCODE AND FLOWCHART
USING MICROSOFT WORD
ASSUMPTIONS
6. Students have the basic experience in loading and opening particular software
in Microsoft Windows.
[Pelajar mempunyai pengalaman asas memuat dan membuka perisian tertentu
dalam Microsoft Windows.]
LAB EXERCISES
i. Load the Microsoft Word software into the main memory of the
computer (i.e. RAM).
[Muatkan perisian Microsoft Word ke dalam ingatan utama komputer,
iaitu RAM.]
16
LAB 2: DESIGNING PSEUDOCODE AND FLOWCHART USING MICROSOFT WORD
Figure 2.1
OR
[Atau]
17
Algoritma 2.2 : Mengira hasil tambah bagi tiga nombor
1. Mula
2. Setkan HASILTAMBAH bersamaan 0
3. Baca NOMBOR1
4. Baca NOMBOR2
5. Baca NOMBOR3
6. Tambah NOMBOR1, NOMBOR2 dan NOMBOR3 dan simpan dlm
HASILTAMBAH
7. Paparkan HASILTAMBAH
8. Tamat
Figure 2.2
b. Click twice on the folder that contains your files. Then type
your word document filename. For example,
KodSudoKira3Nom as in Figure 2.3 below:
[Klik dua kali pada folder yang mengandungi fail-fail anda.
Kemudian taipkan nama fail dokumen word. Sebagai contoh,
KodSudoKira3Nom seperti Rajah 2.3 berikut:]
18
LAB 2: DESIGNING PSEUDOCODE AND FLOWCHART USING MICROSOFT WORD
Figure 2.3
Figure 2.4
19
b. On the following dialogue box, select Page Break and click on
the OK button. See Figure 2.5.
[Pada kekotak dialog berikut, pilih pada Page Break dan klik
pada bebutang OK. Lihat Rajah 2.5.]
Figure 2.5
3. Make sure that the Drawing submenu is activated. If it is not active, on the
View menu, select Toolbars and select Drawing as Figure 2.6 below:
[Pastikan bahagian Drawing diaktifkan. Jika tidak aktif, pada menu View,
pilih Toolbars dan pilih Drawing seperti Rajah 2.6 berikut:]
Figure 2.6
4. On the Drawing panel, click on the text box icon. See Figure 2.7.
[Pada panel Drawing, klik pada ikon kekotak teks. Lihat Rajah 2.7.]
20
LAB 2: DESIGNING PSEUDOCODE AND FLOWCHART USING MICROSOFT WORD
Figure 2.7
Start
6. Change its shape to a terminal symbol by clicking on the Draw menu, select
Change Autoshape, select Flowchart, select the terminator symbol. See
Figure 2.8.
[Ubah rupa supaya berbentuk simbol terminal dengan cara, klik pada menu
Draw, pilih Change Autoshape, pilih Flowchart, pilih simbol terminator.
Lihat Rajah 2.8.]
Figure 2.8
21
START
Display TOTAL
END
Figure 2.9
EXERCISE 3:
[LATIHAN 3]
22
LAB 2: DESIGNING PSEUDOCODE AND FLOWCHART USING MICROSOFT WORD
2. Using the Microsoft Word software, develop a pseudocode that assigns values
to variables as in Algorithm 2.4. Then trace the content of the variables and
determine the output of the Algorithm 2.4.
[Dengan menggunakan perisian Microsoft Word, bina kod sudo yang
mengumpukkan nilai kepada pembolehubah seperti Algoritma 2.4. Kemudian
jejak kandungan pembolehubah dan tentukan output bagi Algoritma 2.4
tersebut.]
3. Using the Microsoft Word software, develop a pseudocode that reads the
radius of a circle, and computes the area of the circle as in Algorithm 2.5.
[Dengan menggunakan perisian Microsoft Word, bina kod sudo seperti
Algoritma 2.5 yang membaca jejari bagi suatu bulatan dan mengira luas
kawasan bulatan tersebut.]
i. Trace the content of the variables and determine the output of the
Algorithm 2.5 if the input for Radius is:
[Jejak kandungan pembolehubah serta tentukan output Algoritma 2.5
sekiranya input jejari (Radius) ialah:]
a. 3
b. 10
c. 150
4. Using the Microsoft Word software, develop a pseudocode that reads the
money collection of a user. The algorithm computes the number of Ringgit
and cents (50, 20, 10 5, and 1 cent) that can be extracted from the collection.
Tips: You can use the Modulus operator that obtains the remainder from a
division.
23
[Dengan menggunakan perisian Microsoft Word, bina kod sudo yang
membaca koleksi duit pengguna. Algoritma tersebut mengira bilangan
Ringgit dan syiling (50, 20, 10, 5, dan 1 sen) yang boleh diasing-asingkan
daripada koleksi tersebut. Panduan: Anda boleh menggunakan operator
Modulus untuk mendapatkan baki daripada hasil bahagi.]
a. 927
b. 1274
c. 6785
d. 35565
24
LAB 2: DESIGNING PSEUDOCODE AND FLOWCHART USING MICROSOFT WORD
EXERCISE 4:
[LATIHAN 4]
1. Using the Microsoft Word software, draw a flowchart as in Figure 2.10 that
calculates the payment for normal and overtime working hours of an
employee. Then trace the content of the variables and determine the output
displayed from the algorithm.
[Dengan menggunakan perisian Microsoft Word, lukiskan carta alir seperti
Rajah 2.10 yang mengira bayaran untuk jam kerja normal dan lebih masa
seseorang pekerja. Kemudian jejak kandungan pembolehubah dan tentukan
output algoritma tersebut.]
START
Set NormalHours = 20
Set OverTimeHours = 8
Display TOTAL
END
Figure 2.10
25
2. Using the Microsoft Word software, draw a flowchart as in Figure 2.11 that
calculates the total cost of item purchased.
[Dengan menggunakan perisian Microsoft Word, lukiskan carta alir seperti
Rajah 2.11 yang mengira jumlah harga sesuatu pembelian.]
Start
Read ItemName
Read PricePerUnit
Read Quantity
Display "Total
payment"
Read Payment
End
Figure 2.11
26
LAB 2: DESIGNING PSEUDOCODE AND FLOWCHART USING MICROSOFT WORD
i. Trace the content of the variables and determine the output of the
algorithm if the input values are as follows:
[Jejak kandungan pembolehubah dan tentukan output algoritma
tersebut sekiranya input adalah seperti berikut:]
a. ItemName: Pencil
PricePerUnit: 0.50
Quantity: 15
Payment: 10.00
c. ItemName: Pencil
PricePerUnit: 3
Quantity: 1
Payment: 5.00
EXERCISE 5:
[LATIHAN 5]
Given the following set of problems. Analyze each problem and identify the input,
formula and the output. Write the pseudocode and draw the flowchart for the problem.
[Diberi masalah-masalah seperti berikut. Analisis setiap masalah dan kenalpasti
input, formula serta output. Tuliskan kod sudo dan lakarkan carta alir bagi masalah
berkenaan.]
1. Read three numbers. Calculate the sum of those three numbers and find the
average. Display all the three numbers, as well as the total of those numbers
and the in average.
[Baca tiga nombor. Kira dan jumlahkan ketiga-tiga nombor dan cari purata.
Paparkan ketiga-tiga nombor, dan juga jumlah ketiga-tiga nombor serta
puratanya.]
Output:
Input:
Formula:
27
2. Calculate the average weight of four students. Attempt to analyze this problem
by stating it’s input, output and the formula required to determine the average
weight. Display each student’s weight and the average weight calculated.
[Cari purata berat bagi 4 orang pelajar. Paparkan berat setiap pelajar dan
purata yang dikira. Cuba analisa permasalahan ini dengan menyatakan input,
output serta formula yang diperlukan untuk mengira purata.]
Output:
Input:
Formula:
3. Convert the time entered by the user in the form of day, hours and minute to
minutes. The conversion unit is as follows:
1 day is equivalent to 24 hours
1 hour is equivalent to 60 minutes
[Tukarkan masa yang dimasukkan oleh pengguna dalam bentuk hari, jam dan
minit ke minit. Pertukaran unit adalah seperti berikut:
1 hari bersamaan dengan 24 jam
1 jam bersamaan dengan 60 minit]
Output:
Input:
Formula:
4. Convert the temperature entered by the user in the unit of Fahrenheit to the
unit of Celcius. The conversion formula is as follows:
Celsius x 9
Fahrenheit = + 32
5
[Tukarkan suhu yang dimasukkan oleh pengguna ke dalam unit Fahrenheit
kepada unit Celcius. Formula penukaran unit adalah seperti berikut:]
Output:
Input:
Formula:
28
LAB 2: DESIGNING PSEUDOCODE AND FLOWCHART USING MICROSOFT WORD
EXERCISE 6:
[LATIHAN 6]
Given the following problem. Analyze the problem and design its solution using
structured chart. Then write the appropriate pseudocode or flowchart.
[Diberi masalah berikut. Analisa masalah tersebut dan reka bentuk penyelesaiannya
menggunakan carta berstruktur. Kemudian, tuliskan kod sudo atau carta alir yang
bersesuaian.]
Figure 2.12
Calculate the
area of triangle
29
LAB 3: DESIGN PSEUDOCODE/FLOWCHART TO
SOLVE SELECTION AND LOOP PROBLEM
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
1. Based on the following information regarding input, output and process, write
the pseudocode and flowchart to solve the problem.
[Berdasarkan maklumat input, output dan proses di bawah, tuliskan kod sudo
dan carta alir untuk menyelesaikan masalah tersebut.]
Input :
i. Purchase price (in ringgit).
[Harga beli (dalam ringgit).]
30
LAB 3: DESIGN PSEUDOCODE/FLOWCHART TO SOLVE SELECTION AND LOOP PROBLEM
Process :
Difference = Purchase price - Selling price
If Difference > 0, Output = "Profit"
If Difference = 0, Output = "Return Capital"
If Difference < 0, Output = "Loss"
2. Draw suitable flowchart symbol and write the correct C expression for the
following conditions.
[Lukis simbol carta alir yang sesuai dan tuliskan ungkapan C yang betul bagi
setiap syarat di bawah.]
3. Execute the flowchart in Figure 3.1 using the input values supplied in the
following Table 3.1. Record the output statements.
[Laksanakan carta alir di Rajah 3.1 menggunakan data input yang diberikan
pada Jadual 3.1. Rekodkan setiap output yang dipaparkan.]
Start
Read N
True
N<0 N is negative
False
True
N>0 N is positive
False
End
Figure 3.1
31
BASIC PROGRAMMING C
Table 3.1
Input Value Output Statement
7
-5
0
3.5
ii. Redraw the flowchart and add another selection symbol into Figure 3.1
and an associated output to write "N is zero" when 0 is entered.
[Lukis semula carta alir tersebut dan tambah satu lagi simbol pilihan
pada Rajah 3.1 dan juga simbol cetak yang bermesej "N is zero"
apabila 0 dimasukkan.]
Figure 3.2
Start
Read N
True
(N % 2) = = 0 N is even number
False
N is odd number
End
Figure 3.3
32
LAB 3: DESIGN PSEUDOCODE/FLOWCHART TO SOLVE SELECTION AND LOOP PROBLEM
5. Trace the following pseudo code using the input values given in Table 3.2.
Record the output statements.
[Jejak kod sudo berikut menggunakan data input yang diberi pada Jadual 3.2.
Rekod setiap output yang dipaparkan.]
Table 3.2
Input Value Output Statement
5.0
3.0
2.5
15.0
12.0
11.5
6. The electric company gives a discount on electricity based upon usage. The
normal rate is RM0.60 per Kilowatt Hour (KWH). If the number of KWH is
above 1000, then the rate is RM0.45 per KWH.
[Syarikat elektrik telah memberikan diskaun ke atas penggunaan tenaga
elektrik. Kadar normal ialah RM60 bagi setiap jam Kilowatt (KWH). Jika
amaun KWH melebihi 1000, maka kadarnya ialah RM0.45 setiap KWH.]
i. Design a pseudo code or flowchart that requires the user to enter the
number of Kilowatt Hours used and then calculates and displays the
total electric bill.
[Bina kod sudo atau carta alir yang meminta pengguna memasukkan
bilangan penggunaan jam Kilowat dan seterusnya mengira serta
memaparkan jumlah bil elektrik.]
33
BASIC PROGRAMMING C
ii. According to the algorithm developed in (i), determine the cost for the
following usage:
[Berdasarkan algoritma yang dibina pada (i), tentukan kos bagi
penggunaan berikut:]
a. 900 KWH?
b. 1,754 KWH?
c. 10,000 KWH?
iii. Then, modify your algorithm in (i) to compute the electric bill based
on the rates as stipulated in the conditions supplied by Table 3.1.
[Seterusnya, ubahsuai algoritma (i), untuk mengira bil elektrik
berdasarkan kadar penggunaan elektrik mengikut syarat-syarat pada
Jadual 3.3.]
Table 3.3
Usage Rate
0-999 KWH $0.60
1000-1499 KWH $0.45
1500-1999 KWH $0.40
2000 or more KWH $0.35
iv. Modify your algorithm in (iii) and let's suppose that the electric rates
are based upon certain rate classes within each grouping as depicted in
Figure 3.4.
[Ubahsuai algoritma (iii), serta andaikan bahawa kadar elektrik lain
adalah berpandukan kepada kelas kadar tertentu dalam kumpulan
yang ditunjukkan pada Rajah 3.4.]
0 - 999 KWH
commercial rate class RM 0.49
r1 rate class RM 0.57
r2 rate class RM 0.60
1000-1499 KWH
commercial rate class RM 0.38
r1 rate class RM 0.43
r2 rate class RM 0.44
r3 rate class RM 0.45
34
LAB 3: DESIGN PSEUDOCODE/FLOWCHART TO SOLVE SELECTION AND LOOP PROBLEM
EXERCISE 2:
[LATIHAN 2]
1. Trace the flowchart in Figure 3.5 and answer the following questions.
[Jejak carta alir pada Rajah 3.5 dan jawab soalan-soalan berikut.]
Start
total = 0
i=1
true
i < 10 total = total + i i=i+2
false
Print total
End
Figure 3.5
iii. Modify the flowchart in Figure 3.5 by using the decrement counter
loop without changing the variables involved and the number of loops
involved.
[Ubahsuai carta alir pada Rajah 3.5 dengan menggunakan gelung
pembilang menyusut tanpa mengubah pembolehubah serta bilangan
gelung yang terlibat.]
2. Trace the flowchart in Figure 3.6 and answer the following questions.
[Jejak carta alir pada Rajah 3.6 dan jawab soalan-soalan berikut.]
35
BASIC PROGRAMMING C
Start
total = 0
count = 0
count = count + 1
True
count < 5
False
Print total
End
Figure 3.6
iv. Modify the flowchart in Figure 3.6 by using while loop without
changing the variables and the number of loops involved.
[Ubahsuai carta alir pada Rajah 3.6 dengan menggunakan gelung
while tanpa mengubah pembolehubah serta bilangan gelung yang
terlibat.]
3. Trace the following pseudocode and record the output statements in Table 3.4.
[Jejak kod sudo berikut dan rekod pernyataan output pada Jadual 3.4.]
36
LAB 3: DESIGN PSEUDOCODE/FLOWCHART TO SOLVE SELECTION AND LOOP PROBLEM
Table 3.4
Input Value Output Statement
1 2 3 0
0 1 2 3
1 2 3 4 5 6
0
4. Trace the following pseudocode and answer the following questions that
follows.
[Jejak kod sudo berikut dan jawab soalan-soalan berikutnya.]
i. Trace Algorithm 3.3 and fill in the Table 3.5 with appropriate answers
for the given input.
[Jejak Algoritma 3.3 dan isikan kekotak kosong pada Jadual 3.5
dengan jawapan yang betul bagi data input yang diberi.]
Input :
20 12 1
11 51 2
37
BASIC PROGRAMMING C
Table 3.5
repeat repeat=1 no1 no2 no1+no2
1 true
ii. Modify Algorithm 3.3 by changing the sentinel value where the loop
will be terminated if val is not equal to ‘y’ or ‘Y’.
[Ubahsuai Algoritma 3.3 dengan menukarkan nilai sentinel yang
memberhentikan gelung jika val bukan ‘y’ atau ‘Y’.]
5. Write a pseudo code that will generate the output as depicted in Figure 3.7.
[Tuliskan kod sudo yang akan menjana output seperti di Rajah 3.7.]
1,0
2,0 2,1
3,0 3,1 3,2
4,0 4,1 4,2 4,3
Figure 3.7
EXERCISE 3:
[LATIHAN 3]
1. Given the velocity, v, the distance, d, and the time, t, of a car that accelerates
from rest at constant acceleration, a.
[Diberi halaju, v , jarak, d dan masa, t, bagi sebuah kereta yang bergerak
daripada pegun kepada pecutan tetap, a.]
v = at
d = ½ at2
Draw a flowchart diagram to determine v and d as every second for the first
10 seconds for a car with acceleration of a = 1.55 m/s2. The flowchart
should be able to print the velocity, v and distance, d every 2 seconds.
[Lukis cartalir yang akan mengira nilai v dan d untuk setiap saat bagi tempoh
10 saat dengan pecutan a = 1.55 m/s2. Cartalir anda akan mencetak
halaju, v dan jarak, d bagi setiap sela 2 saat.]
38
LAB 3: DESIGN PSEUDOCODE/FLOWCHART TO SOLVE SELECTION AND LOOP PROBLEM
* * * * *
* * * *
* * *
* *
*
Figure 3.8
3. Construct a pseudo code or flowchart which reads in two integer values. Then
display all the numbers that is located between two numbers. If the first
number entered is smaller than the second number entered, print all numbers
in ascending order. On the other hand, if the first number entered is greater
than the second number entered, print all numbers in descending order. Figure
3.9 depicted the example for these cases.
[Bina kod sudo atau carta alir yang akan membaca dua nilai integer.
Kemudian dua nombor tadi akan dipamerkan termasuklah nombor-nombor
yang terletak di antara kedua-dua nombor tersebut. Sekiranya nombor
pertama yang dimasukkan adalah lebih kecil daripada nombor kedua, maka
tertib paparan nombor adalah secara menaik. Sebaliknya, jika nombor
pertama yang dimasukkan adalah lebih besar daripada nombor kedua, maka
susunan paparan nombor adalah dalam keadaan menurun. Rajah 3.9
menggambarkan contoh bagi kes-kes ini.]
Input : 3 7
Output : 3 4 5 6 7
Input : 7 3
Output : 7 6 5 4 3
Figure 3.9
39
LAB 4: CONVERTING ALGORITHM TO C CODE
3. To compile, link and run the C program and produce the result.
[Untuk mengkompil, memaut, dan melaksana aturcara C serta menghasilkan
keputusan.]
ASSUMPTIONS
1. Students have the experience in developing pseudo code and flow chart.
[Pelajar mempunyai pengalaman dalam membina kod sudo dan carta alir.]
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
1. Convert the pseudo code of Algorithm 2.3 into correct C code. Compile and
run the program and state the output of the program.
[Tukarkan kod sudo Algoritma 2.3 ke dalam kod C dengan betul. Kompil dan
larikan aturcara dan nyatakan output bagi aturcara tersebut.]
2. Convert the pseudo code of Algorithm 2.4 into correct C code. Compile and
run the program and state the output of the program.
[Tukarkan kod sudo Algoritma 2.4 ke dalam kod C dengan betul. Kompil dan
larikan aturcara dan nyatakan output bagi aturcara tersebut.]
40
LAB 4: CONVERTING ALGORITHM TO C CODE
3. Convert the pseudo code of Algorithm 2.5 into correct C code. Compile and
run the program and state the output of the program if the Radius is input as:
[Tukarkan kod sudo Algoritma 2.5 ke dalam kod C dengan betul. Kompil dan
larikan aturcara dan nyatakan output bagi aturcara tersebut jika jejari input
adalah:]
i. 67
ii. 320
iii. 19
4. Convert the pseudo code of Algorithm 2.6 into correct C code. Compile and
run the program and state the output of the program if the Collection is
input as:
[Tukarkan kod sudo Algoritma 2.6 ke dalam kod C dengan betul. Kompil dan
larikan aturcara dan nyatakan output bagi aturcara tersebut jika Simpanan
input adalah:]
i. 89123
ii. 45560
iii. 12
EXERCISE 2:
[LATIHAN 2]
1. Convert the flow chart of Figure 2.10 into correct C code. Compile and run
the program and state the output of the program.
[Tukarkan carta alir Rajah 2.10 ke dalam kod C dengan betul. Kompil dan
larikan aturcara dan nyatakan output bagi aturcara tersebut.]
2. Convert the flow chart of Figure 2.11 into correct C code. Compile and run
the program and state the output of the program if the input for the variables
are as follows:
[Tukarkan carta alir Rajah 2.11 ke dalam kod C dengan betul. Kompil dan
larikan aturcara dan nyatakan output bagi aturcara tersebut jika input
pembolehubah adalah seperti berikut:]
i. ItemName: Pencil
PricePerUnit: 0.50
Quantity: 15
41
BASIC PROGRAMMING C
EXERCISE 3:
[LATIHAN 3]
Given the following C program, compile and run the program. Write down any
syntax error and logic error that occurs. Rewrite the program to correct the error.
[Diberi aturcara C di bawah, kompil dan larikan aturcara tersebut. Tuliskan semula
aturcara untuk membetulkan sintaks.]
1.
1 //Program 4.1
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main(){
6 Printf("I like programming ");
7 Getch();
8 Return 0;
9 }
2.
1 //Program 4.2
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main (){
6 int nilai1;
7 nilai1 = 4;
8 printf("%d+%d=%d", nilai1, nilai2,
nilai1+nilai2);
9 getch();
10 return 0;
11 }
3.
1 //Program 4.3
2 #include <stdio.h>
3 #include <conio.h>
4 void main ( )
5 {
6 int 125umur
7 125umur = 125;
8 printf "umur= %d tahun", umur);
42
LAB 4: CONVERTING ALGORITHM TO C CODE
4.
1 //Program 4.4
2 #include <stdio.h>
3 #include <conio.h>
4 int main()
5 {
6 printf("’This is my simple program’");
7 getch();
8 return 0;
9 }
5.
1 //Program 4.5
2 #include <stdio.h>
3 #include <conio.h>
4 void my_address (void)
5 {
6 printf("Dayang Norhayati Abang Jawawi\n");
7 printf("\tFakulti Sains Komputer");
8 printf("dan Sistem Maklumat\n");
9 printf("\tSkudai, Johor\n");
10 }
11
12 void main ( )
13 {
14 print_my_address();
15 getch();
16 }
6.
1 //Program 4.6
2 #include <stdio.h>
3 #include <conio.h>
4 int main (){
5 char c1, c2, c3, c4;
6 c1=65; c2='A'; c3=0x41; c4=0101;
7 printf("%c %d %f %s", c1, c2, c3, c4);
8 getch();
9 return 0;
}
43
LAB 5: WORKING WITH DATA
4. Write simple programs that assign values to variables, process the values and
display the results.
[Menulis satu aturcara yang mudah yang dapat mengumpukkan nilai kepada
pembolehubah, memproses nilai-nilai tersebut dan memaparkan hasil operasi
tersebut.]
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
44
LAB 5: WORKING WITH DATA
EXERCISE 2:
[LATIHAN 2]
1. Download Program 5.1. There are a number of syntax errors in the Program
5.1. Locate as many as you can.
[Muat turun Program 5.1. Terdapat beberapa ralat sintaks di dalam Program
5.1. Kenalpasti sebanyak yang mungkin.]
1 //Program 5.1
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 int a,b;
8 a=3;
9 b=4;
10 c=a+b;
11 printf ("The value of c is %d, c)";
12 getch();
13 return 0;
14 }
45
BASIC PROGRAMMING C
EXERCISE 3:
[LATIHAN 3]
1 //Program 5.2
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 int length, width, area;
8
9 length = 12;
10 width = 13;
11 area=length*width;
12 printf ("Area: %d", area, "\n");
13 getch();
14 return 0;
15 }
4. Now, modify the Program 5.2 by changing the value of length to 12.12 and
width to 13.12. Compile and run the modified program. What is the output?
Explain the output.
[Ubah aturcara di dalam Program 5.2 dengan menukarkan nilai length
kepada 12.12 dan width kepada 13.12. Kompil dan laksanakan aturcara
yang telah diubahsuai. Apakah hasilnya. Berikan penerangan tentang hasil
tersebut.]
5. Now, change the length and width variable type to float. Compile and
run the modified program. What is the output?
[Ubah pembolehubah length dan width kepada jenis float. Kompil dan
laksanakan aturcara yang telah diubahsuai. Apakah hasilnya?]
46
LAB 5: WORKING WITH DATA
EXERCISE 4:
[LATIHAN 4]
1. What will be printed by the extracted code below. Explain how you get such
output.
[Apakah yang akan dicetak oleh cebisan kod di bawah. Terangkan bagaimana
kamu boleh mendapat hasil tersebut.]
1 //Program 5.3
2
3 int n, m, x, y;
4 m=10;
5 n=m++*2;
6 printf ("n: %d", n);
7 printf ("\nm: %d", m);
8
9 x=10;
10 y=++x*2;
11 printf ("\nx: %d", x);
12 printf ("\ny: %d", y);
2. What is the final value of t? Why such output? Explain the output.
[Apakah hasil akhir nilai t? Kenapa hasil tersebut dihasilkan? Berikan
penerangan tentang hasil tersebut.]
1 //Program 5.4
2
3 int j=2, k=3;
4 double r=24.5, s=3.0, t1, t2;
5
6 t1*=r+s;
7 t2=r-s*3%(2+j)/k;
47
BASIC PROGRAMMING C
EXERCISE 5:
[LATIHAN 5]
1. Start
2. Store 12.95 in the item1 variable.
3. Store 24.95 in the item2 variable.
4. Store 6.95 in the item3 variable.
5. Sum up the three variables and store the result in the
subtotal variable.
6. Multiply the subtotal variable with 0.06 and store the
result in the sales tax variable.
7. Subtract the sales tax amount from the subtotal and
store the result in the total variable.
8. Display each item’s value, the subtotal value, the
amount of sales tax and the total.
9. End
3. Convert the designed solution for "Get the input values" (Lab 2,
Exercise 6, Question 1) to C code.
[Tukarkan penyelesaian yang telah direkabentuk bagi "Get the input
values" (Lab 2, Exercise 6, Question 1) kepada kod C.]
48
LAB 5: WORKING WITH DATA
EXERCISE 6:
[LATIHAN 6]
1. Write a program that computes the tax and tip of a restaurant bill for a patron
with a cost of RM50.60. The tax should be 10% of the meal cost. The tip
should be 5% of the total after adding the tax. Display the cost, tax amount, tip
amount and total bill on the screen.
[Tuliskan satu aturcara yang akan mengira nilai cukai dan tip untuk bil
restoran yang mempunyai nilai kos RM50.60. Cukai ialah 10% daripada kos
tersebut. Tip pula ialah 5% daripada jumlah kos setelah dicampur dengan
cukai. Paparkan nilai kos, nilai cukai, nilai tip dan jumlah bil di skrin.]
49
LAB 6: INPUT & OUTPUT
2. To write simple programs that read numbers and text, process the input and
display the results.
[Untuk menulis sebuah aturcara mudah yang dapat membaca nombor-nombor
dan teks, memproses data masukan dan memaparkan hasil-hasil proses
tersebu.]
3. To format output.
[Untuk memformat output.]
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
50
LAB 6: INPUT & OUTPUT
iv. Add a value of 1 to the counter variable and store the result to the
counter variable.
[Tambah nilai 1 dalam pembolehubah counter dan simpan hasil
dalam pembolehubah counter.]
EXERCISE 2:
[LATIHAN 2]
1 //Program 6.1
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main ()
6 {
7 char char1;
8 char char2;
9 char char3;
10 char char4;
11 printf("Input four characters > ");
12 scanf ("%c%c%c%c", &char1, &char2, &char3,
13 &char4);
14 printf("%c %c %c %c", char1, char2, char3,
15 char4);
51
BASIC PROGRAMMING C
16 getch();
17 return 0;
18 }
1 //Program 6.2
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main ()
6 {
7 char char1;
8 char char2;
9 char char3;
10 char char4;
11 printf("Input four characters > ");
12 char1=getchar();
13 char2=getchar();
14 char3=getchar();
15 char4=getchar();
16 putchar(char1);
17 putchar(char2);
18 putchar(char3);
19 putchar(char4);
20 getch();
21 return 0;
22 }
2. Compile and run them with the same set of the input data. e.g. (a b c d).
Examine the results carefully.
[Kompil dan laksanakan aturcara-aturcara tersebut dengan set data input
yang sama (contoh a b c d). Semak hasil tersebut secara teliti. ]
3. Understand what each line of the statement in the program does. In your own
words, explain what the program does and the difference between the two
programs.
[Fahamkan apa yang dilakukan oleh setiap baris di pernyataan dalam
aturcara tersebut. Di dalam ayat kamu sendiri, terangkan apa yang dilakukan
oleh setiap aturcara tersebut lakukan dan perbezaan di antara kedua-dua
aturcara tersebut.]
EXERCISE 3:
[LATIHAN 3]
1. Write a C program that asks the user to enter an integer, a floating point
number, and a character, and write the results back out. All output must be
must be in the format shown in the sample output.
[Tulis satu aturcara C yang meminta pengguna memasukkan satu nilai integer,
satu nilai titik terapung dan satu aksara, dan paparkan semula nilai-nilai
52
LAB 6: INPUT & OUTPUT
Sample input:
Enter an integer: 7
Enter a decimal number: 2.25
Enter a single character: r
Sample output:
You entered 7
You entered 2.25
You entered r
2. Write a C program that will read your yearly gross wage from a keyboard,
calculate and display your monthly net wage. Assuming your yearly gross
wage is between RM50,000 and RM80,000. Below are the deductions that
need to be considered:
EXERCISE 4:
[LATIHAN 4]
1 //Program 6.3
2 #include <stdio.h>
3
4 int main()
5 {
6
7 float val1, val2, val3, val4;
8 FILE *inData;
9 FILE *outData;
10
11 inData = fopen("DataIn.txt", "r");
12 outData = fopen("DataOut.txt", "w");
13
53
BASIC PROGRAMMING C
2. Create the input data file DataIn.txt. The file consists of the following data:
[Cipta satu fail input DataIn.txt. Fail tersebut mengandungi data-data
berikut:]
5.5
6.6
7.7
8.8
3. Compile and run Program 6.3. Examine the results carefully. Understand
what each line of the statement in the program does. In your own words,
explain what the program does.
[Kompil dan laksanakan Program 6.3. Kaji hasil nya dengan teliti. Fahamkan
apa yang dilakukan oleh setiap baris pernyataan di dalam aturcara tersebut.
Di dalam ayat kamu sendiri, terangkan apa yang aturcara tersebut
laksanakan.]
4. Modify the program so it also outputs the average of the four input numbers.
[Ubahsuai Program 6.3 aturcara tersebut supaya ia menghasilkan purata
keempat-empat nombor tersebut.]
EXERCISE 5:
[LATIHAN 5]
1 //Program 6.4
2 #include <stdio.h>
3 #include <conio.h>
4 int main()
5 {
6 int n;
7 float f;
8 char s[100];
9
10 printf("Input one integer: ");
11 scanf("%d", &n);
12
13 printf("%d\n%6d\n%-6dend\n", n, n, n, n);
14
54
LAB 6: INPUT & OUTPUT
2. Compile and run Program 6.4. Examine the results carefully. Understand
what each line of the statement in the program does. In your own words,
explain what the program does.
[Kompil dan laksanakan Program 6.4. Periksa hasilnya dengan teliti.
Fahamkan apa yang dilakukan oleh setiap baris arahan di dalam aturcara
tersebut lakukan. Di dalam ayat kamu sendiri, terangkan apa yang dilakukan
oleh aturcara tersebut.]
EXERCISE 6:
[LATIHAN 6]
Nilai matawang tersebut mestilah berjenis titik terapung, dengan dua tempat
perpuluhan. Pastikan titik perpuluhan tersebut dipaparkan.]
55
BASIC PROGRAMMING C
Rate is the monthly interest rate, which is the annual interest rate divided by
12 (e.g. 12% annual interest would be 1 percent monthly interest). N is the
number of payments and L is the amount of the loan. Write a program that
asks for these values and displays a report as follows:
[Rate merujuk kepada kadar interest bulanan, iaitu kadar interest tahunan
dibahagi dengan 12 (contohnya, kadar interest bulanan untuk 12% kadar
interest tahunan ialah 1%). N ialah bilangan pembayaran dan L ialah jumlah
pinjaman. Tulis satu aturcara yang akan membaca nilai-nilai tersebut dan
memaparkan report seperti format di bawah:]
56
LAB 7: SELECTION OR DECISION
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
1. Given the following declarations, evaluate the expression below and assign
true or false value for each expression.
[Diberi pengisytiharan berikut, selesaikan ungkapan di bawah serta berikan
nilai true atau false untuk setiap ungkapan.]
57
BASIC PROGRAMMING C
i. !found
ii. !number
iii. (number >= xint) && (number<=yint)
iv. (found || flag)
v. (xint != yint)
vi. (ydouble * 10) <= xdouble
vii. 'A'<= ch && ch<='Z'
viii. number-5 == xint) && !flag
EXERCISE 2:
[LATIHAN 2]
1. Download Program 7.1. Study the code and run the program.
[Muat turun Program 7.1. Fahamkan aturcara tersebut dan laksanakannya.]
1 //Program 7.1
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main(){
6 double mark;
7
8 printf ("Enter your mark: ");
9 scanf ("%lf", &mark);
10
11 if (mark >= 30)
12 printf ("TEST 1 -> Pass\n");
13 if (mark < 30)
14 printf ("TEST 1 -> Fail\n");
15
16 getch();
17 return 0;
18 }
58
LAB 7: SELECTION OR DECISION
ii. Change the usage of the 2 if statements (Line 11 and Line 13) to an
if..else statement.
[Tukarkan penggunaan 2 kenyataan if (Baris 11 dan Baris 13) kepada
kenyataan if..else.]
iii. Show the difference between the usage of the 2 if statements and the
if..else statement using a flowchart.
[Tunjukkan perbezaan penggunaan 2 kenyataan if dan if..else
dengan menggunakan carta alir.]
2. Download Program 7.2. The program requests the user to input Test 1 mark.
Contribution to the final mark will be calculated if the Test 1 mark is greater
than or equal to 30%, and if the mark is less than 30% the student is required
to re-sit the test. The contribution is 20% of Test 1 mark to the final mark.
[Muat turun Program 7.2. Program tersebut meminta pengguna memasukkan
markah Test 1. Sumbangan kepada markah akhir akan dikira jika markah Test
1 yang dimasukkan adalah lebih besar atau sama dengan 30%, dan jika
kurang daripada 30% pelajar perlu menduduki Test 1 sekali lagi. Test 1
memberi sumbangan 20% kepada markah akhir.]
1 //Program 7.2
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main(){
6 double mark, final20p=0;
7
8 printf ("Enter your mark: ");
9 scanf ("%lf", &mark);
10
11 if (mark >= 30)
12 printf ("TEST 1 -> Pass\n");
13 final20p = ((20.0/100.0) * mark);
14 printf ("Contribution to final mark %d”,
15 final20p);
16 if (mark < 30)
17 printf ("TEST 1 -> Fail\n");
18 printf ("Please re-sit TEST 1\n");
19 getch();
20 return 0;
21 }
59
BASIC PROGRAMMING C
EXERCISE 3:
[LATIHAN 3]
1. Download Program 7.3. Study the code and run the program.
[Muat turun Program 7.3. Fahamkan aturcara tersebut dan laksanakannya.]
1 //Program 7.3
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main(){
6 double mark;
7
8 print ("Enter your mark");
9 scanf ("%lf", &mark);
10
11 if (mark >=75)
12 printf ("Your score: A\n");
13 if ((mark <75)&& (mark>=60))
14 printf ("Your score: B\n");
15 if ((mark <60)&& (mark>=45))
16 printf ("Your score: C\n");
17 if ((mark <45)&& (mark>=30))
18 printf ("Your score: D\n");
19 if (mark <30)
20 printf ("Your score: E\n");
21 getch();
22 return 0;
23 }
iii. Given the input mark = 90.6, identify which if statement will be
evaluated and what are the results of the evaluated expression.
[Diberi input mark = 90.6, kenal pasti garis kenyataan if yang akan
dinilai dan keputusan penilaian ungkapan tersebut.]
2. Download Program 7.4. Study the code and run the program.
[Muat turun Program 7.4. Fahamkan aturcara tersebut dan laksanakannya.]
1 //Program 7.4
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main(){
6 double mark;
7
8 print ("Enter your mark");
9 scanf ("%lf", &mark);
60
LAB 7: SELECTION OR DECISION
10
11 if (mark >=75)
12 printf ("Your score: A\n");
13 else if ((mark <75)&& (mark>=60))
14 printf ("Your score: B\n");
15 else if ((mark <60)&& (mark>=45))
16 printf ("Your score: C\n");
17 else if ((mark <45)&& (mark>=30))
18 printf ("Your score: D\n");
19 else if (mark <30)
20 printf ("Your score: E\n");
21 getch();
22 return 0;
23 }
ii. Given the input mark = 90.6, identify which if statement will be
evaluated and what are the results of the evaluated expression.
[Diberi input mark = 90.6, kenal pasti garis kenyataan if yang akan
dinilai dan keputuan penilaian ungkapan tersebut.]
iii. Explain the difference between the if statement in Program 7.3 with
the if..else..if statement in Program 7.4.
[Jelaskan perbezaan kenyataan if dalam Program 7.3 dan kenyataan
if..else..if dalam Program 7.4.]
EXERCISE 4:
[LATIHAN 4]
1 //Program 7.5
2 #include <studio.h>
3 #include <conio.h>
4
5 int main(){
6 int choice;
7
8 printf("What flavor ice cream do you want?\n");
9 printf("Enter 1 for chocolate\n");
10 printf("Enter 2 for vanilla\n");
11 printf("Enter 3 for strawberry\n");
12 printf("Enter 4 for Yam\n");
13 printf("Enter your choice: \n");
14 scanf("%d", &choice);
15
16 switch (choice) {
17 case 1:
61
BASIC PROGRAMMING C
ii. Based on the flowchart rewrite Program 7.5 using selection control
structure with if..else..if.
[Berdasarkan carta alir yang dilukis, tulis semula Program 7.5 dengan
menggunakan struktur kawalan pilihan if..else..if.]
iii. Compare the original Program 7.5 and the program from answer ii.
Which selection control structure is easy to read?
[Bandingkan Program 7.5 asal dan aturcara dari jawapan ii. Struktur
kawalan pilihan yang manakah lebih mudah untuk dibaca?]
62
LAB 7: SELECTION OR DECISION
EXERCISE 5:
[LATIHAN 5]
START
Read aLetter
false
if aLetter is Display “NOT
‘a’to ‘z’ or ‘A’ A LETTER”
to ‘Z’
true
true
if aLetter ‘a’ Display
or ‘A’ “Vowel A”
false
true Display
if aLetter ‘e’
or ‘E’ “Vowel E”
false
false
true
if aLetter ‘o’ Display
or ‘O’ “Vowel O”
false
true
if aLetter ‘u’ Display
or ‘U’ “Vowel U”
false
Display
“consonant”
END
Figure 7.1
63
BASIC PROGRAMMING C
EXERCISE 6:
[LATIHAN 6]
64
LAB 7: SELECTION OR DECISION
EXERCISE 7:
[LATIHAN 7]
User Code:
1. Household
2. Office
3. Factory
4. Program End
Choice:_
65
BASIC PROGRAMMING C
START
Enter user
code
true
2B
Enter
consumption
totalUnit
true false
code = 1 ?
true
totalUnit
<= 500 ? false
2A
66
LAB 7: SELECTION OR DECISION
1A 1B
true false
code = 2 ?
true false
totalUnit
<= 1000 ?
true
END
67
LAB 8: LOOP STATEMENTS
ASSUMPTIONS
68
LAB 8:LOOP STATEMENTS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
1 //Program 8.1
2 #include <stdio.h>
3 #include <conio.h>
4 int main()
5 {
6 double price1, price2, price3, price4, price5,
price6, price7, totalPrice=0;
7 printf("Program To Calculate The Average and Total
Price Of The 7 Items \n\n ");
8 printf("Enter price of item: ");
9 scanf("%lf", &price1);
10 totalPrice += price1;
11 printf("Enter price of item: ");
12 scanf("%lf", &price2);
13 totalPrice += price2;
14 printf("Enter price of item: ");
15 scanf("%lf", &price3);
16 totalPrice += price3;
17 printf("Enter price of item: ");
18 scanf("%lf", &price4);
19 totalPrice += price4;
20 printf("Enter price of item: ");
21 scanf("%lf", &price5);
22 totalPrice += price5;
23 printf("Enter price of item: ");
24 scanf("%lf", &price6);
25 totalPrice += price6;
26 printf("Enter price of item: ");
27 scanf("%lf", &price7);
28 totalPrice += price7;
29
30 printf("\n\nThe Average Price Of The Items Is %f",
31 totalPrice/7);
32 printf("\nThe Total Price Of The Items Is %f",
33 totalPrice);
34 printf("\n\nEnd Of Program");
35 getch();
36 return 0;
37 }
38
69
BASIC PROGRAMMING C
ii. Why do you need 7 variables to hold the prices of the items?
[Mengapa 7 pembolehubah diperlukan untuk menyimpan harga
barangan?]
iv. Identify the set of statements that are repeated many times in the
program.
[Kenalpasti set pernyataan yang diulang beberapa kali dalam aturcara
ini.]
EXERCISE 2:
[LATIHAN 2]
1 //Program 8.2
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 double price, totalPrice=0;
int Item;
8 printf("Program To Calculate The Average and Total
9 Price Of The 7 Items \n\n ");
10 for (Item=0; Item<7; Item++)
11 {
12 printf("Enter price of item: ");
13 scanf("%lf", &price);
14 totalPrice += price;
15 }
70
LAB 8:LOOP STATEMENTS
21 return 0;
}
2. Study Program 8.2 carefully, then compile and execute it.
[Kaji Program 8.2 dengan teliti, kemudian kompil dan laksana aturcara
tersebut.]
i. What does the program do? In what way is this program different from
Program 8.1.
[Apakah yang dilakukan oleh aturcara tersebut? Apakah perbezaan
antara Program 8.1. dan Program 8.2.]
ii. Identify the body of the loop, and state how many times it is repeated.
[Kenalpasti badan gelung, dan nyatakan berapa kalikah ia diulang.]
iii. Why do we now need only one variable to hold the prices of the item.
[Mengapa kali ini kita hanya perlu satu pembolehubah untuk
menyimpan harga barangan.]
3. Modify the program such that it will calculate and print the average and the
total prices of 20 items.
[Ubahsuai Program 8.2 supaya ia mengira dan mencetak purata dan jumlah
harga untuk 20 barangan.]
71
BASIC PROGRAMMING C
EXERCISE 3:
[LATIHAN 3]
1 //Program 8.3
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 double price, totalPrice=0;
int Item, itemCnt;
8 printf("Program To Calculate The Average and
9 Total Price Of Items \n\n ");
10 printf("Enter the number of item : ");
11 scanf("%d", &itemCnt);
12
13 for (Item=0; Item<itemCnt; Item++)
14 {
15 printf("Enter price of item: ");
16 scanf("%lf", &price);
totalPrice += price;
17 }
i. What does the program do? In what way is this program different from
Program 8.2
[Apakah yang dilakukan oleh aturcara tersebut? Apakah perbezaan
antara Program 8.2. dan Program 8.3]
iv. Program 8.3 contains 1 logic error that makes the program unreliable.
Identify and fix the error.
72
LAB 8:LOOP STATEMENTS
EXERCISE 4:
[LATIHAN 4]
1 //Program 8.4
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 double price, totalPrice=0;
8 int itemCnt=0;
// read price of 1 item before entering loop
9 printf("Enter price of item: ");
10 scanf("%lf", &price);
11
12 while (price>0)
13 {
14 totalPrice += price;
15 itemCnt++;
16 printf("Enter price of item: ");
17 scanf("%lf", &price);
18 }
19
20 printf("\n\nThe Average Price Of The Items Is %f",
totalPrice/itemCnt);
21 printf("\nThe Total Price Of The Items
Is %f", totalPrice);
22 printf("\n\nEnd Of Program");
23 getch();
24 return 0;
}
ii. Does the user know how to tell the program that he has no more item
to be read? Modify the program to make it more user-friendly.
73
BASIC PROGRAMMING C
iii. Why do we need to read the price of 1 item (line 11) before the while
loop?
[Mengapa kita perlu membaca harga satu barangan (baris 11)
sebelum gelung while?]
EXERCISE 5:
[LATIHAN 5]
1 //Program 8.5
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 double price, totalPrice=0, averagePrice;
8 int proceed=1,itemCnt=0;
printf("Program To Calculate The Average and Total
9 Price Of Items \n\n");
10
11 while (proceed==1)
12 {
13 printf("Enter price of item: ");
14 scanf("%lf", &price);
15 totalPrice += price;
16 itemCnt++;
printf("Anymore item? Enter 1 for yes OR 0
17 for no: ");
18 scanf("%d", &proceed);
19 }
20
printf("\n\nYou have %d Items ", itemCnt);
21 printf("\n\nThe Average Price Of The Items Is %f",
totalPrice/itemCnt);
22 printf("\nThe Total Price Of The Items Is %f",
23 totalPrice);
24 printf("\n\nEnd Of Program");
25 getch();
return 0;
}
74
LAB 8:LOOP STATEMENTS
ii. What is the purpose of variable proceed in this program, and why it
is initialized to 1?
[Apakah peranan pembolehubah proceed dalam aturcara ini, dan
mengapakah ia diberi nilai awal 1?]
EXERCISE 6:
[LATIHAN 6]
1 //Program 8.6
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 double price, totalPrice=0, averagePrice;
8 int N,itemCnt=0;
printf("Program To Calculate The Average and
9 Total Price Of N Items \n\n");
10 printf("How many items do you have?");
11 scanf("%d", &N);
12
13 do
14 {
15 printf("Enter price of item: ");
16 scanf("%lf", &price);
17 totalPrice += price;
18 itemCnt++;
19 }while (itemCnt<N);
75
BASIC PROGRAMMING C
20
i. What type of loop is used in Program 8.6, and how does it different
from Program 8.5?
[Apakah jenis gelung yang diguna dalam Program 8.6? Bagaimana
ia berbeza dengan Program 8.5?]
iii. Why do you need variable itemCnt in this program, and why it is
initialized to 0?
[Mengapa pembolehubah itemCnt diperlukan dalam aturcara ini,
dan mengapa ia perlu diberi nilai awal 0?]
iv. Replace while (itemCnt<N) with the following, and state it’s
effect to the program.
[Tukar pernyataan while (itemCnt<N) kepada pernyataan
berikut, dan nyatakan kesannya ke atas aturcara.]
a. while (--N)
b. while (N--N)
76
LAB 8:LOOP STATEMENTS
EXERCISE 7:
[LATIHAN 7]
1 //Program 8.7
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 int mark;
8 do
9 {
10 printf("\nEnter marks for test 1:");
11 scanf("%d", &mark);
12 } while (mark<0 || mark>100);
13 printf("\nYour mark for test 1 is %d", mark);
14 printf("\n\nEnd Of Program");
15 getch();
16 return 0;
ii. We need ONE value for mark in this program. Why do we need the
DO-WHILE loop?
[Kita memerlukan SATU nilai untuk mark dalam aturcara ini.
Mengapa kita perlu gelung DO-WHILE?]
3. Modify Program 8.7 such that the data validation is implemented using a DO-
WHILE loop,
[Ubahsuai Program 8.7 supaya pengesahan data dilakukan menggunakan
gelung DO-WHILE.]
77
BASIC PROGRAMMING C
EXERCISE 8:
[LATIHAN 8]
1 //Program 8.8
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 int choice=0;
8 printf("\nWELCOME TO CYBER BREAKFAST\n");
9 printf("\n1: Nasi Lemak with Kopi O ");
10 printf("\n2: Roti Canai with Teh Tarik ");
11 printf("\n3: Scramble Egg with Iced Milo ");
12 printf("\n4: Mixed Cereals with Strawberry
13 Shake ");
14 printf("\n5: No thank you, I'm overweight..!
15 \n\n");
16
17 while (choice<1 || choice>5)
18 {
19 printf("Enter your choice: ");
20 scanf("%d", &choice);
21 }
22
23 switch (choice )
24 {
25 case 1: printf("\nThat will be RM 6:50 ");
26 break;
27 case 2: printf("\nThat will be RM 4:50 ");
28 break;
29 case 3: printf("\nThat will be RM 5:00 ");
30 break;
31 case 4: printf("\nThat will be RM 8:50 ");
32 break;
default: printf("\nYou look just great..! ");
33 }
34 printf("\nPlease take a seat and make yourself
35 comfortable. ");
36 printf("\n\nEnd Of Program");
getch();
return 0;
}
78
LAB 8:LOOP STATEMENTS
iv. Experiment with entering (invalid) value for choice. How does this
effect the execution of the program?
[Uji dengan memberikan nilai tidak sah untuk choice. Apakah
kesannya terhadap perlaksanaan aturcara?]
3. Modify Program 8.8 such that the data validation is implemented using a do-
while loop.
[Ubahsuai Program 8.7 supaya pengesahan data dilakukan menggunakan
gelung do-while.]
EXERCISE 9:
[LATIHAN 9]
EXERCISE 10:
[LATIHAN 10]
Analyze the given problems, design their solutions using pseudocode or flowchart
and/or structure charts; and implement them using a C program.
[Analisa masaalah yang diberi. Buat rekabentuk penyelesaian menggunakan kod sudo
atau carta alir dan/atau carta struktur. ]
1. The cost of renting a car is RM100 for the first day, RM 70 per day for the
next 3 days and RM 50 per day thereafter. If the input is the number of days
the car was rented, compute the cost of renting the car. Allow the user to
repeat the calculations as many times as needed and enter a zero to stop.
[ Bayaran sewa kereta untuk hari pertama ialah RM100, RM70 sehari untuk 3
hari berikutnya, dan RM50 untuk setiap hari yang seterusnya. Aturcara
hendaklah membaca jumlah hari kereta telah disewa, dan kira berapakah
jumlah sewa yang perlu dibayar. Aturcara hendaklah membenarkan
pengguna untuk mengulangi proses tersebut sebanyak yang ia kehendaki.
Pengguna hendaklah memasukkan nilai 0 untuk memberhentikan
pengulangan. ]
79
BASIC PROGRAMMING C
80
LAB 8:LOOP STATEMENTS
Start
Set totalProfit to 0
Read noOfItem
YES
noOfItem = 0?
NO
Read itemId,
sellPrice,
costPrice, units
profit =
(sellPrice*Units ) –
(costPrice*Units)
Add profit to
totalProfit
Print itemId,
profit
Subtract 1 from
noOfItem
Print
totalProfit
End
Figure 8.1
81
LAB 9: NESTED LOOPS
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
1 // Program 9.1
2 #include <stdio.h>
3 #include <conio.h>
4 int main()
5 {
6 printf ("\n\t Multiplication Tables");
7 printf
8 ("\n___________________________________\n\n");
9 // print multiplication table for 1
10 for (int j=1; j<=10; j++)
11 {
12 printf ("%4d", j*1);
13 }
14 printf ("\n");
15
16 // print multiplication table for 2
17 for (int j=1; j<=10; j++)
18 {
82
LAB 9: NESTED LOOPS
i. Identify the first loop in Program 9.1, and explain what does it do.
[Kenalpasti gelung pertama dalam Program 9.1, dan terangkan
apakah yang dilakukan oleh gelung tersebut.]
ii. Identify the second loop in Program 9.1, and explain what does it do.
[Kenalpasti gelung kedua dalam Program 9.1, dan terangkan apakah
yang dilakukan oleh gelung tersebut.]
iv. What are the similarities and differences between both loops?
[Apakah persamaan dan perbezaan antara kedua-dua gelung
tersebut?]
3. Modify the program such that it will produce the following output using
individual loops (3 loops):
[Ubahsuai Program 9.1 supaya ia mengeluarkan output berikut menggunakan
gelung berasingan (3 gelung):]
i. 4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
ii. Is this a good way of writing the program? Give your comments.
[Adakah ini cara yang baik untuk menulis aturcara tersebut? Beri
komen anda.]
83
BASIC PROGRAMMING C
EXERCISE 2:
[LATIHAN 2]
1 //Program 9.2
2 #include <stdio.h>
3 #include <conio.h>
4 int main()
5 {
6 printf ("\n\t Multiplication Tables");
7 printf
8 ("\n___________________________________\n\n");
9 // print multiplication table for 1 to 2
10 for (int n=1; n<=2; n++)
11 {
12 for (int j=1; j<=10; j++)
13 {
14 printf ("%4d", j*1);
15 }
16 printf ("\n");
17 }
18
19 printf ("\nEnd of Program");
20 getch();
21 return 0;
22 }
2. Study Program 9.2 carefully, then type, compile and execute it.
[Kaji Program 9.2 dengan teliti, kemudian taip, kompil dan laksana aturcara
tersebut.]
ii. Program 9.2 is supposed to produce the same output as Program 9.1,
but the output is different. Identify the problem and fix it.
[Program 9.2 sepatutnya mengeluarkan output sama seperti Program
9.1, tetapi output adalah berbeza. Kenalpasti punca perbezaan
tersebut dan betulkan.]
iii. Identify the outer loop. How many times will the body of the outer
loop execute? What does each outer loop represent? Which exact code
determine the number of times the outer loop will execute?
[Kenalpasti gelung sebelah luar. Berapa kalikah badan gelung luar
dilaksanakan? Apakah yang diwakili oleh gelung ini? Kod manakah
yang menentukan berapa kali gelung ini akan dilaksana?]
iv. Identify the inner loop. How many times will the body of the inner
loop execute? What does each inner loop represent? Which exact code
determines the number of times the inner loop will execute?
84
LAB 9: NESTED LOOPS
EXERCISE 3:
[LATIHAN 3]
1. Study Program 9.3 carefully, then type, compile and execute it.
[Kaji Program 9.3 dengan teliti, kemudian taip, kompil dan laksana aturcara
tersebut.]
1 // Program 9.3
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 int j;
8 printf ("\n\t Multiplication Tables");
9 printf("\n __________________________________\n\n");
10 // print multiplication table for 1 to 10
11 for (int n=1; n<=10; n++)
12 {
13 j=1;
14 while (j<=10)
15 {
16 printf ("%4d", j*n);
17 j++;
18 }
19 printf ("\n");
20 }
21
22 printf ("\n\t End of Program");
23 getch();
24 return 0;
25 }
i. Look at variable j at line 13. What role does variable j play in the
for loop, and why is it set to 1?
[Lihat pembolehubah j pada baris 13. Apakah peranan
pembolehubah j dalam gelung for, dan mengapa ia diberi nilai 1?]
ii. Look at variable j at line 17. What role does variable j play in the
while loop, and why is it incremented with 1?
[Lihat pembolehubah j pada baris 17. Apakah peranan pembolehubah
j dalam gelung while, dan mengapa ia ditambah dengan nilai 1?]
85
BASIC PROGRAMMING C
i. Use a for loop for the outer loop; and a do-while loop for the
inner loop.
[Guna gelung for untuk gelung luar; dan gelung do-while untuk
gelung dalam.]
ii. Use a while loop for the outer loop; and a for loop for the
inner loop.
[Guna gelung while untuk gelung luar; dan gelung for untuk gelung
dalam.]
EXERCISE 4:
[LATIHAN 4]
Analyze the given problems, design their solutions using pseudocode or flowchart
and/or structure charts; and implement them using a C program.
[Analisa masalah yang diberi. Buat rekabentuk penyelesaian menggunakan kod sudo
atau carta alir dan/atau carta struktur, dan bangunkan menggunakan program C.]
2. Write a program that will print neatly the calendar for a year using loops. The
required year will be given by the user with values in the range 2000 through
2020, and the program must validate this value. Watch out for leap year. You
can use the following format for printing the calendar:
[Tulis satu aturcara untuk mencetak dengan kemas kalendar tahunan
menggunakan gelung. Tahun kalendar akan diberi oleh pengguna dengan
86
LAB 9: NESTED LOOPS
nilai antara 2000 hingga 2020. Pastikan aturcara anda mengesahkan nilai
adalah dalam julat yang betul. Lihat juga sama ada tahun yang diberi oleh
pengguna adalah tahun lompat. Anda boleh gunakan format berikut untuk
mencetak kalendar tersebut.]
YEAR 2007
January
M T W T F S S
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 27
29 30
Use the following algorithm to assign day of the week for the given date,
assumed valid and in the Gregorian calendar. The algorithm assigned value is:
1 for Monday, 2 for Tuesday, ..., 7 for Sunday.
[Guna algoritma berikut untuk mengumpuk satu hari dalam satu minggu jika
diberikan tarikh yang sah dan dalam kalender Gregorian. Nilai yang diumpuk
ialah: 1 untuk Isnin, 2 untuk Selasa, ….., 7 untuk Ahad.]
Algorithm 9.1 :
1. Start
2. If (month < 3)
Start_If
month=month+12
decrement year
End_If
3. result= day + (13 * month - 27)/5 + year + year /4 -
year /100 + year /400
4. result =result+6
5. dayofWeek= (result % 7)+1
6. End
87
LAB 10: PREDEFINED FUNCTIONS
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
(x ) 2
1
i.
ii. cos( x )
iii. sin ( x )
iv. ( x )7
v.
(x + x7
3
)
x
vi. | a−b|
88
LAB 10: PREDEFINED FUNCTIONS
EXERCISE 2:
[LATIHAN 2]
1 double x = 781.2856789;
2 printf ("%.5lf\n", x);
3 x =(floor(x * 100 + 0.5)/100);
4 printf ("%.5lf\n", x);
5 x = (int(x * 100 + 0.5)/100);
6 printf ("%.5lf\n", x);
2. Complete Program 10.1 below. Trace the output of each math functions and
brief what it does.
[Lengkapkap Program 10.1 di bawah. Tentukan output dan huraikan peranan
bagi setiap fungsi math yang digunakan.]
1 //Program 10.1
2 #include <stdio.h>
3 #include <conio.h>
4 // 1. Write down an appropriate directive here
5
6 int main()
7 {
8 int a = sqrt(9);
9 printf("\n 1. sqrt(9) is %d ", a);
10
11 int i = pow(5,3);
12 printf("\n 2. pow(5,3) is %d ", i);
13
14 int j = ceil(2.5);
15 printf("\n 3. ceil(2.5) is %d ", j);
16
17 int k = floor(2.5);
18 printf("\n 4. floor(2.5) is %d ", k);
19
20 int x = ceil(2.1);
21 printf("\n 5. ceil(2.1) is %d ", x);
22
23 int y = floor(2.1);
24 printf("\n 6. floor(2.1) is %d ", y);
25 getch();
26 return 0;
27 }
89
BASIC PROGRAMMING C
EXERCISE 3:
[LATIHAN 3]
1. Program 10.2 uses several predefined functions from stdlib library. Determine
what the program tries to show.
[Program 10.2 menggunakan beberapa fungsi yang terdapat di dalam pustaka
stdlib. Tentukan paparan Program 10.2 tersebut.]
1 //Program 10.2
2 #include <stdio.h>
3 #include <conio.h>
4 #include <stdlib.h>
5
6 int main()
7 {
8 int a,b,c,d;
9 printf ("Enter the starting number\n");
10 scanf ("%d", &a);
11 srand(a);
12 b=rand()%RAND_MAX;
13 c=rand()%200;
14 d=rand()%10+200;
15 printf ("The number between 0 and %d is : %d\n",
RAND_MAX, b);
16 printf ("The number between 0 and 199
is : %d\n", c);
17 printf ("The number between 200 and 210
is : %d\n", d);
18 getch();
19 return 0;
20 }
EXERCISE 4:
[LATIHAN 4]
1. Write a program that find the round value of the following number:
[Tulis aturcara bagi mendapatkan nilai bulat seperti nombor berikut:]
90
LAB 11: USER-DEFINED FUNCTION
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
1 //Program 11.1
2 #include <stdio.h>
3 #include <conio.h>
4
5 void func1(); void func2();
6
7 int main(){
8 int input;
9
10 printf ("Enter a number >");
11 scanf ("%d", &input);
91
BASIC PROGRAMMING C
12
13 if (input < 10) {
14 printf("Faculty of Computer Science & Info.
Systems\n");
15 printf(" Universiti Teknologi Malaysia\n");
16 } else {
17 printf(" Universiti Teknologi Malaysia\n");
18 printf("Faculty of Computer Science & Info.
Systems\n");
19 }
20 getch(); return 0;
21 }
ii. Change the code so that it follows the design of the structured chart as
in Figure 11.1.
[Tukarkan aturcara tersebut supaya ia mematuhi reka bentuk carta
berstruktur seperti Rajah 11.1]
2. Refer to problem in Lab 8, Exercise 8. The program must use 4 functions: the
greeting, input, calculation, and output.
[Rujuk kepada masalah pada Lab 8 Latihan 8. Aturcara hendaklah
menggunakan 4 fungsi: pamer selamat datang, baca input dari pengguna,
pengiraan jumlah liter, dan output.]
EXERCISE 2:
[LATIHAN 2]
1. Given Program 11.2 which consists of a void function. Compile and identify
the output of the program. State the name of function call, function header and
function declaration in the program.
[Diberi Program 11.2 yang mengandungi fungsi tanpa parameter. Kompil dan
kenal pasti output bagi aturcara tersebut. Nyatakan nama fungsi, kepala
fungsi dan pengisytiharan fungsi bagi aturcara tersebut.]
92
LAB 11: USER-DEFINED FUNCTION
2. Given Program 11.3 which consists of a function that is passing data by value.
Compile and identify the output of the program. State the name of function
call, function header and function declaration in the program.
[Diberi Program 11.3 yang menghantar data secara nilai. Kompil dan kenal
pasti output bagi aturcara tersebut. Nyatakan nama fungsi, kepala fungsi dan
pengisytiharan fungsi bagi aturcara tersebut.]
1 //Program 11.3
2 #include <stdio.h>
3 #include <conio.h>
4
5 int subtraction (int, int);
6
7 int main ()
8 {
9 int x=5, y=3, z;
10 z = subtraction (7,2);
11 printf ("The first result is %d\n", z);
12 printf ("The second result is %d\n",
13 subtraction(7,2));
14 printf ("The third result is %d\n",
15 subtraction(x,y));
16 z= 4 + subtraction (x,y);
17 printf ("The fourth result is %d\n", z);
18 getch();return 0;
19 }
20
21 int subtraction (int a, int b)
22 {
23 int r;
24 r=a-b;
25 return (r);
26 }
93
BASIC PROGRAMMING C
1 //Program 11.4
2 #include <stdio.h>
3 #include <conio.h>
4
5 void duplicate (int &a, int &b, int &c)
6 {
7 a*=2;
8 b*=2;
9 c*=2;
10 }
11
12 int main ()
13 {
14 int x=1, y=3, z=7;
15 duplicate (x, y, z);
16 printf ("x=%d, y=%d, z=%d", x, y, z);
17 getch();return 0;
18 }
4. Given Program 11.5 which consists of a function that is returning more than
one value. Compile and identify the output of the program. State the name of
function call, function header and function declaration in the program.
[Diberi Program 11.5 yang mengembalikan lebih dari satu nilai. Kompil dan
kenal pasti output bagi aturcara tersebut. Nyatakan nama fungsi, kepala
fungsi dan pengisytiharan fungsi bagi aturcara tersebut.]
1 //Program 11.5
2 #include <stdio.h>
3 #include <conio.h>
4
5 void prevnext (int x, int *prev, int *next);
6
7 int main ()
8 {
9 int x=100, y, z;
10 prevnext (x, &y, &z);
11 printf ("Previous=%d, Next=%d", y, z);
12 getch();return 0;
13 }
14 void prevnext (int x, int *prev, int *next)
15 {
16 *prev = x-1;
17 *next = x+1;
18 }
94
LAB 11: USER-DEFINED FUNCTION
5. Given Program 11.6 which consist of fixed value in a function. Compile and
identify the output of the program. State the name of function call, function
header and function declaration in the program.
[Diberi Program 11.6 yang mempunyai nilai tetap dalam fungsi. Kompil dan
kenal pasti output bagi aturcara tersebut. Nyatakan nama fungsi, kepala
fungsi dan pengisytiharan fungsi bagi aturcara tersebut.]
1 //Program 11.6
2 #include <stdio.h>
3 #include <conio.h>
4
5 int divide (int a, int b=2);
6
7 int main ()
8 {
9 printf ("20/default-value is: %d", divide (12));
10 printf ("\n");
11 printf ("20/4 is: %d", divide (20,4));
12 getch();return 0;
13 }
14
15 int divide (int a, int b)
16 {
17 int r;
18 r=a/b;
19 return (r);
20 }
6. Given Program 11.7 which consists of inline function. Compile and identify
the output of the program. State the name of function call, function header and
function declaration in the program.
[Diberi Program 11.7 yang terdiri daripada fungsi dalam baris. Kompil dan
kenal pasti output bagi aturcara tersebut. Nyatakan nama fungsi, kepala
fungsi dan pengisytiharan fungsi bagi aturcara tersebut.]
1 //Program 11.7
2 inline float cube (const float a) {return a*a*a;}
3
4 int main ( ){
5 float side;
6 printf (“Enter the side length of your cube: “);
7
8 scanf (“%fl”, &side);
9 printf (“Volume of cube with side %fl is %fl\n“,
10 side, cube(side));
11 return 0;
12 }
95
BASIC PROGRAMMING C
EXERCISE 3:
[LATIHAN 3]
1 //Program 11.9
2 #include <stdio.h>
3 #include <conio.h>
4
5 void a(void);
6 void b(void);
7
8 int x = 1;
9 int linenum = 0;
10
11 int main( ){
12 int x = 5;
13
14 linenum++;
15 printf ("%dx = %d\n", linenum, x);
16 {
17 int x = 7;
18
19 linenum++;
20 printf ("%dx = %d\n", linenum, x);
21 }
22 linenum++;
23 printf ("%dx = %d\n", linenum, x);
24
25 a(); b();
26
27 linenum++;
28 printf ("%dx = %d\n", linenum, x);
29 getch(); return 0;
30 }
31
32 void a(void){
33 int x = 25;
34
35 linenum++;
36 printf ("%dx = %d\n", linenum, x);
37 }
38
39 void b(void){
40 linenum++;
41 printf ("%dx = %d\n", linenum, x);
42 }
96
LAB 11: USER-DEFINED FUNCTION
ii. Identify which variable x that is being printed for each line of the
output.
[Kenalpasti pembolehubah x manakah yang dicetak untuk setiap baris
output.]
1 //Program 11.10
2 #include <stdio.h>
3 #include <conio.h>
4
5 void shownum(); // Function prototype
6
7 int main()
8 {
9 for (int count = 0; count < 5; count++)
10 shownum();
11 getch(); return 0;
12 }
13
14 void shownum()
15 {
16 static int num=5;
17 int num2=10;
18
19 printf ("num is %d\n", num);
20 printf ("num2 is %d\n", num2);
21 num++; num2++;
22 }
ii. What are the difference between static variable and local variable?
[Apakah perbezaan antara skop pembolehubah statik dan
pembolehubah setempat?]
iii. What are the differences between static variable and global variable?
[Apakah perbezaan antara skop pembolehubah statik dan
pembolehubah global?]
97
BASIC PROGRAMMING C
EXERCISE 4:
[LATIHAN 4]
1. Given Program 11.11 that reads three integer numbers and find the maximum
number among the three. Complete the program by writing a function named
maximum, that finds the largest of the three numbers.
[Diberikan Program 11.11 yang membaca tiga nombor integer dan mencari
nombor maksimum daripada ketiga-tiga nombor tersebut. Lengkapkan
aturcara tersebut dengan menulis fungsi untuk mencari nombor terbesar di
antara ketiga-tiga nombor.]
1 //Program 11.11
2 #include <stdioh>
3 #include <conio.h>
4
5 int maximum(int,int,int);
6
7 int main()
8 {
9 int a, b, c ;
10
11 printf ("Enter Three Integers: ");
12 scanf ("%d %d %d", &a, &b, &c);
13 printf ("Maximum is: %d\n", maximum(a,b,c));
14
15 getch(); return 0;
16 }
2. Given Program 11.12 that reads an integer number and determines whether the
number is even or odd. Complete the program by writing a function named
is_even, that prints "yes" if the number is even, or prints "no", otherwise.
[Diberikan Program 11.12 yang membaca satu nombor integer dan
menentukan sama ada nombor itu adalah genap atau ganjil. Lengkapkan
aturcara tersebut dengan menulis fungsi bernama is_even, yang mencetak
"yes" sekiranya nombor adalah genap atau mencetak "no" jika sebaliknya.]
1 //Program 11.12
2 #include <stdio.h>
3 #include <conio.h>
4
5 void is_even(int a); // Function Prototype
6
7 int main(void)
8 {
9 int a;
10 printf ("Enter an integer:\n");
11 scanf ("%d", &a);
12 printf ("Is %d even?", a);
13 is_even(a);
14 printf ("\n");
15 getch();
16 return 0;
17 }
98
LAB 11: USER-DEFINED FUNCTION
3. Given Program 11.13 that reads the distance in miles and hours, calculates and
prints miles per hour. Complete the program by writing the function prototype
named GetData (at line 5), writing the code that invoke the function
GetData (at line 13), and writing the body of the function GetData that
reads miles and hours (at line 23).
[Diberikan Program 11.13 yang membaca jarak dalam unit batu serta jam,
mengira dan mencetak batu sejam. Lengkapkan aturcara tersebut dengan
menulis prototaip fungsi bernama GetData (pada baris 5), menulis kod yang
memanggil fungsi GetData (pada baris 13), dan menulis badan fungsi
GetData yang membaca batu dan jam (pada baris 23).]
1 //Program 11.13
2 #include <stdio.h>
3 #include <conio.h>
4
5 /* Write the function(s) prototype for GetData */
6
7 int main ()
8 {
9 float miles;
10 float hours;
11 float milesPerHour;
12
13 /* Write the code(s) to invoke function GetData */
14
15 milesPerHour = miles / hours;
16 printf (“%10f %10f %10f\n”, miles, hours,
17 milesPerHour);
18
19 getch();
20 return 0;
21 }
22
23 /* Write the body of the function(s) GetData that
24 read miles and hours */
99
BASIC PROGRAMMING C
4. Given Program 11.14 that has a function named average, which finds the
average of given numbers. Complete the program by writing the function
prototype named average (at line 5 and 6) that sends 3 parameters, writing
the code that invoke the function average (at line 15 and 16), and writing the
body of the overloaded function average that finds the average of three
numbers (at line 22).
[Diberikan Program 11.14 yang mempunyai fungsi sarat bernama average,
yang mendapatkan purata bagi nombor yang diberi. Lengkapkan aturcara
tersebut dengan menulis prototaip fungsi bernama average (pada baris 5
dan 6), menulis kod yang memanggil fungsi average (pada baris 15 dan 16)
dengan menghantar 3 parameter, dan menulis badan fungsi sarat average
yang mendapatkan purata bagi tiga nombor (pada baris 22).]
1 //Program 11.14
2 #include<stdio.h>
3 #include<conio.h>
4
5 /* Write the function prototype for the function
6 average that sends 3 parameters */
7
8 int main()
9 {
10 int number_A = 5, number_B = 3, number_C = 10;
11
12 printf ("The integer average of %d and %d and %d
13 is\n", number_A, number_B, number_C);
14
15 /* Write the code that invoke the function average
16 with 3 parameters */
17
18 getch();
19 return 0;
20 }
21
22 // write the body of the function average
100
LAB 11: USER-DEFINED FUNCTION
EXERCISE 5:
[LATIHAN 5]
i. int getCoin()
To read the value of a coin input from the user.
[Untuk membaca satu nilai duit siling yang diinput oleh pengguna.]
101
BASIC PROGRAMMING C
Figure 11.2
EXERCISE 6:
[LATIHAN 6]
1. Write a program that reads a student’s name together with his or her
assessment marks. The program should then compute the total mark for each
student and assign the appropriate grade. In order to compute the total mark,
the distribution of marks is tabulated in Table 11.1, while the grade scale is
tabulated in Table 11.2. Your program must use the following functions:
[Tuliskan satu aturcara yang membaca nama pelajar dan markah-markah
penilaian pelajar tersebut. Aturcara ini perlu mengira jumlah markah bagi
setiap pelajar dan memberi gred yang bersesuaian kepadanya. Untuk mengira
jumlah markah Jadual 11.1 menunjukkan pembahagian markah, manakala
skala gred dijadualkan di Jadual 11.2. Aturcara anda perlu menggunakan
fungsi-fungsi berikut.]
102
LAB 11: USER-DEFINED FUNCTION
output bagi jumlah markah yang dihasilkan. Tugas ini perlu dilakukan
dalam fungsi utama.]
iii. Test your program on the following data. Read the data from a text file and
send the output to another text file. Do not use global variables. Use the
appropriate parameters to pass values in and out of functions.
[Uji aturcara anda dengan data berikut. Baca data dari fail teks dan hantar
output ke fail teks yang lain. Jangan menggunakan pembolehubah global. Sila
gunakan parameter yang bersesuaian untuk menghantar nilai ke dalam atau
keluar dari fungsi.]
103
BASIC PROGRAMMING C
Hasyimah 85 90 88 79 90
Rahim 77 80 65 76 60
Syadhila 79 88 68 79 85
Nurfarhana 81 84 84 82 85
Nurliyana 55 68 69 75 80
Ooi 88 82 88 81 86
Ping 60 85 45 39 45
Quah 85 67 50 75 67
Sham 80 84 89 93 95
Sien 32 45 86 78 65
Selan 40 57 60 57 67
Susan 89 79 88 81 80
Tan 46 58 69 79 82
Sample Output:
[Contoh Output:]
Lab Final Total
STUDENT Test 1 Assignments Quiz works Exam Mark Grade
Hasyimah 85 90 88 79 90 87.7 A
Rahim 77 80 65 76 60 71.5 B+
Syadhila 79 88 68 79 85 82.4 A
Nurfarhana 81 84 84 82 85 83.5 A
Nurliyana 55 68 69 75 80 69.8 B
Ooi 88 82 88 81 86 84.9 A
Ping 60 85 45 39 45 59.4 C+
Quah 85 67 50 75 67 69.7 B
Sham 80 84 89 93 95 87.9 A
Sien 32 45 86 78 65 55.8 C+
Selan 40 57 60 57 67 56.9 C+
Susan 89 79 88 81 80 82.4 A
Tan 46 58 69 79 82 66.0 B
104
LAB 12: ONE-DIMENSIONAL ARRAY
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
1 //Program 12.1
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 float score1, score2, score3, score4;
8 printf ("Enter four floats: \n");
9 scanf ("%f", &score1);
10 scanf ("%f", &score2);
11 scanf ("%f", &score3);
12 scanf ("%f", &score4);
13 printf ("The scores in reverse order are: \n");
14 printf ("%f %f %f %f", score4, score3, score2,
15 score1;
105
BASIC PROGRAMMING C
15 getch();
16 return 0;
17 }
1 //Program 12.2
2 #include <stdio.h>
3 #include <conio.h>
4 #define SIZE 4
5
6 int main()
7 {
8 float score[SIZE];
9 int i;
10 printf ("Enter %f floats: ", SIZE);
11 for(i = 0; i <= (SIZE - 1); i = i + 1)
12 scanf ("%f", &score[i]);
13 printf ("The scores in reverse order are: \n");
14 for(i = SIZE - 1; i >= 0; i = i - 1){
15 printf ("%f", score[i]);
16 printf ("\n");}
17 getch();
18 return 0;
19 }
2. Write and run the following Program 12.3, then answer the following
questions.
[Tulis dan laksanakan Program 12.3, kemudian jawab soalan berikutnya.]
1 //Program 12.3
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 char a[11] = "Boring";
8 printf ("Index 0 has %c\n", a[0]);
9 printf ("Index 1 has %c\n", a[1]);
10 printf ("Index 2 has %c\n", a[2]);
11 printf ("Index 3 has %c\n", a[3]);
12 printf ("Index 4 has %c\n", a[4]);
13 printf ("Index 5 has %c\n", a[5]);
14 printf ("Index 6 has %c\n", a[6]);
15 printf ("Index 7 has %c\n", a[7]);
16 printf ("Numerically, the a[6] is %c ",a[6]);
17 getch();
18 return 0;
19 }
106
LAB 12: ONE-DIMENSIONAL ARRAY
ii. How many characters (including the null character at the end of the
array), do this array hold?
[Berapakah bilangan bilangan aksara (termasuk aksara null yang
terdapat di akhir tatasusunan) yang dipegang oleh tatasusunan?]
iii. The number of an index is also called an index. What is the lowest
index?
[Bilangan indeks turut dikenali sebagai indeks. Apakah nilai bagi
indeks yang terendah?]
3. Run the following Program 12.4 with the first printf commented out. Then
answer the following questions.
[Laksanakan Program 12.4 berikut dengan pernyataan pertama printf
dikomenkan. Seterusnya jawab soalan-soalan berikut.]
1 //Program 12.4
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 char a[16] = "Programming C";
8 int i;
9 for(i = 0; i <= 9; i = i + 1)
10 {
11 a[i] = a[9 - i];
12 // printf ("i = %d%s\n", i, a);
13 }
14 printf (“%s”, a);
15 getch();
16 return 0;
17 }
107
BASIC PROGRAMMING C
iv. After removing the comment at line 12, show the output of the
program.
[Selepas menghapuskan symbol komen pada baris 12, tunjukkan
output bagi aturcara.]
4. Run the following Program 12.5 and answer the following questions.
[Laksanakan Program 12.5 berikut dan jawab soalan-soalan berikut.]
1 //Program 12.5
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 int i, x[6], y[6] = {3, 8, 2, 9, 4, 1};
8 for(i = 0; i <= 5; i = i + 1)
9 x[i] = y[i];
10 for(i = 0; i <= 5; i = i + 1)
11 printf (“%d”, x[i]);
12 getch();
13 return 0;
14 }
108
LAB 12: ONE-DIMENSIONAL ARRAY
5. Run Program 12.6 below with the statement at line 9 being replaced by
suggested statement below. Show the output of this program.
[Laksanakan Program 12.6 dengan pernyataan pada baris 9 digantikan
dengan pernyataan-pernyataan yang dicadangkan berikut. Tunjukkan output
bagi aturcara ini.]
1 //Program 12.6
2 #include <stdio.h
3 #include <conio.h>
4
5 int main()
6 {
7 int i, a[] = {40, 20, 70, 10, 80, 30, 90};
8 for(i = 1; i <= 5; i = i + 1)
9 //_____________________________
10 printf ("\n ");
11 getch();
12 return 0;
13 }
EXERCISE 2:
[LATIHAN 2]
int a[7]={8,6,5,3,9,2,7};
sort(a,6);
1 //Program 12.7
2 void swap_values(int &v1, int &v2)
3 {
4 int temp;
5 temp = v1;
6 v1 = v2;
7 v2 = temp;
8 }
9
10 int index_of_smallest(const int a[], int begin_index,
int end_index)
109
BASIC PROGRAMMING C
11 {
12 int min = a[end_index],
13 index_of_min = end_index;
14
15 for (int index=begin_index; index < end_index;
index++)
16 if (a[index] < min )
17 {
18 min = a[index];
19 index_of_min = index;
20 }
21
22 return index_of_min;
23 }
24
25 void sort(int a[], int last_index)
26 {
27 int index_of_next_smallest;
28
29 for (int index=last_index; index>=0; index--)
30 {
31 index_of_next_smallest = index_of_smallest(a, 0,
index);
32 swap_values(a[index], a[index_of_next_smallest]);
33 }
34 }
i. Write the contents of the array a for each loop when the function sort
is being executed. (Write your answers in a table as shown below).
[Tuliskan kandungan tatasusunan a bagi setiap ulangan semasa
fungsi sort dilaksankan. (Tuliskan jawapan anda menggunakan
jadual di bawah).]
110
LAB 12: ONE-DIMENSIONAL ARRAY
ii. Read 10 data then assign the values into array number.
[Membaca 10 data untuk dimasukkan ke dalam tatasusun bagi
number.]
EXERCISE 3:
[LATIHAN 3]
C = 5/9 x (F - 32)
Write a complete C program that reads in a list of data F from a text file, then
calculates the values of C using the formula given. The program should use an
array to store the values of F as example shown in Figure 12.1
[Tuliskan satu aturcara C lengkap yang membaca satu senarai data F
daripada sebuah fail teks, kemudian mengira nilai-nilai C menggunakan
formula yang diberi. Aturcara tersebut perlu menggunakan tatasusunan untuk
menyimpan nilai-nilai F seperti contoh pada Rajah 12.1.]
111
BASIC PROGRAMMING C
13.29
29.76
14.81
23.78
29.37
..
..
..
The program then prints a summary output onto the screen and the detail
output into a text file as shown in Figures 12.2 and 12.3. Grades ‘H’ mean
high temperature; ‘M’ is medium temperature and ‘L’ is low temperature
[Seterusnya, aturcara tadi akan mencetak output rumusan ke skrin dan
output terperinci ke dalam sebuah fail teks seperti yang ditunjukkan
masing-masing pada Rajah 12.2 dan 12.3. Gred ‘H’ mewakili suhu tinggi;
‘M’ pula mewakili suhu sederhana dan ‘L’ mewakili suhu rendah.]
112
LAB 12: ONE-DIMENSIONAL ARRAY
Your program must define several functions at least as listed in the Table 12.1.
You are also required to apply the concept of parameter passing to these
functions.
[Aturcara anda perlu mendefinisikan beberapa fungsi sekurang-kurangnya
seperti yang disenaraikan dalam jadual berikut. Anda juga dikehendaki
melaksanakan konsep penghantaran parameter terhadap fungsi-fungsi
tersebut.]
Table 12.1
Fungsi Keterangan
[Function] [Description]
readFile This function reads in a list of numbers from a text file and
stores them into a one-dimensional array. It receives the
following parameters:
[Fungsi ini digunakan untuk membaca senarai nombor
daripada sebuah fail teks dan menyimpan nombor-nombor
tersebut ke dalam sebuah tatasusunan. Ia perlu menerima
parameter-parameter berikut:]
• The name of the text file to be read from
[Nama bagi fail teks yang hendak dibaca]
113
BASIC PROGRAMMING C
For printing summary output onto the screen, you may define another function
or you may just put the code into the function main.
[Untuk cetakan output rumusan ke skrin, anda juga boleh mendefinisikan
satu fungsi yang lain atau anda boleh menulis kod-kod yang berkenaan terus
ke dalam fungsi main.]
114
LAB 13: TWO-DIMENSIONAL ARRAY
ASSUMPTIONS
LAB EXERCISES
EXERCISE 1:
[LATIHAN 1]
1. Show the output of Program 13.1 and answer the following questions.
[Paparkan output bagi Program 13.1 dan jawab soalan-soalan berikut.]
1 //Program 13.1
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 int i, j;
8 int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
9
10 for(i = 0; i <= 2; i = i + 1)
11 {
12 for(j = 0; j <= 3; j = j + 1)
13 printf ("a[%d][%d] = %d\t", i, j, a[i][j]);
115
BASIC PROGRAMMING C
14 printf ("\n");
15 }
16 getch();
17 return 0;
18 }
ii. When i is 0 and j is 3, the element in which row and which column is
printed?
[Apabila i ialah 0 dan j ialah 3, elemen pada baris dan lajur
manakah yang akan dipaparkan?]
iii. When i is 2 and j is 1, the element in which row and which column is
printed?
[Apabila i ialah 2 dan j ialah 1, elemen pada baris dan lajur
manakah yang akan dipaparkan?]
2. Write and run the following Program 13.2, then try answering questions that
follow.
[Tulis dan laksanakan Program 13.2 serta jawab soalan-soalan berikutnya.]
1 //Program 13.2
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 int i, j;
8 int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
9
10 for(i = 2; i >= 0; i = i - 1)
11 {
12 for(j = 3; j >= 0; j = j - 1)
13 printf ("a[%d][%d] = %d\t", i, j, a[i][j]);
14 printf ("\n");
15 }
16 getch();
17 return 0;
18 }
ii. When i is 2 and j is 2, the element in which row and which column is
printed?
116
LAB 13: TWO-DIMENSIONAL ARRAY
iii. When i is 2 and j is 0, the element in which row and which column is
printed?
[Apabila i ialah 2 dan j ialah 0, elemen pada baris dan lajur
manakah yang akan dipaparkan?]
iv. When i is 1 and j is 3, the element in which row and which column is
printed?
[Apabila i ialah 1 dan j ialah 3, elemen pada baris dan lajur
manakah yang akan dipaparkan?]
1 //Program 13.3
2 int array[3][3], index1, index2;
3 for(index1=0;index1<3;index1++)
4 for(index2=0;index2<3;index2++)
5 array[index1][index2]=index1 + index2;
6 for(index1=0;index1<3;index1++)
7 {
8 for(index2=0;index2<3;index2++)
9 printf (“%d”, array[index1][index2]);
10 printf ("\n");
11 }
117
BASIC PROGRAMMING C
EXERCISE 2:
[LATIHAN 2]
1 //Program 13.4
2 #include <stdio.h>
3 #include <conio.h>
4
5 int main()
6 {
7 int i, j;
8 char a[3][4];
9 for(i = 0; i <= 2; i = i + 1)
10 for(j = 0; j <= 3; j = j + 1)
11 scanf (”%d”, &a[i][j]);
12
13 for(i = 0; i <= 2; i = i + 1)
14 {
15 for(j = 0; j <= 3; j = j + 1)
16 printf ("a[%d][%d] = %d\t", i, j, a[i][j]);
17 printf ("\n"); }
18 getch();
19 return 0;
20 }
21
i. Fill in the box given in Figure 13.1 with all the characters are read
properly into this array.
[Lengkapkan kotak kosong yang terdapat pada Rajah 13.1 dengan
aksara dibaca mengikut aturan yang betul ke dalam tatasusunan.]
Figure 13.1
118