Single and Multi Dimensional Arrays
Arrays in C
An array is a collection of data items, all of the same type, accessed using a common name.
-
A one-dimensional array is like a list (vector).
-
A two-dimensional array is like a table (matrix).
-
Arrays can also have more dimensions.
Memory Characteristics
-
Array elements are stored in contiguous (adjacent) memory locations.
-
Elements can be randomly accessed.
-
The address of each element can be calculated using:
-
Base address
-
Size of each data element
-
Declaring Single Dimensional Arrays
Array variables are declared like normal variables, except:
-
The variable name is followed by square brackets
[ ] -
The brackets contain the array dimension (size)
Rules
-
Dimensions must be positive integers or constant expressions.
-
In C99, variables may be used as sizes if they hold a positive value at declaration.
-
Memory is allocated only once when declared.
-
Array size does not change later, even if the variable used changes.
Examples
C99 Variable Length Array Example
Initializing Arrays
Arrays can be initialized at the time of declaration.
-
Use curly braces
{} -
Separate values with commas
-
Initialization may be partial
-
Remaining elements automatically become 0
If the array is fully initialized, the size can be omitted.
The compiler will automatically determine the size.
Examples
✅ Note: Array size can be omitted when initializing a single-dimensional array.
Initializing Specific Elements Using Index
You can assign values to particular elements using their index.
-
Initializes the 11th element to
100 -
Remember: Array indexing starts from 0
Initializing Arrays After Declaration
Arrays can also be initialized later using assignments:
Designated Initializers (C99 Feature)
C99 provides designated initializers, allowing you to initialize specific positions.
-
Elements need not start from index 0
-
Can be mixed with normal initialization
-
Order does not matter
-
Uninitialized elements become 0
Example
Explanation
-
numbers[0] = 1 -
numbers[1] = 2 -
numbers[2] = 3 -
numbers[10] = 10→ 11th element -
Next values:
-
numbers[11] = 11 -
numbers[12] = 12
-
-
numbers[60] = 50 -
numbers[42] = 420 -
All other elements = 0
If array size is not specified, the compiler sets the size based on the largest initialized index.
Using Arrays in C
-
Elements of an array are accessed by specifying the index (offset) of the desired element inside square brackets
[ ]after the array name.
Array Subscripts
-
Array subscripts must be of integer type:
-
int -
long int -
char -
or other integer-compatible types
-
Important Rule About Indexing
⚠ VERY IMPORTANT:
-
Array indices in C start at 0.
-
They go up to size − 1.
Example
For a 5-element array:
Reason
-
The index represents an offset from the beginning of the array.
-
The first element is at the beginning → offset = 0
Common Mistake (Landmine)
⚠ The most common mistake in C arrays is:
-
Forgetting that indexing starts from 0
-
Forgetting that the last index is one less than the array size
Arrays with Loops
-
Arrays are commonly used with loops
-
This helps perform the same operation on:
-
all elements, or
-
part of the array
-
Examples
Updating an Array Element
Accessing an Array Element

