J.Ruffalo
J.Ruffalo

Reputation: 15

Bizzare numbers appears randomly in output.(C++)

My Code:

#include <iostream>
using namespace std;
int main(){
int a[500];
int value;
for(int i=0;i<500;i++){
    cout<<"Please Enter a value (0-100):";
    cin>>value;
    if (value>=0 && value<=100){
        a[i]=value;
    }
    else if(value<0){
        break;
        }
    }
    for(int i=0;i<5;i++){
        cout<<a[i]<<" ";
    }

}

Output Sample:

Please Enter a value (0-100):10

Please Enter a value (0-100):12

Please Enter a value (0-100):5

Please Enter a value (0-100):-5

10 12 5 0 786432

--------------------------------
Process exited after 7.597 seconds with return value 0
Press any key to continue . . .

Array has values that is not given. I have no idea how they are defined. Please help me about this.

Note: Sorry for my mistakes. I am still a newbie.

Upvotes: 1

Views: 105

Answers (4)

VJAYSLN
VJAYSLN

Reputation: 473

You are declaring a array with size 500, and initialize by using for loop iterations. FYI, In c++, a uninitialized array holds all its value as garbage value...Garbage value is nothing but a random number. You can initialize all array value as zero with using below code.,

int a[500] = {0};

Upvotes: 0

SJN
SJN

Reputation: 385

You can have a index to track number of items entered by the user(noOfItem) and then print upto that number. For example,

 #include <iostream>
    using namespace std;
    int main(){
    int a[500];
    int value;
    int noOfItem=0;
    for(int i=0;i<500;i++){
        cout<<"Please Enter a value (0-100):";
        cin>>value;
        if (value>=0 && value<=100){
            a[i]=value;
            noOfItem++;
        }
        else if(value<0){
            break;
            }
        }
        for(int i=0;i<noOfItem;i++){
            cout<<a[i]<<" ";
        }

    }

Upvotes: 0

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

else if(value<0)

When this condition is true you leave an uninitialized value in a[i] which is what you are seeing. It could just as well do something completely different since reading uninitialized values makes your program have Undefined Behaviour.

Initialize your array with zeroes: int a[500]{};

Upvotes: 4

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

Reading an uninitialized variable is undefined behavior. Your array a is uninitialized. Undefined behavior implies that anything can happen in your program, including printing garbage values.

I advise you to read a good C++ book which covers these basics.

Upvotes: 3

Related Questions