Reputation:
I am required to write a code for getting 5 positive numbers from the user. Here is my code:
cout << "Write 5 positive numbers:" << endl;
int input;
int num[5];
for(int i = 0; i <= 4; ++i){
cin >> input;
if(input < 0){
cout << "Error" << endl;
}else{
num[i] = input;
}
}
for(int i = 0; i <= 4; ++i){
cout << "Number " << i << " = " << num[i] << endl;
}
The problem is that array should only store positive numbers. When I enter negative num
, it stores it too, and then prints the garbage value. For example, inputs are: 3 -2 1 6 8
The output is:
Number 0 = 3
Number 1 = -1608404014
Number 2 = 1
Number 3 = 6
Number 4 = 8
The code should ask the user enter the input until all 5 buckets in array will be filled only with positive numbers
Upvotes: 2
Views: 5931
Reputation: 3911
because the the input value is negative you don't store it to the element i
but only popup a message then you left this element without input and increment the loop counter and as you guess un-initialized variables have a garbage value:
the solution is to block at the negative value using an embedded wile loop for example until a valid value is inputted:
int input;
int num[5];
for(int i = 0; i <= 4; ++i)
{
cin >> input;
while(input < 0)
{
cout << "Error" << endl;
cout << "num[ " << i << "]: ";
cin >> input;
}
num[i] = input;
}
for( i = 0; i <= 4; ++i){
cout << "Number " << i << " = " << num[i] << endl;
}
Upvotes: 0
Reputation: 29282
Garbage value is printed because if a negative number is entered, that index of the array in your code is skipped.
For your program to keep asking user for the input until the user inputs a positive value, you need a while loop
inside your if block
which displays Error
message if negative value is entered.
Also you need to remove else block
inside for loop
from your code because that's what causing the garbage value to get printed.
Try following code
int main()
{
cout << "Write 5 positive numbers:" << endl;
int input;
int num[5];
for(int i = 0; i <= 4; i++)
{
cin >> input;
if(input < 0)
{
cout << "Error" << endl;
while(input < 0)
{
cin>>input;
}
}
num[i] = input;
}
for(int i = 0; i <= 4; i++){
cout << "Number " << i << " = " << num[i] << endl;
}
return 0;
}
Upvotes: 5