How does the index increment?

I have a question about the program below. The index is set to 0 right? As c is being incremented, what happens to index. As far as i can see, it remains 0. So how does it work so that "ans" is being checked against every value in the array?








const int TWENTY = 20;
int a[TWENTY] = {0};
int index = 0;
int ans;

cout << "Enter twenty unique numbers in the range of 10-100 inclusives." << endl;

for ( int b = 0; b < TWENTY; )
{
int duplicate = 0;
cin >> ans;

if ( ans >= 10 && ans <= 100 )
{
for ( int c = 0; c < index; c++ )
{
if ( ans == a[c] )
{
duplicate = 1;
break;
}
}
if ( !duplicate )
{
a[index++] = ans;
b++;
}
else
cout << "\nThe number is a duplicate!!!\n" << endl;
}
else
cout << "\nThe number is out of range!!!" << endl;
}

for ( int d = 0; d < TWENTY; d++ )
{
cout << "\n" << a[d] << endl;
}



return 0;
}
It's correct, at the beginning Index = 0.
But in the first run of this loop, you don't need to check if the input value is still existing. So this loop
for ( int c = 0; c < index; c++ ) is not entered.

This way duplicate is still 0 and this command gets called a[index++] = ans;

Here you save ans in a[0] and after this you increase index by 1.

When you read the second value, index=1. So you check if a[0] equals the new value.
1
2
3
4
5
6
7
8
for ( int c = 0; c < index; c++ )
{
  if ( ans == a[c] )
  {
  duplicate = 1;
  break;
  }
}

If it's not equal you save it as a[1] and increase the index again.

With the 3rd value it's the same - here you compare with a[0] and a[1].

And so on
Thanks a bunch!!! I think i get it now!
Topic archived. No new replies allowed.