David Smyth
David Smyth

Reputation: 25

Simple program to compare an array running but giving incorrect result

Simple code to compare a log of hours ran every Sunday recording the number of improvements from one week to the next.

I have tried printing the array to see if its correct but have gotten random unrelated numbers printed out

// Program that takes array representing hours ran each saturday sequentially. Record number of days where more was ran then previous days.

#include <iostream>
#include <iomanip>

using namespace std;

int main(){

    int nr_progress;
    int times [5];
    cout << "Enter the track times you set for the last 5 Sundays: "<< flush;

    for(int i=0; i<5; i++){

       cin >> times[0];

        }
    for(int l=1; l<4; l++){
        if(times[l] > times [l-1]){
            nr_progress += 1;
        }
    }

std :: cout << "The number of progress days is equal to: " << nr_progress << endl;

}

For inputs 7 9 13 12 8. I would expect a output as 2 but the program is outputting 1.

Upvotes: 1

Views: 66

Answers (1)

ruohola
ruohola

Reputation: 24038

You have a simple typo in your first for-loop:

for(int i=0; i<5; i++){
    cin >> times[0];
}

Should be:

for(int i=0; i<5; i++){
    cin >> times[i];
}

You are only initializing the first value in your array. Then when you try printing the values, you are just accessing uninitialized memory, that's why you're seeing some random garbage values.

Edit:

You also forgot to initalize nr_progress, with:

int nr_progress = 0;

always always initialize your variables, there's hardly every a reason to just declare one.

Upvotes: 1

Related Questions