So I have this but I'm not really sure of how to print the smallest element of array a , print the sum of all the elements in array a , and print the average of all the elements in array a. Help please.

Is this how to print out smallest element? a[1] = i+1;
I'm new to C++, so I need a little help with this.

#include <cstdlib>
// rand()
// srand()
// time()

#include <iostream>
using std::cout;
using std::endl;


int main() {
    int a[100];

    srand(time(NULL));

    for (int i=0; i<100; i++)
        a[i] = rand()%1000;

Q1. (one solution)

int lowest = a[0];
for (int i = 1; i < 100; i++){
    if (a[i] < lowest){
        lowest = a[i];
    }
}

Edited 2 Years Ago by Suzie999

Can you check if I have the first 4 of the todo problems correct?
I'm not sure if I did it right.

#include <time.h> 
#include <cstdlib>
// rand()
// srand()
// time()

#include <iostream>
using std::cout;
using std::endl;


int main() {
    // declare an array with 100 elements
    int a[100];

    // seed the random number generator
    srand(time(NULL));

    // initialize the array with 100 random values, each between 0 and 999,
    // inclusive
    for (int i = 0; i<100; i++)
        a[i] = rand() % 1000;

    // TODO:
    // - print out all the elements of array `a`, with spaces inbetween

    for (int i = 0; i < 100; i++)
        cout << a[i] << " "; 

    // - print the smallest element of array `a`

    int smallest = a[0];

    for (int i = 0; i < 100; i++){
        if (a[i] < smallest) {
            smallest = a[i];
        }
    }
    cout << smallest;
    // - print the largest element of array `a`

    int largest = a[100];

    for (int i = 0; i < 100; i++) {
        if (a[i] < largest) {
            largest = a[i];
        }
    }
    cout << largest;

    // - print the sum of all the elements in array `a`
    int i; 
    int count=0;

    for (i = 0; i < 100; i++){
        count += a[i]; 
    }

    // - print the average of all the elements in array `a`

    system("pause"); 
    return 0;
}

Edited 2 Years Ago by DS9596: added more

for the average you would just divide count by the array size, so in this case it would be

insert after line 59

int average = count/100;
cout << average; //prints the average of the array

At line 42 you have: int largest = a[100]; which is out of bounds for the array.
Set largest to a[0]
At line 45, you're checking the wrong condition, you need to check whether the value is greater: if (a[i] > largest)
Seeing as smallest and largest are (now) initially set as having the value of a[0] you can start the loop iteration from element 1: for (int i = 1; i < 100; i++)

Some food for thought: you could easily combine getting the largest, smallest and total sum inside a single loop.

This article has been dead for over six months. Start a new discussion instead.