Chapter 7: Arrays and Types of arrays
Arrays:-
In C, an array is a collection of elements of the same data type, stored in continuous memory locations. An index is used to access the elements of an array. Here is the basic syntax for defining an array and an example:
Syntax:-
data_type array_name[array_size];
a) data_type:-
It
defines the data type of the elements in the array.b) array_name:-
It defines the name of the array.c) array_size:-
It defines the number of elements in the array.
Types of Array:-
There are 2 types of Array
1. 1 dimensional Array(1-D array)
2. 2 dimensional array (2-D array)
1-D Array:-
These are the serial or sequential representations of data with a single row and multiple columns. It is also known as a linear array.
Example:-
int a[5];
=> a[0]: Lower Bound of Array
=> a[5]: Upper Bound of Array
int a[5]={9,11,8,17,3};
Array elements:
Element at index 0: 9
Element at index 1: 11
Element at index 2: 8
Element at index 3: 17
Element at index 4: 3
- => int numbers[5] defines a 1D array named numbers with a size of 5.
- => {9, 11, 8, 17, 3} initializes the array with the specified values.
How to input and print 1-D array elements:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i;
for(i=0;i<=5;i++)
{
printf("Enter array element");
scanf("%d",&a[i]);
}
for(i=0;i<=5;i++)
{
printf("%d\n",a[i]);
}
getch();
}
2-D Array:- A two-dimensional (2D) array is a collection of elements arranged in rows and columns. Each element is accessed through the use of two indices, one for the row and one for the column. Here's an example of a 2D array in C:
Example:-
//-- Declare and initialize a 2D array of integers
int a[2][2] = {
{1, 2},
{3, 4}
};
Element at row 0, column 0: 1
Element at row 0, column 1: 2
Element at row 1, column 1: 3
Element at row 1, column 2: 4
=>Enter and get the 2D array elements:-
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][2],i,j;
printf("Enter the 2-D array elements\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("output of 2-D array elements is\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d",a[i][j]);
}
}
getch();
}