UAS 24-25 FAC1003 Programming II

--- Page 1 ---

UNIVERSITI MALAYA UNIVERSITI MALAYA

PEPERIKSAAN ASASI SAINS FIZIKAL EXAMINATION FOR FOUNDATION IN PHYSICAL SCIENCES

SESI AKADEMIK 2024/2025 : SEMESTER 2 ACADEMIC SESSION 2024/2025 : SEMESTER 2

FAC1003 : Pengaturcaraan II Programming II

Mei/Jun 2025 Masa : 2 jam May/Jun 2025 Time : 2 hours


ARAHAN KEPADA CALON : INSTRUCTIONS TO CANDIDATES :

Kertas soalan ini dibahagikan kepada dua bahagian: Bahagian A dan Bahagian B. Calon dikehendaki menjawab semua soalan.

This question paper is divided into two parts: Part A and Part B. Candidate is required to answer all questions.

(Kertas soalan ini mengandungi 6 soalan dalam 10 halaman yang dicetak) (This question paper consists of 6 questions on 10 printed pages)

--- Page 2 ---

FAC1003

BAHAGIAN A / PART A

  1. (a) Nyatakan sama ada pernyataan berikut adalah BETUL atau SALAH.

(i) Antara contoh-contoh fungsi yang ditakrifkan oleh pengguna dalam C++ adalah sqrt() dan pow().

(ii) Fungsi yang ditakrifkan oleh pengguna dalam C++ mesti ditulis menggunakan sintaks

returnType functionName(parameterList).

(iii) Salah satu kelebihan utama menggunakan fungsi dalam C++ ialah ia membantu mengurangkan pengulangan kod dan menambahbaik kebolehselenggaraan.

(iv) Suatu prototaip fungsi membolehkan penggunaan fungsi tersebut sebelum ditakrifkan dalam program.

(v) Tujuan prototaip fungsi adalah untuk mengelakkan kompilasi ralat apabila sesuatu fungsi digunakan sebelum ditakrifkan.

(vi) Takrifan fungsi merangkumi jenis pulangan, nama, dan parameter tetapi tidak termasuk badan fungsi.

(b) Program dalam Rajah 1 meminta pengguna untuk memasukkan dua nombor titik apungan. Jika nombor pertama lebih besar daripada nombor kedua, maka program akan mendarabkan kedua-dua nombor tersebut. Sebaliknya, program akan membahagikannya. Program tersebut perlu memanggil fungsi jenis call-by-pointer untuk operasi darab, dan fungsi jenis call-by-reference untuk operasi bahagi. Isikan tempat kosong dengan arahan C++ yang betul.

#include <iostream>
using namespace std;

// Function to multiply two numbers using pointers
(i)

// Function to divide two numbers using references
(ii)

int main() {
    float num1, num2, result;

    // Input two floating-point numbers
    cout << "Enter the first number: ";
    cin >> num1;

    cout << "Enter the second number: ";
    cin >> num2;

2/10

--- Page 3 ---

FAC1003

// Check condition and call appropriate function
if (num1 > num2) {
    _______________________________________
                  (iii)

    cout << "The first number is greater than the
    second." << endl;
    cout << "Multiplication result: " << result
    << endl;
} else {
    if (num2 != 0) {
        _______________________________________
                      (iv)

        cout << "The first number is not greater
        than the second." << endl;
        cout << "Division result: " << result <<
        endl;
    } else {
        cout << "Error: Division by zero is not
        allowed." << endl;
    }
}

return 0;
}

Rajah 1 / Figure 1

(a) State whether the statements below are TRUE or FALSE.

(i) Some examples of user-defined functions in C++ are sqrt() and pow().

(ii) A user-defined function in C++ must be written by using the syntax returnType functionName(parameterList).

(iii) One of the main advantages of using functions in C++ is to help in reducing code duplication and improving maintainability.

(iv) A function prototype allows the use of the function before it is defined in the program.

(v) The purpose of a function prototype is to help avoid compilation errors when a function is used before it is defined.

(vi) A function definition includes the return type, name, and parameters but does not include the function body.

