1

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.

J.Ruffalo
  • 15
  • 5

4 Answers4

4

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]{};

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
3

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.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
0

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]<<" ";
        }

    }
SJN
  • 377
  • 2
  • 8
  • 18
0

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};

VJAYSLN
  • 473
  • 4
  • 12