Lecture 7
Lecture 7
Eng.Fadia M Hasen
Arrays
An array is a group of variables (called
elements or components) containing
values that all have the same type.
Declaring and Creating Arrays
In C++, we have to declare the array like any other variable before using it. We can declare an
array by specifying its name, the type of its elements, and the size of its dimensions. When we
declare an array in C++.
In this method, we initialize the array along with its declaration. We use an initializer list to
initialize multiple elements of the array. An initializer list is the list of values enclosed within
braces { } separated b a comma
We initialize the array after the declaration by assigning the initial value to each element individually. We
can use for loop, while loop, or do-while loop to assign the value to each element of the array.
array_name [index];
One thing to note is that the indexing in the array always starts with 0, i.e., the first element is
at index 0 and the last element is at N – 1 where N is the number of elements in the array
C++ Array Traversal
Traversal is the process in which we visit every element of the data structure. For C array
traversal, we use loops to iterate through each element of the array
Array Traversal using for Loop
#include<iostream>
int main()
{ int i,first_arry[6];
for (i=0;i<6;i++)
cin>> first_arry[i] ;
cout<<"the Content of array is :\n";
for (i=0;i<6;i++)
cout<< first_arry[i]<<"\t";
}
Example
program to sum array items
#include<iostream>
int main()
{
{ int i,array1[5],sum=0;
for (i=0;i<5;i++)
cin>> array1[i] ;
for (i=0;i<5;i++)
sum=sum+array1[i];
cout<< "sum of array item="<<sum;}
}
Example
Maximum item in array
#include<iostream>
int main()
{
{ int i,array1[7],max;
for (i=0;i<7;i++)
cin>> array1[i] ;
max=array1[0];
for (i=0;i<7;i++)
if (array1[i] > max )
max=array1[i];
cout<< "max number in array1 is="<<max;}}
Exercise