Advantages and Disadvantages of Arrays in C
✅ Advantages of Arrays in C
-
Random Access
Elements can be accessed directly using the array index. -
Less Code
A single array can store multiple elements, reducing the number of variables and lines of code. -
Easy Element Access
All elements can be accessed easily using their indices. -
Easy Traversal
Traversing the array becomes simple using one loop. -
Easy Searching and Sorting
Searching and sorting operations are easier since they can be implemented with fewer lines of code.
❌ Disadvantages of Arrays in C
-
Fixed Size
Arrays allow only a fixed number of elements, decided at declaration time.
Unlike a linked list, arrays in C are not dynamic. -
Costly Insertion and Deletion
Adding or removing elements is expensive because:-
Elements must be shifted, or
-
Memory must be reorganized.
-
Sample Programs Using 1-D Arrays
/* Program to calculate the first 20 Fibonacci numbers. */
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
int i, fibonacci[ 20 ];
fibonacci[ 0 ] = 0;
fibonacci[ 1 ] = 1;
for( i = 2; i < 20; i++ )
fibonacci[ i ] = fibonacci[ i - 2 ] + fibonacci[ i - 1 ];
for( i = 0; i < 20; i++ )
printf( "Fibonacci[ %d ] = %f\n", i, fibonacci[ i ] );
} /* End of sample program to calculate Fibonacci numbers */
Program to read n numbers and find the largest using array(University Question)
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
int i, n,a[100],large;
printf("enter...n\n”);
scanf(“%d”,&n);
printf(“Enter the elements\n”);
for( i = 0; i < n; i++ )
scanf(“%d”,&a[i]);
large=a[0];
f or( i = 1; i < n; i++ )
if (a[i]>large) large=a[i]
printf( "Largest Element in the array is %d”,large);
}
#include <stdio.h>
int main()
{
int a[100],b[100],c[100],i,j,k,n,m;
printf("Enter the number of elements in array a:");
scanf("%d",&n);
printf("Enter the array elements in sorted order....\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the number of elements in array b:");
scanf("%d",&m);
printf("Enter the array elements in sorted order....\n");
for(i=0;i<m;i++)
scanf("%d",&b[i]);
for(i=0,j=0,k=0;i<n&&j<m;k++)
{
if(a[i]<b[j])
c[k]=a[i++];
else
c[k]=b[j++];
}
while(i<n) c[k++]=a[i++];
while(j<m) c[k++]=b[j++];
printf("The merged array is...\n");
for(i=0;i<k;i++)
printf("%d\n",c[i]);
}
int main()
{
//Initialize array
int arr[50];
int n,i,j,count;
//Array fr will store frequencies of element
int fr[50];
int visited = -1; // -1 indcated element already considered
printf("Enter n \n");
scanf("%d",&n);
printf("Enter elements\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for( i = 0; i < n; i++){
count = 1;
for(j = i+1; j < n; j++)
{
if(arr[i] == arr[j]){
count++;
//To avoid counting same element again
fr[j] = visited;
}
}
if(fr[i] != visited)
fr[i] = count;
}
//Displays the frequency of each element present in array
printf("---------------------\n");
printf(" Element | Frequency\n");
printf("---------------------\n");
for(int i = 0; i < n; i++){
if(fr[i] != visited){
printf("%5d", arr[i]);
printf(" | ");
printf("%5d\n", fr[i]);
}
}
printf("---------------------\n");
return 0;
}
void main()
{
int arr[50],key,i,n,flag=0;
printf("Enter the number of elements n<=50\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter a key element to search\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(arr[i]==key)
{
flag=1;
break;
}
}
if(flag==1)
printf("%d is found in the list, at position %d\n",key,i+1);
else
printf("%d is not in the list\n",key);
}
main()
{
int arr[51],k,i,n,flag=0;
printf("Enter the number of elements n<50\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter a number to be search\n");
scanf("%d",&k);
for(i=0;i<n;i++)
{
if(arr[i]==k)
{
flag=1;
break;
}
}
if(flag==1)
printf("%d is found in the list, at position %d\n",k,i+1);
else
{printf("%d is not in the list\n",k);
printf("element is inserted at end...\n");
arr[n]=k;
for(i=0;i<=n;i++)
printf("%3d",arr[i]);
}
}
void main()
{
int arr[50],i,j,n,exchng,temp;
printf("Enter the number of elements n<=50\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n-1;i++)
{exchng=0;
for(j=0;j<n-1-i;j++)
{
if (arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
exchng=1;
}
}
if(exchng==0) break;
}
printf("Sorted List...\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
}
void main()
{
int arr[50],i,j,n,exchng,temp;
printf("Enter the number of elements n<=50\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n-1;i++)
{exchng=0;
for(j=0;j<n-1-i;j++)
{
if (arr[j]<arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
exchng=1;
}
}
if(exchng==0) break;
}
printf("Sorted List...\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
}
void main()
{
int arr[50],i,j,n,exchng,temp,c;
printf("Enter the number of elements n<=50\n");
scanf("%d",&n);
printf("Enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n-1;i++)
{exchng=0;
for(j=0;j<n-1-i;j++)
{
if (arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
exchng=1;
}
}
if(exchng==0) break;
}
printf("Sorted List...\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
// finding duplicate elements
for(i=0;i<n;i+=c)
{c=1;
for(j=i+1;j<n;j++)
if(arr[i]==arr[j]) c++;
if(c>1) printf("%d is duplicate...occures %d times\n",arr[i],c);
else printf("%d is unique\n",arr[i]);
}
}
Multidimensional Arrays
Multi-dimensional arrays are declared by providing more than one set of square [ ] brackets after the variable name in the declaration statement.
One dimensional arrays do not require the dimension to be given if the array is to be completely initialized. By analogy, multi-dimensional arrays do not require the first dimension to be given if the array is to be completely initialized. All dimensions after the first must be given in any case.
For two dimensional arrays, the first dimension is commonly considered to be the number of rows, and the second dimension the number of columns.
Two dimensional arrays are considered by C/C++ to be an array of single dimensional arrays.
For example:
-
int numbers[5][6]refers to a single dimensional array of 5 elements, where each element is a single dimensional array of 6 integers. -
By extension,
int numbers[12][5][6]refers to an array of 12 elements, each of which is a two dimensional array.
Another way of looking at this is that C stores two dimensional arrays by rows, with all elements of a row stored together as a single unit. Knowing this can sometimes lead to more efficient programs.
Initialization of Multidimensional Arrays
Multidimensional arrays may be completely initialized by listing all data elements within a single pair of curly { } braces, as with single dimensional arrays.
It is better programming practice to enclose each row within a separate subset of { } braces, to make the program more readable. This is required if any row other than the last is to be partially initialized.
-
When subsets of braces are used, the last item within braces is not followed by a comma.
-
The subsets themselves are separated by commas.
Multidimensional arrays may be partially initialized by not providing complete initialization data. Individual rows of a multidimensional array may be partially initialized, provided that subset braces are used.
Accessing Elements
Individual data items in a multidimensional array are accessed by fully qualifying an array element.
If data is a three dimensional array of floats:
-
data[1][2][5]→ refers to a float -
data[1][2]→ refers to a one-dimensional array of floats -
data[1]→ refers to a two-dimensional array of floats
These concepts relate to memory-management issues.
Example: Declaring and Initializing 2D Arrays
The two-dimensional array can be defined as an array of arrays.
A 2D array is organized as a matrix (rows and columns).
Declaration
In a 1D array, we don't need to specify the size if declaration and initialization are done together.
However, this does not work for 2D arrays — we must define at least the second dimension.
Initialization
Invalid Initializations
Accessing Elements
Elements are accessed using both row and column index.
(Indexing starts from 0.)
Let’s consider a 2D array abc[5][4].
The conceptual memory representation is shown below.
The difference between the orders lies in which elements of an array are contiguous in memory. In row-major order, the consecutive elements of a row reside next to each other, whereas the same holds true for consecutive elements of a column in column-major order.
Sample Program Using 2-D Arrays
void main()
{
int A[50][50],B[50][50],rsum;
int r,c,m,n;
printf("Enter the size of the matrix nof of rows,columns\n");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrix A row by row\n");
for(r=0;r<m;r++)
for(c=0;c<n;c++)
scanf("%d",&A[r][c]);
//computing transpose
for(r=0;r<m;r++)
{rsum=0;
for(c=0;c<n;c++)
rsum=rsum+A[r][c];
printf("Sum of elements in row %d=%d\n",r,rsum);
}
}
#include <stdio.h>
main()
{
int A[50][50],B[50][50];
int r,c,m,n;
printf("Enter the size of the matrix nof of rows,columns\n");
scanf("%d%d",&m,&n);
printf("Enter the elements of matrix A row by row\n");
for(r=0;r<m;r++)
for(c=0;c<n;c++)
scanf("%d",&A[r][c]);
//computing transpose
for(r=0;r<m;r++)
for(c=0;c<n;c++)
B[c][r]=A[r][c];
printf("The transpose of A is \n");
for(r=0;r<n;r++)
{
for(c=0;c<m;c++)
printf("%3d",B[r][c]);
printf("\n");
}
}
Adding two matrix sum=a+b ( university question)
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };
int b[ 2 ][ 3 ] = { { 1, 2, 3 }, { 3, 2, 1 } };
int sum[ 2 ][ 3 ], row, column;
/* First the addition */
for( row = 0; row < 2; row++ )
for( column = 0; column < 3; column++ )
sum[ row ][ column ] =a[ row ][ column ] + b[ row ][ column ];
/* Then print the results */
printf( "The sum is: \n\n" );
for( row = 0; row < 2; row++ ) {
for( column = 0; column < 3; column++ )
printf( "\t%d", sum[ row ][ column ] );
printf( '\n' ); /* at end of each row */
}
return 0;
}
Multiply two matrix C=A*B ( university question)
#include<stdio.h>
int main(void)
{
int i,j,k,m,n,p,q,tot;
int A[30][30], B[30][30], C[30][30];
printf(" Please insert the number of rows and columns for first matrix \n ");
scanf("%d%d", &m, &n);
printf(" Insert your matrix elements : \n ");
for (i= 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &A[i][j]);
printf("Please insert the number of rows and columns for second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf(" Your given matrices cannot be multiplied with each other. \n ");
else
{
printf(" Insert your elements for second matrix \n ");
for (i= 0; i< p; i++)
for (j= 0; j< q; j++)
scanf("%d", &B[i][j] );
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
for (k = 0; k < p; k++) {
tot = tot + A[i][k] * B[k][j];
}
C[i][j] = tot;
}
}
printf(" The result of matrix multiplication or product of the matrices is: \n ");
for (i = 0; i < m; i++) {
for (j = 0;j < q; j++)
printf("%5d", C[i][j] );
printf(" \n ");
}
}
return 0;
}
Check whether the given matrix is diagonal ( university question)
Write a C program to check whether a matrix is symmetric or skew symmetric
#define MAX_SIZE 10
int main() {
int A[MAX_SIZE][MAX_SIZE];
int i, j, rows, cols;
int symmetric = 1, skewsymmetric = 1;
printf("Enter the number of rows and columns of the square matrix: ");
scanf("%d", &rows);
cols = rows;
printf("Enter the elements of the matrix:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
scanf("%d", &A[i][j]);
}
}
// Check for symmetric matrix
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
if (A[i][j] != A[j][i]) {
symmetric = 0;
break;
}
}
if (symmetric == 0) {
break;
}
}
// Check for skew-symmetric matrix
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
if (A[i][j] != -A[j][i]) {
skewsymmetric = 0;
break;
}
}
if (skewsymmetric == 0) {
break;
}
}
if (symmetric == 1) {
printf("The matrix is symmetric.\n");
} else if (skewsymmetric == 1) {
printf("The matrix is skew-symmetric.\n");
} else {
printf("The matrix is neither symmetric nor skew-symmetric.\n");
}
return 0;
}
2.Find the average of list of numbers.
3.Find the maximum and minimum values from an array of integers.
4.Swap the k th and k+1 th element in an array. Read k.
5.Find the binary equivalent of a number using array.
6.Find similar elements in an array and compute the number of times they occur.
7. Separate odd and even integers in separate arrays from a given array.
8.Find the intersection of two set of numbers.
9.Rearrange n numbers in an array in reverse order.(selection sort)
10.Sort the numbers stored in array in ascending order.(bubble sort)
11.Arrange numbers in an array in such a way that the array will have odd numbers followed by the even numbers.
12.Find the frequency of digits in a set of numbers.
13.Remove duplicate elements from an array.( Hint: sort the array)
14.Merge two sorted arrays into another array in sorted order.
15.Find the mean,variance,median and standard deviation of set of integer data.
16.Read list of numbers and print prime numbers from the list.
17.List of internal marks of a subject is stored in an array ( marks out of 50).
a.number of passed students ( need 50 percentage or more)
b.number of failed students
c.number of students having 60 percentage or more
d.maximum , minimum and average mark in the subject.
( do it as a menu driven program..)
18.Search a key element in a given array ( linear search)
19.Search a key element in the give sorted array ( binary search)
20.Generate Fibonacci numbers up to n and store it in an array.Read and print prime numbers from it.
21.Given two vectors V1 and V2 in R3 . Find their sum (V1+V2)and dot product V1.V2.
22.Find the length of a given vector in Rn.
23.Find the second largest element in an unsorted array.
24.Find the kth largest element in a list.
a)addition b)subtraction c)multiplication
3.Find transpose of a given matrix.(uq)
4.Find the trace of a matrix.( sum of the diagonal element)
5.Find sum of each rows and columns of a matrix.
7.Given two square matrices A and B of same order.
Check whether AB equal BA.
8.Check whether the given matrix is symmetric.(university question)
9.Check whether a given matrix is an identity matrix.
10. Calculate determinant of a 3 x 3 matrix.
11.Find the saddle points in a matrix.
12.Check for upper triangular/lower triangular matrix.
13. marks(out of 150) of 5 students in 3 subjects are stored in matrix form.Find
a)top marks in each subject
b)Number of failed students in each subject
c)average mark in each subject.
d)Number of supply subjects each students have.
14.Print all prime numbers from a matrix.(university question)
15.Write a C program to accept a two dimensional matrix and display the row sum, column sum and diagonal sum of elements.(university question)




Comments
Post a Comment