Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

EEET2601 Engineering Computing 1

Week 4 - Arrays
Problem
• To compute the average quiz marks of 3 students, we could do this:
int mark0, mark1, mark2;
printf("Enter mark0: ");
scanf("%d", &mark0);
printf("Enter mark1: ");
scanf("%d", &mark1);
printf("Enter mark2: ");
scanf("%d", &mark2);
float avg = (mark0 + mark1 + mark2) / 3.0;

• What if we have 1,000 marks?


2
What is an array?
▪ Single Variable ▪ Array
int mark = 8; int marks[5] = {7, 5, 10, 6, 8};

8 value 7 5 10 6 9 values

• An array is a collection of multiple elements with


the same data type
• Array elements are stored in continuous memory
locations
• Array size (number of elements) can’t be
changed after the array is created
3
How to create an array?
// Syntax
data_type array_name[array_size];

// Declare array, values of array elements are unknown


int marks[5];

// Declare & initialize array

int marks[5] = {7, 5, 10, 6, 9};


int marks[] = {7, 5, 10, 6, 9}; //the array size will be automatically inferred
int marks[5] = {8}; //other elements are initialized with value 0

4
How to access each element?
• We can access all elements of an array by their indexes.
• Suppose you declared an array marks as previously. The first element
is marks[0], the second element is marks[1], and so on.

Array Size = 5

Indexes: 0 1 2 3 4
Element Access: marks[0] marks[1] marks[2] marks[3] marks[4]
Calculate average value

• Suppose that we have an array: int marks[5] = {7, 5, 10, 6, 9};

• We can calculate the average mark like this


float avg = (marks[0] + marks[1] + marks[2] + marks[3] + marks[4]) / 5.0;

• Or using a loop
#define SIZE 5 //define a constant value

int sum = 0;
for (int i = 0; i < SIZE; i++) {
sum = sum + marks[i];
}
float avg = (float)sum / SIZE; //(float) means type casting to float data type

6
Array size known at runtime and input values
// Create an array whose size only known at runtime
printf("Enter array size: ");
int size;
scanf("%d", &size);
int marks[size]; // Compute average mark
float sum = 0;
// Input arr for (int i = 0; i < size; i++) {
for (int i = 0; i < size; i++) { sum += marks[i];
printf("Enter arr[%d]: ", i); }
scanf("%d", &marks[i]); float avg = sum / size;
}
// Output average mark
printf("The average mark is %.2f\n", avg)
;

7
Search for a value in an array
// Array of marks to search /* Search the array for the value
#define SIZE 5 //define a constant value --> found or not ? */
int marks[SIZE] = {6, 2, 8, 9, 5}; int found = 0;
for (int i = 0; i < SIZE; i++) {
// Input a value to search for if (marks[i] == value) {
printf("Enter a value to search for: "); found = 1;
int value; }
scanf("%d", &value); }

// Output search result


if (found) {
printf("%d is in the array\n", value);
} else {
printf("%d is not in the array\n",
value);
}

8
Find the largest element of an array
// Array of arr
int arr[] = {6, 2, 8, 9, 5};

// Find the largest element of the array


int largest = arr[0];
...

// Output the largest element


printf("The largest element is %d\n", largest);

9
Generate a random integer
#include <stdio.h>
#include <stdlib.h> • Use rand() and srand() in <stdlib.h>
#include <time.h>
• Use time(NULL) in <time.h>
int main() {
int N = 100;

//Intializes random number generator


srand(time(NULL));

//Generate random number from 0 to N


int num = rand() % (N + 1);
printf("Got a random num is: %d \n", num); Output:

return 0;
}

10
Generate an array of random integers
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 5

int main() {
int arr[SIZE];

/* Generate array of random integers */


srand(time(NULL)); // Initialize random generator

//Generate random values in range [0..100]


for (int i = 0; i < SIZE; i++) {
arr[i] = rand() % 101; //value in range [0..100]
printf("%d ", arr[i]);
}
printf("\n");

return 0;
} 11
#define SIZE 5
How to sort an array int arr[SIZE] = {6, 2, 8, 9, 5};

in descending order for (int i = 0; i < SIZE; i++) { //Go from first to last
for (int j = i + 1; j < SIZE; j++) {
/* For each element i, go from next element
Selection Sort Algorithm to the last (values on the right) */

// If value on the right > element i (on the left)


//--> Swap them, since they are not in correct order
if (arr[j] > arr[i]) {
RULE (Simplified Version of Selection Sort): int tmp = arr[i];
arr[i] = arr[j];
Descending Order: Largest > ... > Smallest arr[j] = tmp;
(Left must always > Right) }
}
If a value on the Right > another on the Left }
→ swap them
//Print out result
printf("Sorted array: \n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}

12
How to swap values of two numbers ?
Example: Correct Way:

a = 10; tmp = a; //tmp is 10

b = 5; a = b; //a becomes 5 (correct)


b = tmp; //b becomes 10 (correct)
A third variable tmp is used to temporarily
Wrong Way: store the value of a
a = b; //a becomes 5 (correct)
b = a; //b also become 5
(because a already got new value !)

13
Multi-dimensional array
// Syntax
data_type array_name[size1][size2] … [sizen];

// Examples
int matrix[3][4] = {
{72, 16, 22, 39},
{44, 99, 65, 72},
{84, 6, 100, 51}
};

14
Multi-dimensional array
// Find the largest element in the matrix
int largest = matrix[0][0];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
if (matrix[i][j] > largest) {
largest = matrix[i][j];
}
}
}
printf("Largest element is %d\n", largest);

15
References
1. Fresh2Refresh, C Programming Tutorial, 2020.
2. StudyTonight, C Programming Language Tutorial, 2020.
3. TutorialsPoint, C Programming Tutorial, 2020.
4. Cprogramming.com, C Tutorial, 2020.
5. GeeksforGeeks, Selection Sort Algorithm, 2020.
6. TutorialsPoint, C Standard Library, 2020.

16

You might also like