(b) The program in Figure 1 asked the user to input two floating numbers. If the first number is greater than the second, then the program will multiply the two numbers. Otherwise, it will divide them. The program calls a call-by-pointer function for multiplying the two numbers and a call-by-reference function for dividing. Fill in the blanks with the correct C++ command.

(10 markah/marks)

Page 3/10

--- Page 4 ---

FAC1003

2. (a) Rajah 2 menunjukkan suatu program C++ yang mengira jumlah harga bagi lima barangan runcit yang disimpan dalam satu tatasusunan. Sepanjang pengiraan, program tersebut perlu memaparkan jumlah terkumpul selepas menambah harga setiap item dan jumlah harga keseluruhan. Program tersebut menggunakan satu fungsi yang menerima tatasusunan sebagai argumen. Isikan tempat kosong dengan arahan C++ yang bersesuaian.

#include <iostream>
#include <iomanip>
using namespace std;

// Function to calculate total price
float ____(i)____(float prices[5]);

int main() {
    float  total,items[5]={5.99,  12.5,  3.45,  7.3,
10.0};
    
    total = ____(ii)____(items);
    cout<<"Total  price=RM"<<fixed<<setprecision(2)<<
total<< endl;
    return 0;
}

float calculateTotal(float prices[5]) {
    float sum = 0.0;
    for (int i = 0; i < 5; ++i) {
        sum += prices[i];
        cout<<"Running  total  =  RM"  <<  fixed  <<
setprecision(2)<< sum << "   prices["<< i<<"]
= "<< ____(iii)____ << endl;
    }
    return ____(iv)____;
}

Rajah 2 / Figure 2

(b) Program C++ dalam Rajah 3 bertujuan untuk mencipta suatu tatasusunan dinamik bersaiz $n$, menyimpan nilai $i * 2$, dan memulangkannya kepada fungsi main() untuk dipaparkan. Namun begitu, kod tersebut mengandungi tiga ralat. Kenal pasti barisnya dan berikan justifikasi.

Page 4/10

--- Page 5 ---

FAC1003

Line 1: #include <iostream>
Line 2: using namespace std;
Line 3:
Line 4://Function to create and return a dynamic array
Line 5: int createDoubleIndexArray(int size) {
Line 6:   int* arr = new int[size];
Line 7:   for (int i = 0; i < size; ++i) {
Line 8:     arr[i] == i * 2;
Line 9:   }
Line 10:   return arr;
Line 11: }
Line 12:
Line 13: int main() {
Line 14:   int n;
Line 15:   cout << "Enter the size of the array: ";
Line 16:   cin >> n;
Line 17:
Line 18:   int* doubleArray;
Line 19:   doubleArray = createDoubleIndexArray[n];
Line 20:   cout << "Values (i * 2):" << endl;
Line 21:   for (int i = 0; i < n; ++i) {
Line 22:   cout<<"Element["<<i<<"]="<<doubleArray[i];
Line 23:   cout<< endl;
Line 24:   }
Line 25:     delete doubleArray;
Line 26:     return 0;
Line 27: }

Rajah 3 / Figure 3

(a) Figure 2 shows a C++ program that calculates the total price of five grocery items stored in an array. During the calculation, the program should display the running total after adding each item's price and the total price. The program uses a function that takes the array as an argument. Fill in the blanks with the suitable C++ commands.

(b) The C++ program in Figure 3 is intended to create a dynamic array of size n, storing the values of i * 2, and return it to the main() function for display. However, the code contains three errors. Identify the lines and justify.

(10 markah/marks)

5/10

--- Page 6 ---

FAC1003

