C Programming Arrays
C Programming 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 (will be discussed in next chapter)
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.
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
#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;
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
int testArray[10];
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as
table with 3 row and each row has 4 column.
You can think this example as: Each 2 elements have 4 elements, which makes 8 elements and each
8 elements can have 3 elements. Hence, the total number of elements is 24.
Above code are three different ways to initialize a two dimensional arrays.
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
};
The user is asked to enter elements of the matrix (of order r*c).
Then, the program computes the transpose of the matrix and displays it on the screen.
Example: Program to Find Transpose of a Matrix
#include <stdio.h>
int main()
{
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);
// Storing elements of the matrix
printf("\nEnter elements of matrix:\n");
for(i=0; i<r; ++i)
for(j=0; j<c; ++j)
{
printf("Enter element a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}
return 0;
}