Array in c programming

Why we need array in C++

Suppose you have to calculate average of four numbers. What will you do? You will declare four int variables to store four numbers, then will add all numbers and divide by four. You will get average. Code is given blow.

int num1 = 9;
int num2 = 8;
int num3 = 7;
int num4 = 6;
int sum=num1+num2+num3+num4;
int average = sum / 4;

Now consider a scenario where you need to calculate average of 100 numbers. Will you declare 100 variables of int data type? Obviously it is not convenient to declare 100 variables. Here C++ array helps to overcome this problem. 

What is Array in C/C++ 

Array in C programming is a container to store multiple values of same data type. Rather then declaring 100 variables to store 100 numbers, one int array of size 100 will be used. 

How to declare Array 

Syntax of array declaration is below 
Data-type array-name[size of array]; 

int numbers[100];

This array declaration is equivalent to declaring 100 int variables. 

How to initialize array / insert element in array 

Elements are inserted in array using Subscript Operator ([index]) and similarly this operator is used to access array elements. First element is stored at index 0, second element at index 1 as below 

number[0= 12
number[1= 21
number[2= 9
- 
-
- 
number[99= 10; 

Above code to store element in array is inconvenient as 100 lines of code need to be written. Best way to store elements in array is using loop. In following lines of code, while loop is used and inside while loop, user is prompted to type value from keyboard in each iteration of loop. 
int number[100]; 
int loopCounter = 0
while(loopCounter < 100
 cout<<"Enter num"<<loopCounter+1
 int num; 
 cin>>num; 
 number[loopCounter] = num; 
 loopCounter++
}  

How to read / get element from array 

As you have to calculate average of 100 numbers so again a loop is used and in each iteration of loop, array element is get using Subscript Operator ([index]). A variable sum is used to add all numbers. For this purpose, here we use for loop. 

int counter = 0
int sum = 0
for(counter; counter<100; counter++
   sum = sum + number[counter]; 
int average = sum / 4; 

Different ways to initialize array 

In above example, first array is declared and later array is initialized in loop. However array can be initialized at the time of declaration. Here array size is optional. 
int number[5]={2,6,12,13,9,7}; 
OR 
int number[]={2,6,12,13,9,7}; 

How to calculate size of array / number of elements 

C++ provides a function sizeof(array) which returns number of bytes array reserved in memory. int variable reserves 4 bytes in memory and similarly one element of int array also reserves 4 bytes. We can calculate size of array as below 

int arraySize = 
sizeof(number)/sizeof(number[0]);

Write a C++ Program which take 10 numbers from user and calculate average.

array in c
array in c/c++
Output
array in c output
array in c/c++ output

Comments