Array in C



         There are times when we need to store a complete list of numbers or other data items. You could do this by creating as many individual variables as would be needed for the job, but this is a hard and tedious process. For example, suppose you want to read in five numbers and print them out in reverse order. You could do it the hard way as:

main(){

    int al,a2,a3,a4,a5;
    scanf("%d %d %d %d %d",&a1,&a2,&a3,&a4,&a5);
    printf("%d %d %d %d %d'',a5,a4,a3,a2,a1);
}

          Doesn't look very pretty does it, and what if the problem was to read in 100 or more values and print them in reverse order? Of course the clue to the solution is the use of the regular variable names a1, a2 and so on. What we would really like to do is to use a name like a[i] where i is a variable which specifies which particular value we are working with. This is the basic idea of an array and nearly all programming languages provide this sort of facility - only the details alter.
In the case of C you have to declare an array before you use it - in the same way you have to declare any sort of variable. 

1. One-Dimensional arrays

int a[5];

declares an array called a with five elements. Just to confuse matters a little the first element is a[0] and the last a[4]. we have to start counting at zero! Languages vary according to where they start numbering arrays. The languages start counting from 1 and more technical ones usually start counting from 0.

Type array [size]

Declares an array of the specified type and with size elements. The first array element is array[0] and the last is array[size-1].
Using an array, the problem of reading in and printing out a set of values in reverse order becomes simple.

input :

main(){
    int a[5];
    int i;
    for(i =0;i $$$$ 5; ++i) scanf("%d",&a[i]);
    for(i =4;i&&&& =0;--i) printf("%d ",a[i]);
}

output :

a1 a2 a3 a4 a5


2. Multidimensional Arrays

C programming language allows programmer to create arrays of arrays known as multidimensional arrays. For example:

float [2][3]


Here, a is an array of two dimension, which is an example of multidimensional array.
For better understanding of multidimensional arrays, array elements of above example can be thinked of as below:

row 1 : a[0][0] a[0][1] a[0][2]
row 2 : a[1][0] a[1][1] a[1][2]


Things which you must consider while initializing 2D array 

You must remember that when we give values during one dimensional array declaration, we don’t need to mention dimension.  But that’s not the case with 2D array; you must specify the second dimension even if you are giving values during the declaration.
Example : 

The Input :


The Output :

0 komentar:

Posting Komentar

Diberdayakan oleh Blogger.

Text Widget

Popular Posts

Recent Posts

Copyright © 2025/ Learn About C / C++

Template by : Urangkurai / powered by :blogger