BAHAGIAN B / PART B

  1. Tulis satu program C++ menggunakan tatasusunan dua dimensi yang merangkumi kesemua berikut:

    • isytiharkan satu tatasusunan dua dimensi temp[4][4] yang meminta pengguna untuk memasukkan bacaan suhu dalam Celsius sebanyak empat kali sehari (lajur) selama empat hari (baris) dengan menggunakan gegelung while atau for.

    • tukarkan semua nilai suhu kepada Fahrenheit melalui gegelung do-while, menggunakan formula

      $$F = C * 9/5 + 32$$

      hanya jika nilai Celsius melebihi 30, dan kira jumlah keseluruhan nilai Fahrenheit yang telah ditukar.

    • gunakan gegelung for untuk mengisi satu tatasusunan baru humidity[4][4] dengan nilai bermula daripada 10 dan bertambah sebanyak 10 bagi setiap elemen (contohnya: 10, 20, 30, ...).

    • cipta satu tatasusunan baru weatherData[8][8] yang mengandungi elemen-elemen daripada temp (selepas penukaran) dan humidity (separuh pertama untuk temp dan separuh kedua untuk humidity).

    Write a C++ program using two dimensional arrays comprises of all the following:

    • declare a two dimensional array temp[4][4] for user to input temperature readings in Celcius for four times per day (columns) within four days (rows) using while or for loop.

    • convert all the temperature values to Fahrenheit via a do-while loop by the formula

      $$F = C * 9/5 + 32$$

      only if the Celsius value is greater than 30, and compute the total sum of the converted Fahrenheit values.

    • create a for loop to fill a new array humidity[4][4] with values starting at 10 and increases by 10 for each element (i.e. 10, 20, 30, ...).

    • create a new array weatherData[8][8] that consists of the elements from temp (after conversion) and humidity (first half for temp and second half for humidity).

(15 markah/marks)

6/10

--- Page 7 ---

FAC1003

  1. Seorang pelajar ingin merekod dan menganalisis markah kuiz kursus FAC1003 untuk rakan sekelasnya. Markah-markah tersebut disimpan dalam tatasusunan dua dimensi (2D), di mana setiap baris mewakili seorang pelajar, dan setiap lajur mewakili satu kuiz.

Tulis satu program C++ yang memenuhi kriteria berikut:

  • menggunakan fungsi utama sahaja (main()), tanpa sebarang fungsi tambahan.
  • membenarkan pelajar memasukkan markah bagi tiga orang pelajar dan empat kuiz masing-masing.
  • mengira jumlah dan purata markah bagi setiap pelajar.
  • memaparkan pelajar yang mempunyai purata tertinggi.

Syarat tambahan:

  • gunakan arahan #define untuk menetapkan bilangan pelajar dan bilangan kuiz.
  • gunakan penuding untuk mengakses setiap elemen dalam tatasusunan dan pembolehubah yang berkaitan.
  • program mesti melibatkan penggunaan gelung serta operasi aritmetik asas seperti tambah dan bahagi.

A student wants to record and analyse the quiz scores for the FAC1003 course for their classmates. The scores are stored in a two-dimensional (2D) array, where each row represents a student, and each column represents a quiz.

Write a C++ program that fulfills the following criteria:

  • Use only the main() function, without creating additional functions.
  • Allow the student to enter scores for three students and four quizzes each.
  • Calculate the total and average score for each student.
  • Display the student with the highest average score.

Additional requirements:

  • Use #define to set the number of students and quizzes.
  • Use pointers to access all array elements and related variables.
  • The program must use loops and basic arithmetic operations like addition and division.

(15 markah/marks)

7/10

--- Page 8 ---

FAC1003

  1. Kesedaran terhadap penggunaan tenaga elektrik yang cekap semakin penting dalam kehidupan moden. Kajian simulasi dijalankan bagi mengira jumlah penggunaan tenaga elektrik yang meningkat secara linear setiap hari dalam satu tempoh masa tertentu. Kadar penggunaan harian bertambah secara tetap mengikut bilangan hari penggunaan peralatan elektrik tersebut.

Pelajar diminta untuk menulis satu atur cara menggunakan bahasa pengaturcaraan C++ bagi mengira jumlah tenaga elektrik dalam unit kilowatt-jam (kWj) berdasarkan peningkatan penggunaan harian tersebut.

Atur cara ini mesti menggunakan fungsi rekursif untuk mengira jumlah kumulatif penggunaan tenaga dari hari pertama hingga hari terakhir. Pengguna perlu memasukkan dua input iaitu: penggunaan tenaga elektrik pada hari pertama dan jumlah bilangan hari penggunaan. Pengiraan mesti berdasarkan formula matematik seperti berikut:

Jumlah_tenaga = penggunaan(hari) + penggunaan(hari - 1)
                + ... + penggunaan(1).

Pelajar wajib memastikan program tersebut mengandungi struktur kawalan if-else, menerima input pengguna, menggunakan operasi matematik asas dan memaparkan jumlah tenaga dengan dua tempat perpuluhan yang tepat. Contoh berikut menunjukkan senario penggunaan:

