Problem Solving using C Language

0 of 48 lessons complete (0%)

Array, String and Pointer

Array: 1- Dimensional

An array is a sequential collection of variables of same data type which can be accessed using an integer as index, that generally starts from 0. It stores data elements in a continuous memory location. Each element can be individually referenced with its respective index.

1-Dimensional array: It is a linear array that stores elements in a sequential order. Let us try to demonstrate this with an example: Let us say we have to store integers 2, 3, 5, 4, 6, 7. We can store it in an array of integer data type. The way to do it is:

Declaration:

datatype   nameOfTheArray   [sizeOfTheArray];
int Arr[6];

Here Arr is the name of array and 6 is the size. It is necessary to define the size array at compile time.

 To store the above elements in the array:

dataType nameOfTheArray [ ] = {elements of array };
int Arr [ ] = { 2, 3, 5, 4, 6, 7 };

Since, the indexing of an array starts from 0, if the 4th element needs to be accessed, Arr [ 3 ] will give you the value of the 4th element. Similarly, nth element can be accessed by Arr[n-1].

Definition of Array

#include<stdio.h>
int main(void)
{
	int a[5];
	a[0]=9;
	a[1]=10;
	a[2]=14;
	a[3]=76;
	a[4]=34;

	for(int i=0; i<5; i++)
	{
		printf("%d",a[i]);
	}
}


#include<stdio.h>

int main(void)
{
	int a[5]={9,4,22,18,17};
		
	for(int i=0; i<5; i++)
	{
		printf("%d",a[i]);
	}
}

Array using Loop

#include<stdio.h>
int main(void)
{
	int a[5];
	printf("Enter the 5 values: ");
	for(int i=0; i<5; i++)
	{
		scanf("%d",&a[i]);
	}
		for(i=0; i<5; i++)
	{
		printf("\nThe Values are: %d",a[i]);
	}
}

Why array starts from ‘0’

For INT Data Type

5000+0 (Index) * 2(Size of Datatype INT)=5000
5000+1 (Index) * 2(Size of Datatype INT)=5002
5000+2 (Index) * 2(Size of Datatype INT)=5004

For FLOAT Data Type

5000+0 (Index) * 4(Size of Datatype Float)=5000
5000+1 (Index) * 4(Size of Datatype Float)=5004
5000+2 (Index) * 4(Size of Datatype Float)=5008