ARRAY in C

Array in C
Array in C
  • It is a collection of multiple data of the same data type. for example, we can have an array of int type data or float type data
  • An array in C has a static memory allocation i.e memory size once allocated for an array cannot be changed. It’s Index starts from 0 to n number of index

The syntax for data_type in C Programming Language

Syntax:
data_type array_name[array_size];
  • Remember, An array in C can have data of the same type only i.e. all elements of an array have to be of the same type only
  • We cannot have an array of a combination of different data types
  • We need to note two very important points about an array

1. The starting index i.e. index of the first element of an array is always zero

2. The index of the last element is n-1, where n is the size of the array

  • An array has static memory allocation i.e. memory size once allocated for an array cannot be changed
  • The memory allocated to an array also depends on the data type i.e. the space required for each element
  • For e.g.: int a[10]; will require 20-byte memory locations, as each integer type data requires 2-byte memory locations; while float x[20] will require 80-byte memory locations, as each float type data requires 4 bytes of memory
  • To access an element of an array we have to use the array selection operator i.e. []
  • For e.g. if we want to access the 3rd element of an array named ‘a’, then we need to access it as a[2]
  • Remember 3rd element will be indexed 2, as the index of the first element is 0
  • Hence to access an element we need to use the array name or identifier and write the index number in square brackets
  • Another e.g. to access the 9th element of an array ‘x’, we need to write x[8]

1.Display the program to print the sum of n element

#include<stdio.h>
#include<conio.h>
void main()
{
int n,a[20],sum=0;
printf("enter the number of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
printf("the sum of array elements is=%d",sum);   
}

OUTPUT:

enter the number of elements:5 
1 
3 
2
4 
5 
the sum of array elements is=15
Translate »