Arrays
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value
An array is a variable that can store multiple values. For example, if you want
to store 100 integers, you can create an array for it.
int data[100];
Example:
###include<stdio.h>
void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d \t",arr[i]);
}
}
Types of Array in C
There are two types of arrays based on the number of dimensions it has. They
are as follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays
1. One Dimensional Array in C
The One-dimensional arrays, also known as 1-D arrays in C are those arrays
that have only one dimension.
Syntax of 1D Array in C
array_name [size];
Example:
#include <stdio.h>
main()
{
int values[5];
}
2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one
dimension. Some of the popular multidimensional arrays are 2D arrays and 3D
arrays.
A. Two-Dimensional Array
B. Three-Dimensional Array
A. Two-Dimensional Array
Syntax of 2D Array in C:
array_name[size1] [size2];
Here,
• size1: Size of the first dimension.
• size2: Size of the second dimension.
Example of 2D Array in C
// C Program to illustrate 2d array
#include <stdio.h>
main()
{
// declaring and initializing 2d array
int arr[2][3] = { 10, 20, 30, 40, 50, 60 };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
Output
10 20 30
40 50 60
B. Three-Dimensional Array in C
Syntax of 3D Array:
#include <stdio.h>
main()
{
// 3D array declaration
int arr[2][2][2] = { 10, 20, 30, 40, 50, 60, 70, 80};
// printing elements
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
#include <stdio.h>
float calculateSum(float num[]);
main()
{
float result;
float num[] = {23.4, 55, 22.6, 3, 40.5, 18};
result = calculateSum(num);
Output
Result = 162.50
Array of Characters
An array of characters in C is used to store a sequence of characters, such as a string. It is
essentially a collection of char data types.
Syntax
char arrayName[size];
Example