Arrayes
Arrayes
ARRAYS
INTRODUCTION
Suppose we need to find out the average of 100 integer numbers entered by user.
In C,for this we have two ways to do this.
Ø Define 100 variables with int data type and then perform 100 scanf()
operations to store the entered values in the variables and then at last
calculate the average of them.
Ø Have a single integer array to store all the values, loop the array to store all
the entered values in array and later calculate the average.
Which solution is better according to you? Obviously the second solution, it is
convenient to store same data types in one single variable and later access them
using array index.
Definition
An array is defined as finite ordered collection of homogenous data, stored in
contiguous memory locations
Here the words,
Declaration:
int num[35]; /* An integer array of 35 elements */ Similarly an array can be of any
char ch[10]; /* An array of characters for 10 elements */ data type such
as double, float, short etc.
Initialization of an array
Program:01
#include <stdio.h> Output:
int main() Enter number 1
{ 10
int avg = 0; Enter number 2
int sum =0; 10
int x=0; Enter number 3
int num[4]; /* Array- declaration – length 4*/ 20
for (x=0; x<4;x++) Enter number 4
{ 40
printf("Enter number %d \n", (x+1)); Average of entered
scanf("%d", &num[x]); number is: 20
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}
avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
DECLARATION:
int abc[2][2] = {1, 2, 3 ,4 } /* Valid declaration*/ Explanation
Things that you must con
int abc[][2] = {1, 2, 3 ,4 } /* Valid declaration*/ We already know, when we initialize a
normal array (or you can say one dimensional
int abc[][] = {1, 2, 3 ,4 } /* Invalid because you must specify array) during declaration, we need not to
second dimension*/
specify the size of it. However that’s not the
case with 2D array, you must always specify
int abc[2][] = {1, 2, 3 ,4 }/* Invalid declaration – because you
the second dimension even if you are
must specify second dimension*/
specifying elements during the declaration.
Let’s understand this with the help of few
examples –
Initialization of 2D Array
There are two ways to initialize a two Dimensional arrays during declaration
}
} To store the elements entered by user we are using
return 0; two for loops, one of them is a nested loop. The
} outer loop runs from 0 to the (first subscript -1) and
the inner for loops runs from 0 to the (second
subscript -1). This way the the order in which user
enters the elements would be abc[0][0], abc[0][1],
abc[0][2]…so on.