Beginner Array Question

Topic is array. User enters in 100 numbers, but If they type in zero I want the display to be Try again and make the user enter the value again. My code is not functioning in this case. May anyone help me give me an idea of how to solve this issue?

1
2
3
4
5
6
7
8
9
  int list[100];
	int i;

	for (i=0; i<100;i++)
	{
		cin>>list[i];
	if (list[i]=0)
		cout<<"Try Again";
	}
You want a do while loop inside of the for loop here.
You want:
1
2
3
4
5
6
7
8
int list[100];

for (int i = 0; i < 100; i++)
{
      cin >> list[i];
      if (list[i] == 0)    // need two == 
            cout << "Try Again";
}


Your code is saying if (set list[i] to 0). Though, its late and not sure my code is going to do what you want as I didn't test it.
Thanks for the reply guys. BHSSpecter, I did fix that method but i'm still conflicting with the same problem. Its's not outputting try again.

and ispil, I was thinking about the do while loop but how do I using arrays?
How about this:
1
2
3
4
5
6
7
8
9
10
int list[100];
for	(int i = 0; i < 100; i++)
{
	do
	{
		cin >> list[i];
		if	(list[i] == 0)
			cout << "Try Again";
	}	while	(list[i] == 0);
}
I'm an idiot. I wasn't thinking. You have to initialize the array to 0 otherwise it holds whatever is in memory when you create it.

You need to do:
1
2
3
4
5
6
7
8
9
int list[100] = {0}; // initialize all elements to 0
for (int i = 0; i < 100; i++)
{
      do{
            cin >> list[i];
            if(list[i] == 0)
                  cout << "Try Again";
      }while(list[i] == 0);
}


[EDIT] Wanted to elaborate if this is found in archive searches later. Not initializing the array to 0 made it so the array had a random number according to whatever was in memory so it was failing on if(list[i]==0) because technically it wasn't empty but had a number (positive or negative).
Last edited on by closed account z6A9GNh0
Thanks bhx and Nikko! Just wanted to make sure if I can do the do while method involving arrays but I'm clear now
Glad we could help.
Topic archived. No new replies allowed.