I wanted to put this on the forum for anyone who is learning c++. Arrays are special. When dealing with arrays you have to make sure you pay attention to the element index and element value. Sometimes these two get mixed up and blurred together for someone that is learning. I hope this helps in peering into array operations.
C++ has no guard against out of bounds indices. So be careful. Always check to make sure your operations aren't splattering your memory with your elements
Pay special attention to finding the largest and smallest elements, you will then see why you need to keep track of your element index and element value!
Code:
/* main.cpp
*
* Copyright 2012 Bit_Hacker
*
* Array Operations
* ----------------
* 1 - Initializing each element
* 2 - Inputting data into each element
* 3 - Outputting each elements data
* 4 - Finding the largest element
* 5 - Finding the smallest element
*
* --- NUMERICAL OPERATIONS ---
* 6 - Sum of elements
* 7 - Average of elements
*/
#include <iostream>
using namespace std;
int main()
{
// 1) Initializing each element
double sales[10];
int index;
for (index = 0; index < 10; index++)
sales[index] = 0.0;
// 2) Inputting data into each element
for( index = 0; index < 10; index++ )
cin >> sales[index];
// 3) Outputting each elements data
for( index = 0; index < 10; index++ )
cout << sales[index] << " ";
// 4) Finding the largest element
// Assuming maxIndex is the first occurence of the largest element.
int maxIndex = 0;
double largestSale;
for( index = 1; index < 10; index++ )
{
if( sales[maxIndex] < sales[index] )
maxIndex = index;
}
largestSale = sales[maxIndex];
// 5) Finding the smallest element
// Assuming minIndex is the first occurence of the smallest element.
int minIndex = 0;
double smallestSale;
for( index = 1; index < 10; index++ )
{
if( sales[minIndex] > sales[index] )
minIndex = index;
}
smallestSale = sales[minIndex];
/* --- NUMERICAL DATA OPERATIONS BELOW --- */
// 6) Sum of elements
double sum = 0;
for( index = 0; index < 10; index++ )
sum = sum + sales[index];
// 7) Average of elements
double average;
for( index = 0; index < 10; index++ )
{
sum = sum + sales[index];
}
average = sum / 10;
cin.ignore(2);
return 0;
}
-Bit_Hacker