Check The Programming Section
To take input elements of the array we needs to traverse that array by using the index of each item with the subscript operator [ ]. The following steps needs to follow:
Initialize the index variable with the lower bound of the array 0
We need a loop to traverse an array and loop will execute till the upper bound -1 times. The upper bound of the array is size - 1.
size is the number of items of the array
Array with lower and upper bound
The required source code to declare and traverse an array by following the above listed steps is (edit and try):
#include<iostream>
using namespace std;
int main(){
int num[10]; //array is declared with size 10
//for loop to traverse the array elements to take input
for(int index = 0; index<10; index+=1){
cout<<"Enter a number at index "<<index<<":";
cin>>num[index];
}
cout<<"The item of the array :"<<endl;
//for loop to traverse the array elements to display the array items
for(int index = 0; index<10; index+=1){
cout<<num[index]<<" ";
}
}
The statement int num[10]; declares an array with 10 (size of the array) elements
Inside the for loop int index = 0; is initialized the index to the lower bound of the array
Before entering to the loop the condition index<10; needs to be true. This loop will execute 10 times (0 to 9 (size - 1)) equal to the size of the array
Inside the loop, cout with insertion operator << is used to display a message, to prompt an user
cin with extraction operator >> is used to take the input by passing the index with [ ]
The second for loop is used to display the array items and similar steps is followed, like input
To display each item of the array an index with [ ] needs to be suffix the array name like num[index]
The first 10 lines prompts the user to give input and all the item gets displayed in a line with space separated.
Enter a number at index 0:4
Enter a number at index 1:6
Enter a number at index 2:7
Enter a number at index 3:9
Enter a number at index 4:0
Enter a number at index 5:2
Enter a number at index 6:5
Enter a number at index 7:6
Enter a number at index 8:7
Enter a number at index 9:8
The item of the array :
4 6 7 9 0 2 5 6 7 8
#include<iostream>
using namespace std;
int main(){
int num[10]; //array is declared with size 10
//for loop to traverse the array elements
for(int index = 0; index<10; index+=1){
cout<<"Enter a number at index "<<index<<":";
cin>>num[index];
}
int max = num[0];
int loc = 0;
for(int index = 1; index<10; index+=1){
if(max<num[index]){
max = num[index];
loc = index;
}
}
cout<<"The maximum of all items is "<<max<<" and location is "<<loc;
}