Lecture 5 Arrays
Lecture 5 Arrays
Valid indexes:
values[0]=5;
values[9]=7;
Invalid indexes:
values[10]=3;
values[-1]=6;
In memory: elements of an array are stored
at consecutive locations
Arrays - Example
#include <iostream> Using symbolic
Using namespace std; constants for array
size makes program
int main () more general
{
int values[6];
int index, i;
for ( index = 0; index < 6; index++ ) {
cout<<“Enter value of element”<<index<<endl;
cin>>values[index];
}
for ( index = 0; index < 6; index++ )
cout<< “values[“<<index<<“]=“<< values[index]<<endl;
return 0; Typical loop for
} processing all
elements of an array
What goes wrong if an index goes out of range ?
#include <iostream>
using namespace std;
int main (){
int NA, NB;
cout<<"Enter NA and NB: "<<endl;
cin>>NA>>NB;
int a[NA],b[NB];
int index;
for ( index = 0; index < NA+2; ++index ){
a[index]=index;}
for ( index = 0; index < NA+2; ++index ){
cout<<"a ["<<index<<"]= "<<a[index]<<endl;}
for ( index = 0; index < NB; index++ ){
b[index]=10+index;}
for ( index = 0; index < NB+2; ++index ){
cout<<"b ["<<index<<"] ="<< b[index]<<endl;}
return 0;
}
Exercise: Fibonacci numbers
// Program to generate the first 15 Fibonacci numbers
#include <iostream>
using namespace std;
int main (){
int size; cout<< "Please give the Fibonacci range: ";
cin>>size;
int Fibonacci[size], i;
Fibonacci[0] = 0; // by definition
Fibonacci[1] = 1;
for ( i = 2; i < size; i++ )
Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];
for ( i = 0; i < size; i++ )
cout<< "Fibonacci["<<i<<"]="<<Fibonacci[i]<<endl;
return 0;
}
Exercise: Prime numbers
An improved method for generating prime numbers involves the notion that a number
p is prime if it is not evenly divisible by any other prime number
2 3 5 7 11
0 1 2 3 4
primeIndex
Exercise: Prime numbers
a special case of character arrays: the character string type =>in a later chapter
Exercise:
1. Develop a program that stores your Name and ID using two
different arrays and displays your information at the end.