Lab09 1 D Arrays
Transcript of Lab09 1 D Arrays
-
8/10/2019 Lab09 1 D Arrays
1/3
ICS 103: Computer Programming in C
Lab #9: 1-D Arrays (Part1)
Objective:
Learn how to declare, initialize and use one-dimensional arrays.Background: Arrays are collections of elements all of the same type. The elements gointo memory, one after the other.
If an array is declared as:int values[ 5 ];
then the array valueshas 5 elements; they are values[0], values[],values[!], values["], and values[#].
$otice that the inde% &su'script( starts from 0 toArraySize - 1.
The elements of the array 'ehave li)e normal varia'les. In order to use anyelement of the array, *e need to use the array name plus the inde% value.
Initialializing an Array +ou can initialie an array *hen you declare it using the initialiation list:int scores [ 5 ] = { 10, 20, -5, 40, 5 };
+ou cannot assign multiple values to an array name or to anarray element:
int scores[ 5 ];scores = { 10, 20, 30, 40, 50 }; // ERRORscores[5]={1, 32, -3, 5, !}; // ERROR
-onsider the follo*ing initialiation statement:int "[#]= { 2, -#, $};
the initialiation *ill create an array of elements; the /rst " elements *ill 'eassigned the values !, , and 1 in order i.e. %[0]2!, %[]2, and %[!]21.3ach of the remaining " elements of the array *hich are %["], %[#], and %[5]*ill 'e assigned a value of 0.
The follo*ing declaration *ill create a compilation error 'ecause of notspecifying the array sie:%ou&le "[ ]; // ERROR'( )O* + (OR+ .+R+E*ER E+R+*'O)
but the following declaration and initialization%ou&le "[] ={ 3,$,!,11};
is accepted because in this case the compiler will count the number of elements in the list and makethe array size equal to that number which is 4 in the above example.
The following statementint [4]={4,#,$,!,}; //coilation error
Will lead to a compilation error because the number of initizer values (! is more that the size of the
array (4!.
"
-
8/10/2019 Lab09 1 D Arrays
2/3
Assigning values to the elements of an array:After the array is declared, *e can assign values to individual elements assho*n 'elo*:int arra[ 5 ];arra[ 0 ] = 10;arra[ 1 ] = 20;arra[ 2 ] = 30;arra[ 3 ] = 40;arra[ 4 ] = 50;
and *e can use these elements 4ust as *e *ould an ordinary varia'le:rint 6 7*8e t8ir% eleent is 9%:n7, arra[ 2 ] ;
e can also read values from the user or a /le and assign them to the arrayany of the array elements.The 'ig advantage of using arrays is the use of loops to process theirelements. +ou could imagine ho* silly it *ould 'e to *rite a program to /ll allthe elements of the array sho*n 'elo*:int tens[10000];tens[0] = 10;tens[1] = 20;// < < < $ ore assinents <