2nd Semester: Programming (C Language) – 3rd Edition 2021
void main()
{
int x,y,answer1;
printf("Please enter first number:");
scanf("%d",&x);
printf("\n Please enter second number:");
scanf("%d",&y);
answer1 = func_subtraction(x,y);
printf("\n%d - %d = %d ", x,y,answer1); //function call
printf("\n%d x %d = %d ", x,y,func_multiplication(x,y)); //function call
printf("\n%d / %d = %.2f ", x,y,func_division(x,y)); //function call
}
int func_subtraction(int no1,int no2)
{ int f1;
f1=no1-no2;
return f1;
}
int func_multiplication(int no1,int no2)
{ int f2;
f2=no1*no2;
return f2;
}
float func_division(int no1,int no2)
{ float f3;
f3=no1/no2;
return f3;
}
6. // Calculate discount
#include<stdio.h>
float ProductDiscount(float, int);
void main()
{ float ProductPrice;
int discount;
printf("Product Price ? RM");
scanf("%f", &ProductPrice);
printf("Discount ? ");
scanf("%d", &discount);
printf("\nPrice of product after %d %% discount : RM%.2f", discount, ProductDiscount
(ProductPrice, discount));
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
float ProductDiscount (float ProductPrice, int discount)
{
float NewPrice;
NewPrice = ProductPrice - ((float) discount / 100 * ProductPrice);
return NewPrice;
}
7. //function with 1 parameter
#include<stdio.h> //function prototype
char search_grade(int);
void comment(char);
void main()
{
int mark;
printf("Enter your mark : ");
scanf("%d", &mark);
printf("You got grade %c", search_grade(mark)); //function call
comment(search_grade(mark));
}
char search_grade(int mark)
{
char grade;
if (mark >= 80)
grade = 'A';
else if (mark >= 70)
grade = 'B';
else if (mark >= 60)
grade = 'C';
else if (mark >= 50)
grade = 'D';
else
grade = 'E';
return grade;
}
void comment(char mark)
{
switch(mark)
{
case 'A': printf("\nExcellent");
break;
case 'B': printf("\nGood");
break;
case 'C': printf("\nSatisfy");
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
break;
case 'D': printf("\nWeak");
break;
case 'E': printf("\nVery Weak");
break;
}
}
8. /* Functions with parameters */
#include<stdio.h>
void Menu_Greeting(int);
void main()
{
int greeting;
printf("Enter the month of your desired greeting: ");
scanf("%d", &greeting);
Menu_Greeting(greeting);
}
void Menu_Greeting(int greeting) //can use any name variable
{
switch (greeting)
{
case 1: printf("Selamat Hari Raya\n");
break;
case 2: printf("Happy Deepavali\n");
break;
case 3: printf("Kong Xi Fa Choi\n");
break;
default: printf("Error number of greeting");
break;
}
}
9. //Functions with parameter
#include<stdio.h>
void find_value(int);
void main()
{
int num;
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
printf("Enter a number from 1-20: ");
scanf("%d",&num);
if(num<=10)
{ printf("%d less than or equal to 10.\n",num);
find_value(num);
}
else if(num<=20)
{ printf("%d greater than or equal to 20.\n", num);
find_value(num);
}
else
printf("Out of range.");
}
void find_value(int num)
{ int balance;
balance = num % 2;
{ if(balance==1)
printf("%d is a odd number", num);
else
printf("%d is a even number", num);
}
}
10. //function with 1 parameter
#include<stdio.h>
char search_grade(int); //function prototype
void main()
{
int mark;
printf("Enter your mark : ");
scanf("%d", &mark);
printf("You got grade %c", search_grade(mark)); //function call
}
char search_grade(int mark)
{
char grade;
if (mark >= 80)
grade = 'A';
else if (mark >= 70)
grade = 'B';
else if (mark >= 60)
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
grade = 'C';
else if (mark >= 50)
grade = 'D';
else
grade = 'E';
return grade;
}
11. Function with 2 parameter
#include<stdio.h>
void cetak_segiempat(int, int); // function prototype
void main()
{
int long, width;
printf(“What is the long value :”) ;
scanf(“%d”, &long);
printf(“What is the with value:”);
scanf(“%d”, &width);
cetak_segiempat(long, width); //function call
}
void cetak_segiempat(int long, int width) //function definition
{
int i, j, a;
a=1;
for (i=1; i<=long; i++)
{
printf(“\n”);
for (j=1; j<=width; j++)
printf(“%d”, a);
}
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
12. Selepas modify program ini untuk cetak segiempat dan kita kira pula luas segiempat inilah
programnya:
#include<stdio.h>
void cetak_segiempat (int, int);
void kira_luas (int, int); // function prototype
void main()
{
int panjang, lebar;
printf("What is the long value(CM) :") ;
scanf("%d", &panjang);
printf("What is the witdh value(CM):");
scanf("%d", &lebar);
cetak_segiempat(panjang, lebar); //call function
kira_luas(panjang, lebar);//call function
}
void cetak_segiempat(int panje, int leba)
void cetak_segiempat (int panjang, int lebar)
{
int i, j, a;
a=5;
for (i=1; i<=panjang; i++)
{
printf("\n");
for (j=1; j<=lebar; j++)
printf("%d", a);
}
void kira_luas(int panjang,int lebar)
{
int luas;
luas = panjang*lebar;
printf("\n\nThe area of this rectangle is : %d CM2\n", luas);
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
5.7 Tutorial 8: Algorithm for Function
*Save as in C:\Librararies\Documents\Programming C\Tutorial8\
Contoh 1
a) Tulis pseudocode dan bina sebuah carta alir untuk sebuah fungsi (function / subroutine/ module)
yang menerima dua nombor, kemudian mengira hasil tambah kedua-dua nombor tersebut.
b) Seterusnya, tulis pseudocode dan bina carta alir utama (main flowchart) dengan memanggil
fungsi tadi, untuk mengira hasil tambah empat nombor yang dimasukkan oleh pengguna.
Jawapan:
Langkah 1:
Input : 2 nombor, n1 dan n2
Output : Hasil tambah 2 nombor
Proses : Operasi tambah dua nombor dilaksanakan di dalam fungsi (modul)
Langkah 2:
Pseudocode Carta alir (Flowchart)
(a) Main Program Utama (Main)
1. Mula Program Main Start
2. Baca n1 dan n2 Read n1 and n2
3. Panggil fungsi ADD (call function ADD)
4. Papar hasil tambah 2 nombor tersebut ADD (n1, n2)
5. Baca dua nombor baharu n3 dan n4 Print sum1 result
6. Panggil fungsi ADD (call function ADD)
7. Papar hasil tambah 2 nombor tersebut
8. Tamat Main Program
Read n3 and n4
ADD (n1, n2)
Print sum2 result
Stop
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
(b) ADD Function Program Fungsi (Function)
ADD (A,B)
1. Mula Fungsi ADD
2. Operasi tambah 2 nombor yang Result = A + B
Return
dihantar dari main program
3. Pulangkan hasil tambah kepada
4. program main semula.
Contoh 2
Tulis pseudocode dan bina sebuah carta alir untuk sebuah fungsi (function / subroutine/ module) yang
menerima dua nombor, kemudian mengira hasil tambah kedua-dua nombor tersebut.
Jawapan:
Langkah 1:
Input : 3 nombor, n1, n2 dan n3
Output : Nombor yang paling besar antara 3 nombor
Proses : Operasi pengujian terbesar antara 3 nombor dilaksanakan di dalam fungsi (modul)
Langkah 2:
Pseudocode
Main Program
1. Mula Program Main
2. Baca n1, n2 dan n3
3. Panggil fungsi BIGGEST untuk banding n1 dan n2 (call function BIGGEST)
4. Papar nombor yang terbesar
5. Panggil fungsi BIGGEST untuk banding result perbandingan antara n1 dn n2 dengan n3
pula (call function BIGGEST)
6. Papar nombor yang terbesar
7. Tamat Main Program
BIGGEST Function Program
1. Mula Fungsi BIGGEST
2. Pengujian nombor terbesar antara dua nombor
3. Pulangkan nombor terbesar.
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
Carta alir (Flowchart) BIGGEST (x, y) result = x
(a) Fungsi
Yes
is x > y?
No
result = y
(b) Utama Return
Start
Read n1, n2 and n3
BIGGEST (n1, n2)
Print Biggest1
BIGGEST (Biggest1, n3)
Print the latest biggest
number
Stop
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
Contoh 3
Tulis pseudocode dan bina sebuah carta alir untuk mengira hasil tambah nombor-nombor daripada a
hingga b (a > 0 dan b> a).
Seterusnya tulis pseudocode dan bina carta alir utama untuk memanggil fungsi tersebutuntuk mengira
hasil tambah esmua nombor daripan 1 hingga n. (nilai n dimasukkan oleh pengguna)
Jawapan:
Langkah 1:
Input : 3 nombor, n1, n2 dan n3
Output : Nombor yang paling besar antara 3 nombor
Proses : Operasi pengujian terbesar antara 3 nombor dilaksanakan di dalam fungsi (modul)
Langkah 2:
Pseudocode
Sum Function Program
1. Mula Fungsi SUM terima nilai 1 sebagai a dan n sebagai b
2. Letak nilai awalan total = 0 dan num = a.
3. Pergiraan hasil tambah total = total + num
4. Penambahan nilai num dengan 1
5. Pengujian num kurang daripada atau sama dengan nilai b
5.1 Jika benar, ulang ke langkah 3 lagi
5.2 Jika tidak, result = total
6. Pulangkan result kepada program utama
Main Program
1. Mula Program Main
2. Baca n
3. Panggil fungsi Sum hantar nilai 1 dan n
4. Papar keputusan
5. Tamat Main Program
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
Carta alir (Flowchart) SUM (a, b) Yes
Fungsi
Initialize:
Total = 0
num = a
total =total + num
num = num + 1
Is num less than
or equeal to b
No
result = total
Utama Return
Start
Read n © Nar | Nisrin Ahmad Ramly \(^o^)/
SUM (1,n)
Print result
Stop
2nd Semester: Programming (C Language) – 3rd Edition 2021
Soalan
1. Tulis pseudocode dan bina carta alir untuk sebuah fungsi yang mengira isipadu sebuah bongkah.
Seterusnya tulis pseudocode dan bina carta alir utama yang memanggil fungsi tersebut untuk
mengira isipadu sebuah tangki. Dimensi –dimensi tangki tersebut (panjang, lebar dan tinggi)
dimasukkan oleh pengguna.
2. Kereta Honda
a) Tulis pseudocode dan bina carta alir sebuah fungsi untuk mengira Harga Kereta
berdasarkan Model Kereta. Model dan harga kereta adalah seperti berikut:
Model Kereta Harga (RM)
Honda Accord 2.0 VTi 14 1000.00
Honda City 1.5 VTEC 85 000.00
Honda Civic 2.0 I-VTEC 122 000.00
b) Tulis pseudocode dan bina carta alir sebuah fungsi untuk mengira Kadar Bunga (interest
rate) berdasarkan bilangan tahun pinjaman. Kadar pinjaman adalah seperti berikut:
Bil Tahun Kadar Bunga (%)
1 -3 2.0
4–5 2.5
6–9 2.7
10 3.0
c) Tulis pseudocode dan bina carta alir utama yang menggunakan kedua-dua carta alir
fungsi di atas untuk mengira Ansuran Bulanan (monthly payment). Input yang perlu
dimasukkan oleh pengguna adalah Model Kereta yang hendak dibeli, downpayment dan
bilangan tahun pinjaman.
3. Tulis pseudocode dan bina sebuah carta alir fungsi untuk mengira factorial suatu nombor, n.
4. Tulis pseudocode dan bina sebuah carta alir untuk mengira bilangan nombor gandaan a
daripada 1 hingga n.
Contoh:
Katakan a = 3 (bermakna nombor ganddan 3
n = 15 (bermakna 1 hingga 15)
Nombor gandaan 3 daripada 1 hingga 15 ialah 3, 6, 9, 12, 15
Maka bilangan nombor = 5
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
5.8 Quiz Function
1. State the condition of the statement is true or false.
a) Top-down design and structured programming design determine a program should be separated
into a main module and its related modules.
b) A function can return more than one value.
c) A function prototype requires only the return type of the function, the function name, and the
number, types and the order of the formal parameters.
d) Variables defined within a block have a global scope.
2. State an appropriate function call for each of the following functions.
a. float line (float a)
{
float b;
b = 3 * a – 1;
return (b);
}
b. void height_ball ( int k, int l )
{
int c;
c = sqrt ( k * k + 1 * 1 );
printf(“c=%i \n”, c);
}
3. Write the first line of the function definition, including argument declarations.
a. A function called simple generates and returns a floating-point quantity.
b. A function called peak accepts two integer arguments and returns a integer results.
c. A function called differ accepts a character and returns another character.
d. A function called move accepts long integer and returns a character.
e. A function called reverse accepts a vharacter and returns a long integer.
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6. Data Structures
Data
Structures
Arrays Structures
6.1 Arrays
An array is a collection of data that holds fixed number of values of same type. For example: if you
want to store marks of 100 students, you can create an array for it.
float marks [100];
The size and type of arrays cannot be changed after its declaration.
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.1.1 One-dimensional Arrays
Array declaration, initialization Example
and accessing
Integer array example:
Array declaration syntax: int age [5];
data_type arr_name [arr_size]; int age [5] = {0, 1, 2, 3, 4};
Array initialization syntax: age [0]; /*0 is accessed*/
data_type arr_name [arr_size] = age [1]; /*1 is accessed*/
(value1, value2, value3,..); age [2]; /*2 is accessed*/
Array accessing syntax: Character array example:
arr_name[index]; char str [10];
char str [10] = {‘H’, ‘a’, ‘i’};
(or)
char str [0] = ‘H’;
char str [1] = ‘a’;
char str [2] = ‘i;
str [0]; /*H is accessed*/
str [1]; /*a is accessed*/
str [2]; /*i is accessed*/
6.1.1.1 How to declare an array in C?
data_type array_name[array_size];
For example, float mark [5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5
floating-point values.
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.1.1.2 Elements of an Array and How to access them?
You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark [0], second element is
mark [1] and so on.
Few key notes:
1. Arrays have 0 as the first index not 1. In this example, mark [0]
2. If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark
[4]
3. Suppose the starting address of mark [0] is 2120d. Then, the next address, a [1], will be 2124d,
address of a [2] will be 2128d and so on. It's because the size of a float is 4 bytes.
6.1.1.3 How to initialize an array in C programming?
It's possible to initialize an array during declaration. For example,
int mark [5] = {19, 10, 8, 17, 9};
Another method to initialize array during declaration:
int mark [] = {19, 10, 8, 17, 9};
Here,
mark [0] is equal to 19
mark [1] is equal to 10
mark [2] is equal to 8
mark [3] is equal to 17
mark [4] is equal to 9
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.1.1.4 How to insert and print array elements?
int mark [5] = {19, 10, 8, 17, 9}
// insert different value to third element
mark [2] = 9;
// take input from the user and insert in third element
scanf ("%d", &mark [2]);
// take input from the user and insert in (i+1) th element
scanf ("%d", &mark[i]);
// print first element of an array
printf ("%d", mark [0]);
// print ith element of an array
printf ("%d", mark[i-1]);
6.1.1.5 Example: C Arrays
// Program to find the average of n (n < 10) numbers using arrays
#include <stdio.h>
int main ()
{
int marks [10], i, n, sum = 0, average;
printf ("Enter n: ");
scanf ("%d", &n);
for (i=0; i<n; ++i)
{
printf ("Enter number%d: “, i+1);
scanf ("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf ("Average marks = %d", average);
printf ("Diplay value in array marks”);
for (i=0; i<n; ++i)
{
printf (" number%d: “, marks[i]);
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
6.1.1.6 Important thing to remember when working with C arrays
Suppose you declared an array of 10 elements. Let's say,
int testArray [10];
You can use the array members from testArray [0] to testArray [9].
If you try to access array elements outside of its bound, let's say testArray [12], the compiler
may not show any error. However, this may cause unexpected output (undefined behavior)
6.1.2 Tutorial 9: Array One Dimensional
*Save as in C:\Librararies\Documents\Programming C\Tutorial9\
1. #include<stdio.h>
#include<conio.h>
main()
{
int x[5]={4, 3, 2, -5, 9};
int total=0, i;
for (i=0; i < 5; i++)
{
printf(“x[%d]=%d\n”, i, x[i] );
total+=x[i];
}
printf(“TOTAL=%d\n”, total );
getch();
return 0;
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
}
2. /* this program is to read 10 numbers and get an average */
#include<conio.h>
#include<stdio.h>
main( )
{
clscr();
int x[10], total=0, i;
for (i=1; i <= 10; i++)
{
printf("Insert number %d>>>", i);
scanf("%d", &x[i]);
total+=x[i];
}
printf("TOTAL = %d\n", total);
printf("AVERAGE = %d",total/10);
getch();
return 0;
}
3. // Sum the number in array
#include<stdio.h>
#define MAX 10
void main ()
{
int num [MAX];
int a, total = 0;
for (a=0; a<10; a++)
{
printf ("%d. Enter 10-digit number: ", a+1);
scanf ("%d", &num[a]);
}
//total all number in array
for (a=0; a<10; a++)
total = total + num[a];
printf ("\nElements in array is");
for (a=0; a<10; a++)
printf("\nnum[%d] = %d", a, num[a]);
printf ("\n\nTotal digit in array is %d”, total);
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
4. #include <stdio.h>
main ()
{
int i, num [5];
// Input data
printf ("Input 5 scores \n");
printf ("Input scores from 0 to 100\n");
for (i=0; i<4; i++)
{
scanf ("%d”, &num[i]);
}
// Show the data
for (i=0; i<4; i++)
{
printf ("score %d = %d\n”, i+1, num [i]);
}
return (0);
}
5. // Array 1 dimensional
#include<stdio.h>
void main ()
{
int mark [6] = {78,98,86,80,75,70};
int i;
for (i=0; i<6; i++)
printf ("Mark student %d [%d] = %d\n", i+1, i, mark[i]);
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.1.3 Searching An Array
Array is usually used to store a list of data, for example list of students scores and list of staff
salary.
At times, we want to find out a certain value like the highest score from the list.
Highest and lowest values of the list can be easily accessed by using array, and also for and if
structure.
Example :
/*This program is to get a maximum value from an array */
#include<conio.h>
#include<stdio.h>
void main ()
{
int i, num [10], max;
printf (“Insert 10 numbers\n”);
for (i=0; i<10; i++)
scanf (“%d”, &num[i]);
max=num [10];
for (i=0; i<10; i++)
{
if (num[i] > max)
{
max = num[i];
}
}
printf (“MAXIMUM value is %d\n”, max);
getch ();
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.1.3.1 Tutorial 10: Searching an Array
*Save as in C:\Librararies\Documents\Programming C\Tutorial10\
1. #include<stdio.h>
void SumArray(int [ ]);
void main( )
{
int markah[5];
int i;
for(i=0; i<5; i++)
{
printf ("Enter mark %d ---> ", i+1);
scanf("%d", &markah[i]);
}
SumArray(markah);
}
void SumArray(int markah[ ])
{
int i;
for (i=0; i<5; i++)
printf (" In Array, Mark[%d] %d\n", i, markah[i]);
}
2. //This program is to get the minimum and maximum value from an array.
#include<conio.h>
#include<stdio.h>
void main( )
{
int i, num[10], max, min;
printf("Insert 10 numbers:\n");
for (i=0; i<10; i++)
scanf("%d",&num[i]);
max=num[10];
min=num[10];
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
for(i=0; i<10; i++)
{
if (num[i] > max)
{
max = num[i];
}
if (num[i] < min)
{
min = num[i];
}
}
printf("MAXIMUM value is %d\n", max);
printf("MINUMUM value is %d\n", min);
getch();
}
3. #include<stdio.h>
#include<conio.h>
void main( )
{
int i, mark[5], j;
// clscr( );
printf("Insert 5 computing students marks:\n");
for (i=0; i<5; i++)
{
scanf("%d",&mark[i]);
}
j=0;
for(i=0; i<5; i++)
{
if (mark[i]>=50)
{
j++;
}
}
printf("\n Total of students passed: %d", j);
getch( );
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
4. // searching for minimum or maximum number
#include<stdio.h>
void main()
{
int num[5];
const n=5;
printf("Enter 5 digit number.\n\n");
for(int a=0; a<n; a++)
{ printf("Number %d : ", a+1);
scanf("%d", &num[a]);
}
//searching maximum number
int max=0;
for(int e=0; e<n; e++)
if(max < num[e])
max = num[e];
printf("\nThe number maximum is %d", max);
}
6.1.2 Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array.
A two-dimensional array is, in essence, a list of one-dimensional arrays.
To declare a two-dimensional integer array of size [x][y], you would write something as follows −
type arrayName [ x] [ y];
Where type can be any valid C data type and arrayName will be a valid C identifier.
A two-dimensional array can be considered as a table which will have x number of rows and y
number of columns.
A two-dimensional array a, which contains three rows and four columns can be shown as
follows –
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where
'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element
in 'a'.
Array declaration, initialization and accessing Example
Array declaration syntax:
data_type arr_name [num_of_rows] [num_of_column]; Integer array example:
int arr [2][2];
Array initialization syntax: int arr [2][2] = {1,2, 3, 4};
data_type arr_name [2][2] = {{0,0}, {0,1}, {1,0}, {1,1}};
arr [0] [0] = 1;
Array accessing syntax: arr [0] ]1] = 2;
arr_name[index]; arr [1][0] = 3;
arr [1] [1] = 4;
6.1.2.1 Example Program for Two Dimensional Arrays:
Example 1:
1 #include<stdio.h>
2
3 int main ()
4{
5 int i, j;
6 // declaring and Initializing array
7 int arr [2][2] = {10,20,30,40};
8 /* Above array can be initialized as below also
9 arr [0][0] = 10; // Initializing array
10 arr [0][1] = 20;
11 arr [1][0] = 30;
12 arr [1][1] = 40; */
13 for (i=0; i<2; i++)
14 {
15 for (j=0; j<2; j++)
16 {
17 // Accessing variables
18 printf ("value of arr[%d] [%d]: %d\n”, i, j, arr[i][j]);
19 }
20 }
21 }
Output:
value of arr [0] [0] is 10
value of arr [0] [1] is 20
value of arr [1] [0] is 30
value of arr [1] [1] is 40
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.1.2.2 Tutorial 11: Program for Two Dimensional Arrays:
*Save as in C:\Librararies\Documents\Programming C\Tutorial11\
// Array 2 Dimensional
#include<stdio.h>
void main ()
{ const int a=3, b=2;
int mark[a][b];
int row, column;
printf ("ARRAY 2 DIMENSIONAL\n\n");
for (row=0; row<a; row++)
{ printf("\n");
for (column=0; column<b; column++)
{ printf("mark[%d] [%d] = ", row, column);
scanf ("%d", &mark[row][column]);
}
}
printf("\n");
//print array
for (row=0; row<a; row++)
{ for (column=0; column<b; column++)
printf ("%d\t", mark[row][column]);
printf("\n");
}
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.2 Sorting an Array
Many situation in life we need to present a list of data in order.
For example, we might need to sort a list of integers in ascending order.
Sorting an
Array
Bubble Insertion
6.2.1 Bubble Sort
Bubble sort repetitively compares adjacent pairs of elements and swaps if necessary.
Scan the array, swapping adjacent pair of elements if they are not in relative order. This
bubbles up the largest element to the end.
Scan the array again, bubbling up the second largest element.
Repeat until all elements are in order.
The following bubbleSort () method implements bubble sort. It uses a nested loop to repetitively
swap elements and bubble up the largest elements one by one.
Example 1:
1 public static void bubbleSort (int [] data)
2{
3 for (int i = data. length - 1; i >= 0; i--)
4{
5 // bubble up
6 for (int j = 0; j <= i - 1; j++)
7{
8 if (data[j] > data [j + 1])
9 swap (data, j, j + 1);
10 }
11 }
12 }
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
The following tracks the code on an array with elements {38, 27, 43, 3, 9, 82, 10} for three rounds of
bubbling.
1 {38, 27, 43, 3, 9, 82, 10}
2 i: 6
3 {27, 38, 43, 3, 9, 82, 10}, j: 0
4 {27, 38, 43, 3, 9, 82, 10}, j: 1
5 {27, 38, 3, 43, 9, 82, 10}, j: 2
6 {27, 38, 3, 9, 43, 82, 10}, j: 3
7 {27, 38, 3, 9, 43, 82, 10}, j: 4
8 {27, 38, 3, 9, 43, 10, 82}, j: 5
9 i: 5
10 {27, 38, 3, 9, 43, 10, 82}, j: 0
11 {27, 3, 38, 9, 43, 10, 82}, j: 1
12 {27, 3, 9, 38, 43, 10, 82}, j: 2
13 {27, 3, 9, 38, 43, 10, 82}, j: 3
14 {27, 3, 9, 38, 10, 43, 82}, j: 4
15 i: 4
16 {3, 27, 9, 38, 10, 43, 82}, j: 0
17 {3, 9, 27, 38, 10, 43, 82}, j: 1
18 {3, 9, 27, 38, 10, 43, 82}, j: 2
19 {3, 9, 27, 10, 38, 43, 82}, j: 3
Example 2: A bubble sort compares 2 array elements and exchanges values if they are out of order.
Loop 1:
32514
2 3 5 1 4 /* swap 3 and 2 */
2 3 5 1 4 /* Compare 3 and 5 */
2 3 1 5 4 /* swap 1 and 5 */
2 3 1 4 5 /* swap 5 and 4 */
Loop 2:
2 3 1 4 5 /* swap 2 with 3 */
2 1 3 4 5 /* swap 1 with 3 */
2 1 3 4 5 /* Compare 3 with 4 */
Loop 3:
1 2 3 4 5 /*swap 2 with 1 */
1 2 3 4 5 /*compare 2 with 3 */
Loop 4:
1 2 3 4 5 /* compare 1 with 2 */
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.2.1.1 Tutorial 12 : Bubble Sort
*Save as in C:\Librararies\Documents\Programming C\Tutorial12\
1. #include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void main( )
{
// clscr( );
int nom[10],i,j,temp;
for(i=0;i<10;i++)
{
nom[i]=(rand( )%10); // generate random numbers range 0-10
printf("[%d]=%d\n",i,nom[i]);
}
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(nom[i]>nom[j])
{
temp=nom[i];
nom[i]=nom[j];
nom[j]=temp;
}
}
}
for(i=0;i<10;i++)
{
printf("%d\t",nom[i]);
}
getch();
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
2. //susunan nombor secara Isihan Buih(Bubble Sort)
#include<stdio.h>
void main( )
{ int no[5];
int temp;
printf("Masukkan 5 nombor:\n\n");
for(int a=0; a<5; a++)
{
printf("Nombor %d :", a+1);
scanf("%d", &no[a]);
}
// susun secara Isihan Buih
for (int b=0; b<5; b++)
{
for (int c=1; c<5; c++)
if (no[c]<no[c-1])
{
int temp;
temp=no[c];
no[c]=no[c-1];
no[c-1]=temp;
}
}
printf("\nSusunan menaik nombor tersebut ialah: ");
for(int d=0; d<5;d++)
printf("%d\t",no[d]);
}
// modify the program above for sorting descending.
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
3. Modify
//susunan nombor secara Isihan Buih(Bubble Sort)
#include<stdio.h>
void main()
{
int no[5];
int temp;
printf("Masukkan 5 nombor:\n\n");
for(int a=0; a<5; a++)
{
printf("Nombor %d :", a+1);
scanf("%d", &no[a]);
}
// susun secara Isihan Buih
for (int b=0; b<5; b++)
{
for (int c=1; c<5; c++)
if (no[c]<no[c-1])
{ int temp;
temp=no[c];
no[c]=no[c-1];
no[c-1]=temp;
}
}
printf("\nSusunan menaik nombor tersebut ialah: ");
for(int d=0; d<5;d++)
printf("%d\t",no[d]);
for (int e=0; e<5; e++)
{
for (int f=1; f<5; f++)
if (no[f]>no[f-1])
{ int temp;
temp=no[f];
no[f]=no[f-1];
no[f-1]=temp;
}
}
printf("\nSusunan menurun nombor tersebut ialah: ");
for(int g=0; g<5;g++)
printf("%d\t",no[g]);
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.2.2 Insertion Sort
Insertion sort maintains a sorted sub-array, and repetitively inserts new elements into it. The
process is as following:
Take the first element as a sorted sub-array.
Insert the second element into the sorted sub-array (shift elements if needed).
Insert the third element into the sorted sub-array.
Repeat until all elements are inserted.
The following insertionSort () method implements insertion sort. It uses a nested loop to
repetitively insert elements into the sorted sub-array.
1 public static void insertionSort (int [] arr)
2{
3 for (int i = 1; i < arr. length; i++)
4{
5 // a temporary copy of the current element
6 int tmp = arr[i];
7 int j;
8
9 // find the position for insertion
10 for (j = i; j > 0; j--)
11 {
12 if (arr [j - 1] < tmp)
13 break;
14 // shift the sorted part to right
15 arr[j] = arr [j - 1];
16 }
17
18 // insert the current element
19 arr[j] = tmp;
20 }
21 }
The following tracks the code on an array with elements {38, 27, 43, 3, 9, 82, 10}.
1 {38, 27, 43, 3, 9, 82, 10}
2 {27, 38, 43, 3, 9, 82, 10}, i: 1
3 {27, 38, 43, 3, 9, 82, 10}, i: 2
4 {3, 27, 38, 43, 9, 82, 10}, i: 3
5 {3, 9, 27, 38, 43, 82, 10}, i: 4
6 {3, 9, 27, 38, 43, 82, 10}, i: 5
7 {3, 9, 10, 27, 38, 43, 82}, i: 6
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
Summary
Algorithm Bubble sort Insertion sort
Pros Scan through the array from
left to right, comparing The first part of the list is sorted and
adjacent elements. the remainder is unsorted.
Whenever two adjacent To begin with, all elements are in
elements are out of order, the unsorted part.
swap them. Go through the elements in the
Repeat this until the array is unsorted part sequencially and
sorted. insert each into the sorted part by
searching for it's correct position
Simple to implement and with a linear search or a binary
understand, but not much search.
more so than several more
efficient sorts Fairly easy to implement with a
Will be very quick on an linear search
already sorted list If a backwards linear search is used,
it is much faster on a partially sorted
array
Cons Probably the slowest sort ever On an array, insertion is slow because all
invented the elements after it have to be moved
up.
Notes Don't bother learning this -
sort.
There are other sorts which
are just as easy to implement
and much faster.
Although there are some
time saving modifications
that can be made (e.g.
keeping track of the last swap
in the previous pass, and only
going up to there in the
current pass), they aren't
worth it.
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.2.3 Tutorial 13: Multi dimensional Array
*Save as in C:\Librararies\Documents\Programming C\Tutorial13\
Koperasi SMKTS menjual 2 jenis disket iaitu bersaiz: 31/2” dan 51/4”. Setiap disket adalah dalam kapasiti:
“single-sided double density”,”double-sided double density”,”single-sided high density” dan “double-
sided high density”.
Harga bagi disket tersebut adalah seperti berikut:
Saiz Double Density High Density
disket
Single sided Double sided Single sided Double sided
3”
5” 2.30 2.75 3.20 3.50
1.75 2.10 2.60 2.95
Anda dikehendaki menulis satu aturcara pendek di dalam C bagi memudahkan menyimpan nilai-nilai
harga bagi setiap kategori disket seperti di atas.
Contoh Output: RM2.30
RM2.75
RM3.20
RM3.50
RM1.75
RM2.10
RM2.10
RM2.60
RM2.95
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.3 Passing Arrays as Function Arguments
If you want to pass a single-dimension array as an argument in a function, you would have to
declare a formal parameter in one of following three ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going to be
received.
Similarly, you can pass multi-dimensional arrays as formal parameters.
6..3.1 Way-1
Formal parameters as a sized array −
void myFunction (int param [10])
{
.
.
.
}
6.3.2 Way-3
Formal parameters as an unsized array −
void myFunction (int param [])
{
.
.
.
}
6.3.3 Tutorial 14: Passing Arrays
*Save as in C:\Librararies\Documents\Programming C\Tutorial14\
Now, consider the following function, which takes an array as an argument along with another
argument and based on the passed arguments, it returns the average of the numbers passed through
the array as follows –
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
double getAverage (int arr [], int size)
{
int i;
double avg;
double sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
Now, let us call the above function as follows –
#include <stdio.h>
/* function declaration */
double getAverage (int arr [], int size);
int main ()
{
/* an int array with 5 elements */
int balance [5] = {1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = getAverage (balance, 5);
/* output the returned value */
printf (“Average value is: %f ", avg);
return 0;
}
When the above code is compiled together and executed, it produces the following result −
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C
performs no bounds checking for formal parameters.
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.4 Tutorial 15: Arrays
*Save as in C:\Librararies\Documents\Programming C\Tutorial15\
1. // without Array 1 dimensional
#include<stdio.h>
void main ()
{
int student1, student2, student3, student4, student5, student6;
student1 = 78;
student2 = 98;
student3 = 86;
student4 = 80;
student5 = 75;
student6 = 70;
printf ("Mark student1 = %d\n", student1);
printf ("Mark student2 = %d\n", student2);
printf ("Mark student3 = %d\n", student3);
printf ("Mark student4 = %d\n", student4);
printf ("Mark student5 = %d\n", student5);
printf ("Mark student6 = %d\n", student6);
}
2. // Array 1 dimensional
#include<stdio.h>
void main ()
{
int mark [6] = {78,98,86,80,75,70};
int i;
for (i=0; i<6; i++)
printf ("Mark student %d [%d] = %d\n", i+1, i, mark[i]);
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
3. // Array 1 dimensional with parameters
#include<stdio.h>
void SumArray (int []);
void main ()
{
int mark [5];
int i;
for (i=0; i<5; i++)
{ printf ("Enter mark %d: ", i+1);
scanf ("%d", &mark[i]);
}
SumArray(mark);
}
void SumArray (int mark [])
{
int i;
for (i=0; i<5; i++)
printf ("\nIn array, mark[%d] %d", i, mark[i]);
}
4. // Array 1 dimensional
#include<stdio.h>
void main ()
{
int mark [6];
int i;
for (int counter=0; counter < 6; counter++)
{ printf ("Please enter mark student %d: ", counter+1 );
scanf ("%d", &mark[counter]);
}
for (i=0; i<6; i++)
printf ("Mark student %d [%d] = %d\n", i+1,i, mark[i]);
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
5. #include <stdio.h>
main () {
int i, num [5];
// Input data
printf ("Input 5 scores \n");
printf ("Input scores from 0 to 100\n");
for (i=0; i<4; i++) {scanf ("%d”, &num[i]);}
// Show the data
for (i=0; i<4; i++) {printf ("score %d = %d\n”, i+1, num [i]);}
return (0);
}
6. // Bubble Sort
#include<stdio.h>
void main ()
{
int num [5];
printf ("Enter 5-digit number. \n\n");
for (int a=0; a<5; a++)
{ printf ("Number %d: ", a+1);
scanf ("%d", &num[a]);
}
//Sorting
for (int b=0; b < (5-1); b++)
{
for (int c=1; c<5; c++)
if (num[c]<num[c-1])
{ int temp;
temp = num[c];
num[c] = num[c-1];
num[c-1] =temp;
}
}
printf ("\nAscending order is ");
for (int d=0; d<5; d++)
printf ("%d “, num[d]);
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
7. // Bubble Sort -descending
#include<stdio.h>
void main ()
{
int num [5];
printf ("Enter 5-digit number. \n\n");
for (int a=0; a<5; a++)
{ printf ("Number %d: ", a+1);
scanf ("%d", &num[a]);
}
//Sorting
for (int b=0; b < (5-1); b++)
{
for (int c=1; c<5; c++)
if (num[c]>num[c-1])
{ int temp;
temp = num[c];
num[c] = num[c-1];
num[c-1] =temp;
}
}
printf ("\nAscending order is ");
for (int d=0; d<5; d++)
printf ("%d “, num[d]);
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
6.3 Structures
C Structure is a collection of different data types which are grouped together and each element in a C
structure is called member.
If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and memory will be allocated for
each separately.
It is a best practice to initialize a structure to null while declaring, if we don’t assign any values
to structure members.
6.31 Difference between C Variable, C Array and C Structure
A normal C variable can hold only one data of one data type at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types and Data types can be int, char, float,
double and long double etc.
C Structure:
Syntax struct student
{
int a;
char b [10];
}
Example a = 10;
b = “Hello”;
C Variable:
Syntax: int a;
int Example: a = 20;
Syntax: char b;
char Example: b=’Z’;
C Array:
int Syntax: int a [3];
Example:
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
a [0] = 10;
a [1] = 20;
a [2] = 30;
a [3] = ‘\0’;
Syntax: char b [10];
char Example:
b= “Hello”;
6.3.2 Table Explains Following Concepts in C Structure
1. How to declare a C structure?
2. How to initialize a C structure?
3. How to access the members of a C structure?
Using normal variable
Syntax:
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example:
struct student
{
int mark;
char name [10];
float average;
};
Declaring structure using normal variable:
struct student report;
Initializing structure using normal variable:
struct student report = {100, “Mani”, 99.5};
Accessing structure members using normal
variable:
report.mark;
report.name;
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
report.average;
6.3.3 Example of Structure
Structure is used to represent a record. Suppose you want to store record of Student which consists of
student name, address, roll number and age. You can define a structure to hold this information.
Defining a structure
struct keyword is used to define a structure. struct define a new data type which is a collection of
different type of data.
Syntax:
struct structure_name
{
//Statements
};
Example of Structure
struct Book
{
char name [15];
int price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which consists of three data fields,
namely name, price and pages. These fields are called structure elements or members. Each member
can have different data type, like in this case, name is of char type and price is of int type etc. Book is
the name of the structure and is called structure tag.
Declaring Structure Variables
It is possible to declare variables of a structure, after the structure is defined. Structure variable
declaration is similar to the declaration of variables of any other data types. Structure variables can be
declared in following two ways.
1) Declaring Structure variables separately
struct Student
{
char [20] name;
int age;
int rollno;
};
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
struct Student S1, S2; //declaring variables of Student
2) Declaring Structure Variables with Structure definition
struct Student
{
char [20] name;
int age;
int rollno;
} S1, S2;
Here S1 and S2 are variables of structure Student. However, this approach is not much recommended.
Accessing Structure Members
Structure members can be accessed and assigned values in number of ways. Structure member has no
meaning independently. In order to assign a value to a structure member, the member name must be
linked with the structure variable using dot. operator also called period or member access operator.
struct Book
{
char name [15];
int price;
int pages;
} b1, b2;
b1. price=200; //b1 is variable of Book type and price is member of Book
We can also use scanf () to give values to structure members through terminal.
scanf (" %s ", b1.name);
scanf (" %d ", &b1.price);
Structure Initialization
Like any other data type, structure variable can also be initialized at compile time.
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = {180.75, 73, 23}; //initialization
or
struct patient p1;
p1.height = 180.75; //initialization of each member separately
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
p1.weight = 73;
p1.age = 23;
Array of Structure
We can also declare an array of structure. Each element of the array representing
a structure variable. Example: struct employee emp [5];
The above code defines an array emp of size 5 elements. Each element of array emp is of
type employee
#include<stdio.h>
#include<conio.h>
struct employee
{
char ename [10];
int sal;
};
struct employee emp [5];
int i, j;
void ask ()
{
for (i=0; i<3; i++)
{
printf ("\nEnter %dst employee record\n”, i+1);
printf ("\nEmployee name\t");
scanf ("%s”, emp[i]. ename);
printf ("\nEnter employee salary\t");
scanf ("%d”, &emp[i]. sal);
}
printf ("\nDisplaying Employee record\n");
for (i=0; i<3; i++)
{
printf ("\nEmployee name is %s”, emp[i].ename);
printf ("\nSlary is %d”, emp[i].sal);
}
}
void main ()
{
clrscr ();
ask ();
getch ();
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
Nested Structures
Nesting of structures, is also permitted in C language.
Example:
struct student
{
char [30] name;
int age;
struct address
{
char [50] locality;
char [50] city;
int pincode;
};
};
Structure as function arguments
We can pass a structure as a function argument in similar way as we pass any other variable or array.
Example:
#include<stdio.h>
#include<conio.h>
struct student
{
char name [10];
int roll;
};
void show (struct student st);
void main ()
{
struct student std;
clrscr ();
printf ("\nEnter student record\n");
printf ("\nstudent name\t");
scanf ("%s”, std.name);
printf ("\nEnter student roll\t");
scanf ("%d”, &std.roll);
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
show(std);
getch ();
}
void show (struct student st)
{
printf ("\nstudent name is %s”, st.name);
printf ("\nroll is %d”, st.roll);
}
6.3.4 Tutorial 15: Structure
*Save as in C:\Librararies\Documents\Programming C\Tutorial15\
1. #include<stdio.h>
struct car
{
char maker [40];
char model [40];
int year;
};
Struct car FirstCar= {"Proton", "Perdana", 2000};
int main ()
{
struct car SecondCar;
printf ("%20s%s, %s, %d\n", "First Car:”, FirstCar.maker, FirstCar.model, FirstCar.year);
SecondCar=FirstCar;
printf ("%20s%s, %s, %d\n", "Second Car:”, SecondCar.maker, SecondCar.model,
SecondCar.year);
printf ("%20s is %d bytes\n", "size of FirstCar:”, sizeof (FirstCar));
printf ("%20s is %d bytes\n", "size of SecondCar:”, sizeof (SecondCar));
return 0;
}
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
2. #include<stdio.h>
struct date
{
int day,
int month,
int year;
} Me
main ()
{
Me.day = 5;
Me.month = 1;
Me.year = 1979;
printf ("I was born: %d/%d/%d\n", Me.day, Me.month, Me.year);
return 0;
}
3. #include<stdio.h>
struct card
{
char *face;
char *suit;
}a;
main( )
{
a.face = “Queen”;
a.suit = “Hearts”;
printf(“%s of %s\n”, a.face, a.suit);
return 0;
}
4. #include<stdio.h>
struct plus
{
char colour[10];
float price;
};
struct car
{
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
char maker[40];
char model[40];
int year;
struct plus more;
};
struct car FirstCar = {"Proton", "Perdana", 2005,{"White", 98000.00}};
int main( )
{
printf("First Car:%s, %s, %d, %s, RM%.2f\n", FirstCar.maker, FirstCar.model,
FirstCar.year, FirstCar.more.colour, FirstCar.more.price);
return 0;
}
5. #include <stdio.h>
#define MAX 10
struct book
{
char title[81];
char author[81];
char category[41];
};
int menu(void);
struct book add(void);
void list(book sp[ ],int size);
int main( )
{
struct book library[MAX];
int choice,count = 0;
do
{
choice = menu();
switch (choice)
{
case 0: puts("\nThank You"); break;
case 1: if(count<MAX)
{
library[count]=add();
count++;
© Nar | Nisrin Ahmad Ramly \(^o^)/
2nd Semester: Programming (C Language) – 3rd Edition 2021
}
else
puts("Library has reached maximum capacity");
break;
case 2:{
list(library,count);
break;
}
default: puts("Wrong selection.Try again.");
};
}while (choice !=0);
return 0;
}
int menu(void)
{
int choice;
puts("\n<<Main Menu>>");
puts("\t0:exit");
puts("\t1:add a book");
puts("\t2:list all books");
printf ("enter your selection:");
scanf("%d",&choice);
return choice;
}
struct book add(void)
{
struct book temp;
fflush(stdin);
puts("\n << Add Menu >>");
printf("title?");
gets(temp.title);
printf("author?");
gets(temp.author);
printf("category?");
gets(temp.category);
© Nar | Nisrin Ahmad Ramly \(^o^)/