miércoles, 26 de octubre de 2011

Arrays en C

In constructing our building, we have identified each brick(variable) by name. That process is fine for a small number of brick, but what happens when we want to construct something larger? We would like to point to a stack of bricks and say: "That's for the left wall. That's brick 1,brick 2, brick 3,...".
Arrays allow us to do something similar with variables. An array is a set of consecutive memory locations used to store data. Each item in the array is called an element. The number of elements in an array is called the dimension of the array. A typical array declaration is:
/*List of data to be sorted and averaged.*/
int datalist[3];
The above example declares datalist to be an array of three elements. datalist[0], datalist[1] and datalist[2] are separate variables. To reference an element of an array, you use a number called the index- the number inside the square brackets([]). C is a funny language that likes to start counting. So, our three elements are numbered to 2.
In this example we compute the total and average of five numbers.
using namespace std;
float data[5];/* data to average and total*/
float total;/*the total of the data items*/
float average;/*average of the items*/
int main()
{
    data[0]=34.0;
    data[1]=27.0;
    data[2]=45.0;
    data[3]=82.0;
    data[4]=22.0;
    total=data[0]+data[1]+data[2]+data[3]+data[4];
    average=total/5.0;
    printf("Total %f Average %f \n", total, average);
    return 0;           
}
and the program outputs:

1 comentario:

  1. Your page is so fantastic! You sure do know how to keep your audience entertained. I am so glad that I took the time to look at this blog, because let me tell you.

    ResponderEliminar