Lecture-06 (Array Lecture Notes)
Lecture-06 (Array Lecture Notes)
C Array
Lecture Outline:
Array
One Dimensional Array
Two Dimensional Array
An array is a variable that can store multiple values of the same type. An array is used to store
a collection of data, but it is often more useful to think of an array as a collection of variables
of the same type.
For example, if you want to store 100 integers, you can create an array for it.
int data[100];
dataType arrayName[arraySize];
Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it can
hold 5 floating-point values.
Note that, the size and type of an array cannot be changed once it is declared.
Figure: C Array
You can access elements of an array by indices. Suppose you declared an array mark as above.
The first element is mark[0], the second element is mark[1] and so on.
o Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
o If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]
Initialization of an array:
Here, we haven't specified the size. However, the compiler knows its size is 5 as we are
initializing it with 5 elements.
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
Here's how you can take input from the user and store it in an array element.
Write a C Program to take 5 values from the keyboard and store them in an array then Print
the elements stored in the array.
#include <stdio.h>
int main()
{
int values[5];
printf("Enter 5 integers: ");
for(int i = 0; i < 5; i++)
{
scanf("%d", &values[i]);
}
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0,
float average;
sum += marks[i];
}
average = sum/n;
printf("Average = %f", average);
return 0;
}
#include<stdio.h>
int main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
return 0;
}
In C programming, you can create an array of arrays. These arrays are known as
multidimensional arrays.
For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the
array as a table with 3 rows and each row has 4 columns.
#include <stdio.h>
int main()
{
int STD, SUBJ;
printf("No of Student: ");
scanf("%d", &STD);
int MARKS[STD][SUBJ];
for (int i = 0; i < STD; i++)
{
for (int j = 0; j < SUBJ; j++)
{
printf("MARKS [%d] [%d]: " ,i, j);
scanf("%d", &MARKS[i][j]);
}
}
return 0;
#include <stdio.h>
int main()
{
int arr1[2][3] = {{2,2,2}, {3,3,3}};
int arr2[2][3] = {{1,1,1}, {4,4,4}};
int arr3 [2][3];