Hari Penggunaan kumulatif (kWj)
1 1.5
2 3.0
3 4.5

Energy efficiency awareness plays an important role in daily technology usage. A simulation task is assigned to estimate total electricity consumption where daily usage grows linearly across a given number of days. The daily energy consumption increases by a fixed amount each day.

Students are required to write a C++ program that calculates the total energy used in kilowatt-hours (kWh) for an electrical appliance that operates daily with increasing usage.

The program must apply a recursive function to compute the cumulative from the first day up to the last day. Users are expected to provide two inputs: the energy usage on the first day and the total number of days. The calculation must follow the mathematical formula below:

Total_energy = usage(day) + usage(day - 1) + ... + usage(1).

8/10

--- Page 9 ---

FAC1003

The solution should include if-else conditions, user input, basic arithmetic operations, and the cumulative usage must be displayed using two decimal places. The following example illustrates the calculation:

[Table with two columns: "Day" and "Cumulative usage (kWh)". Rows: Day 1 → 1.5, Day 2 → 3.0, Day 3 → 4.5]

(15 markah/marks)

  1. Kecekapan sistem penjanaan tenaga boleh diperbaharui seperti panel solar amat penting bagi menjamin kelestarian tenaga masa hadapan. Pelajar dikehendaki membina satu atur cara menggunakan bahasa pengaturcaraan C++ untuk menganalisis kecekapan sistem panel solar dalam menjana tenaga harian. Dua input utama perlu diterima daripada pengguna, iaitu intensiti cahaya matahari ($W/m^2$) dan luas permukaan panel solar ($m^2$).

Pengiraan pertama melibatkan formula fizik berikut: $$\text{Kuasa (W)} = \text{Intensiti Cahaya} \times \text{Luas Panel}.$$

Pengiraan tenaga harian hendaklah dilakukan berdasarkan formula: $$\text{Tenaga Harian (Wh)} = \text{Kuasa} \times 5 \text{ jam}.$$

Program perlu menentukan kecekapan sistem panel solar berdasarkan syarat bahawa sistem adalah cekap jika dan hanya jika tenaga harian yang dijana adalah sekurang-kurangnya 1000 Wh. Program mestilah menunjukkan status kecekapan sebagai paparan.

Secara teknikal, atur cara wajib menggunakan dua fungsi bukan-void dan dua fungsi void, serta mengandungi:

  • pengiraan perpuluhan menggunakan data double.
  • struktur gelungan untuk ulang proses jika perlu.
  • struktur kawalan bersyarat if-else.
  • fungsi daripada Standard Template Library (STL) termasuk iomanip untuk pemformatan output, cmath untuk operasi matematik, dan string untuk paparan teks.

Reka bentuk program hendaklah mesra pengguna dan memberikan output dengan ketepatan dua tempat perpuluhan.

9/10

--- Page 10 ---

FAC1003

Efficiency of renewable energy systems such as solar panels plays a critical role in future energy sustainability. Students are required to develop a program using the C++ programming language to evaluate the efficiency of a solar panel system based on daily energy production. The program must receive two inputs from the user: sunlight intensity ($W/m^2$) and panel surface area ($m^2$).

The first part of the calculation uses the following physics-based formula: $$\text{Power (W)} = \text{Sunlight Intensity} \times \text{Panel Area}.$$

The next step is to compute the daily energy generated using: $$\text{Daily Energy (Wh)} = \text{Power} \times 5 \text{ hours}.$$

The program must then determine whether the solar system is efficient based on the condition that the system is efficient if and only if the daily energy at least 1000 Wh. The program must show the efficiency status as output display.

The technical requirements for the program are as follows:

  • use two non-void functions and two void functions.
  • include decimal point operations using the double data type.
  • apply a loop structure where needed.
  • use if-else conditional statements to evaluate efficiency.
  • include functions from the Standard Template Library (STL) such as iomanip for formatted output, cmath for mathematical operations, and string for text handling.

The output must be user-friendly, and display all numerical results with two decimal places.

(15 markah/marks)

TAMAT END

10/10


Verbatim transcription via Kimi K2.6 vision subagents.