Sie sind auf Seite 1von 4

1 Chapter 9: Arrays

Declaration
//datatype array-name [size]; int num[5]; declares an array of 5 int num[0] num[1] num[2] num[3] num[4]

Accessing array components:


num[0] = 12; //stores the value 12 in index 0 of num int i = 4; num[i] = 38; //stores 38 in num[4] num[2*i-5] =45; //stores 45 in num[3] num[1] = num[0]; //stores 12 in num[1] num[2] = num[0] + num[1]; num[0] num[1] num[2] num[3] num[4] 12 12 24 45 38

We can also use the following:


const int size=10; int list[size]; But remember that the size must be known before the runtime, i.e. int size; cout<<Enter size; cin>>size; int myList[size]; illegal

Array initialization during declaration


char M[3]={A, B, C}; Declares an array of 3 char , and this is equivalent to saying: char M[ ]={A, B, C}; but , we cant say: char M[]; // we must specify the size M[0] M[1] M[2] A B C

Partial assignment:
int list[5]={1,2}; declares an array of 5 int, and initialize the first 2 elements to 1 and 2, and set the rest elements to zero list[0] 1 list [1] 2 list [2] 0 list [3] 0 list [4] 0 int list[10]={0}; array of 10 int, and all elements equal to zero

What is the different between the following two statements?


int list[4]={2,1}; int list[ ] = {2,1}; The result of the first statement (int list[4]={2,1}; ) is: list[0] list [1] list [2] list [3] 2 1 0 0

But, the result of the second statement (int list[ ] = {2,1};) is: list[0] list [1] 2 1

What is the result of the following statement?


char list[4]={a}; Initialize list[0] to a, and the rest of elements will be space list[0] list [1] list [2] list [3] a

Processing one-dimensional Arrays


Main operations used for arrays #include <iostream> #include<iomanip> using namespace std; int main() { int size=3, index; double list[size], sum=0.0, average; cout<<fixed<<showpoint<<setprecision(2); //1. Initializing an array for ( index=0; index<3; index++) list[index]=0.0; Enter three double values:1.5 2.5 2.0 The values = 1.50 2.50 2.00 Sum =6.00 Average =2.00 Maximum 2.50 found at index:1

//2. Reading data into an array // cin>>list; illegal cout<<"Enter three double values:"; for ( index=0; index<3; index++) cin>>list[index]; cout<<endl;

//3. Printing an array // cout<<list; illegal cout<<"The values = "; for ( index=0; index<3; index++) cout<<list[index]<<" "; cout<<endl;

//4.Finding the sum and average of an array for ( index=0; index<3; index++) sum+=list[index]; average = sum /3.0; cout<<"Sum ="<<sum<<endl <<"Average ="<<average<<endl;

//finding the largest element in the array int maxIndex = 0; int max=list[0]; for ( index=1; index<3; index++) if(list[index]>max) { maxIndex = index; max = list[index]; } cout<<"Maximum "<<max <<" found at index:"<<maxIndex; system("pause"); return 0; }

Das könnte Ihnen auch gefallen