Chap 7

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

Arrays

Introduction
• An array in C is a fixed-size collection of similar data items stored in
contiguous memory locations. It can be used to store the collection of
primitive data types such as int, char, float, etc.
• Some examples where the concept of arrays can be used:
• List of students in a class
• List of test scores of a class of students
• List of temperature recorded every hour a day
• List of employees in an organization. Etc…
• Since an array provides a convenient structure for representing data,
it is classified as one of the data structures in C.
• The ability to use a single name to represent a collection of items and
to refer to an item by specifying the item number enables us to
develop concise and efficient programs.
• Arrays do not only represent single list of items but also table of data
in two, three or more dimensions.
• Accordingly array are categorized as:
• One dimensional array
• Two dimensional array
• Multidimensional array
One Dimensional Array
• A list of items can be given one variable name using only one subscript
and such a variable is called a one dimensional array.
• C Array Declaration
• In C, the array must be declared like any other variable before using it.
• An array can be declared by specifying its name, the type of its elements,
and the size of its dimensions.
• When an array is declared in C, the compiler allocates the memory block
of the specified size to the array name.
• Syntax for declaring array
data_type array_name [size];
• Consider the following array declaration:
1. float height[50];
2. int group[10];
3. char name[10];
• Explain each declaration.
#include <stdio.h>
int main()
{
// declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];

return 0;
}
C Array Initialization
• Initialization in C is the process to assign some initial value to the
variable.
• When the array is declared or allocated memory, the elements of the
array contain some garbage value.
• So, we need to initialize the array to some meaningful value.
• An array can be initialized at either of the following stages:
• At compile time
• At run time
Compile time initialization
• In compile time initialization, there are multiple ways:
1. Array Initialization with Declaration
• In this method, we initialize the array along with its declaration.
• An initializer list is used to initialize multiple elements of the array.
• An initializer list is the list of values enclosed within braces { }
separated by a comma.
data_type array_name [size] = {value1, value2, ... valueN};
2. Array Initialization with Declaration without Size
• If an array is initialized using an initializer list, then declaring the size
of the array can bbe skiped as the compiler can automatically deduce
the size of the array in these cases.
• The size of the array in these cases is equal to the number of
elements present in the initializer list as the compiler can
automatically deduce the size of the array.
data_type array_name[] = {1,2,3,4,5};
• The size of the above arrays is 5 which is automatically deduced by
the compiler.
Run time Initialization
• The array can be initialized after the declaration by assigning the
initial value to each element individually.
• For loop, while loop, or do-while loop can be used to assign the value
to each element of the array.

for (int i = 0; i < N; i++) {


array_name[i] = valuei;
}
// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{
// array initialization using initialier list
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without
// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++)
{
arr2[i] = (float)i * 2.1;
}
return 0;
}
Access Array Elements
• Any element of an array in C can be accessed using the array subscript
operator [ ] and the index value i of the element.
array_name [index];
• One thing to note is that the indexing in the array always starts with
0, i.e., the first element is at index 0 and the last element is at N – 1
where N is the number of elements in the array.
• Exercise questions:
1. C program to evaluate the following using array
total = σ𝑛𝑖 𝑥𝑖2
The values of x1, x2…. Are to be read from terminal.
2. Write a C program to store 10 numbers in an array and find the
largest and smallest.
3. C program to store N numbers in an array and count the total
positive, negative, odd and even numbers.
4. C program to find a key from n numbers using sequential search
and if found, show the position.
5. Insert an element in an array in arbitrary location and display the
array before and after the insertion. (necessary condition should be
checked)
6. Delete an element in an array from arbitrary location and display the
array before and after the deletion. (necessary condition should be
checked)
7. C program to reverse the elements of an array.
2 Dimensional Array
• A two-dimensional array or 2D array in C is the simplest form of the
multidimensional array.
• We can visualize a two-dimensional array as an array of one-
dimensional arrays arranged one over another forming a table with
‘m’ rows and ‘n’ columns where the row number ranges from 0 to (m-
1) and the column number ranges from 0 to (n-1).
• Declaration of Two-Dimensional Array in C
• The basic form of declaring a 2D array with m rows and n columns in C is shown
below.
• Syntax:
data_type array_name[row_size][column_size];
where,
data_type: Type of data to be stored in each element.
array_name: name of the array
m: Number of rows.
n: Number of columns.
• We can declare a two-dimensional integer array say ‘x’ with 10 rows and 20
columns as:
• Example:
int x[10][20];
• Initialization of Two-Dimensional Arrays in C
• The various ways in which a 2D array can be initialized are as follows:
1. Using Initializer List
2. Using Loops
Initialization of 2D array using Initializer List
• We can initialize a 2D array in C by using an initializer list as shown in the example below.
• First Method:
int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}
• The above array has 3 rows and 4 columns. The elements in the braces from left to right are
stored in the table also from left to right.
• The elements will be filled in the array in order: the first 4 elements from the left will be filled
in the first row, the next 4 elements in the second row, and so on.
• Second Method (better):
• int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
• This type of initialization makes use of nested braces.
• Each set of inner braces represents one row.
• In the above example, there is a total of three rows so there are three sets of inner braces.
• The advantage of this method is that it is easier to understand.
• If the values are missing in an initializer, they are automatically set to 0. For
instance, the statement
int x[2][3] = { {1,1},{2}};
Will initialize the first two elements of the first row to one, the first element of
second row to two, and all the other elements to zero.
• Initialization of 2D array using Loops
• We can use any C loop to initialize each member of a 2D array one by one
as shown in the below example.
• Example:
int x[3][4];
for(int i = 0; i < 3; i++){
for(int j = 0; j < 4; j++){
x[i][j] = i + j;
}
}
• This method is useful when the values of each element have some
sequential relation.
• Accessing Elements of Two-Dimensional Arrays in C
• Elements in 2D arrays are accessed using row indexes and column indexes. Each element in a 2D
array can be referred to by:
• Syntax:
array_name[i][j]
where,
i: The row index.
j: The column index.
Example:
x[2][1] = 0;
The above example represents the element present in the third row and second column.
• Note: In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for row index
2 row number is 2+1 = 3. To output all the elements of a Two-Dimensional array we can use
nested for loops. We will require two ‘for‘ loops. One to traverse the rows and another to
traverse columns.
• For printing the whole array, we access each element one by one using loops.
• The order of traversal can be row-major order or column-major order depending upon the
requirement.
Example program to read and print a 2D array
#include <stdio.h>
int main(void)
{
int x[10][10], m, n; //declaration of 2D array and size of the array
printf(“Enter the size of the array:”);
scanf(“%d”,&m,&n);
printf(“Enter the array elements”); // read array elements
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf(“%d", &x[i][j]);
}
}
printf(“Array is:”);// output each array element's value
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf(“%d\t", &x[i][j]);
}
printf(“\n”);
}
return (0);
}
• Exercise question:
1. Suppose there are M number of girls who sales N number of items.
Write a C program to using 2D array to compute and print the
following:
a. Total value of sales by each girl
b. Total value of each item sold
c. Grand total of sales of all the items by all girls
2. Write a C program to add and subtract two matrices.
3. Write a C program to transpose a matrix.
4. Write a C program to multiply two matrix.
5. Write a C program to determine the determinant of a matrix.

You might also like