In: Computer Science
Arrays provide the programmer the ability to store a group of related variables in a list that can be accessed via an index. This is often very useful as most programs perform the same series of calculations on every element in the array. To create an array of 10 integers (with predefined values) the following code segment can be utilised:
int valueList[10] = {4,7,1,36,23,67,61,887,12,53};
To step through the array the index '[n]' need to be updated. One method of stepping through the array is via a 'for' loop. Based on the array ‘valueList’ create a small C++ application utilising a 'for' loop that steps through the array and determines the largest number in the list and prints out the index and value. Hint: Consider creating an integer that stores the current largest integer and then compares it with the next indexed value.
Program:
#include<iostream>
using namespace std;
int main()
{
int valueList[10] = {4,7,1,36,23,67,61,887,12,53}; // array variable declaration and assign values
int largestValue,largestValueIndex=0; // variable declaration
largestValue = valueList[0]; // Current largest value is considered as the first element of the arrray
for(int i = 1; i < 10; i++){ // Loop to run for 10 elementd
if(valueList[i] > largestValue){ // if condition to check current value of the array is larger
largestValue = valueList[i]; // update the larger value
largestValueIndex = i; // Update the index value
}
}
cout<<"The largest number in the list is: "<<largestValue<<endl; // print largest number
cout<<"The largest number array index is: "<<largestValueIndex<<endl; // print largest number index
return 0;
}
Output: