Converting the for loop to a while loop is easy, but the for loop is a much safer construct as it groups the initialization, test and increment of the index variable in one clear place.
Incidentally, your code is misindented, and the nested if statements may be inconsistent:
if(structure[X].number == number)
{
if(structure[X].first_info == -1)
structure[X].first_info = position;
structure[X].second_info = position;
break;
}
When properly reformated, it becomes:
if (structure[X].number == number) {
if (structure[X].first_info == -1)
structure[X].first_info = position;
structure[X].second_info = position;
break;
}
Is this what you intended? Be more careful with indentation, it helps avoid silly mistakes.
Here is the converted code, but be aware that contrary to a for statement, a continue statement would by-pass the X++ update expression. Also worth noting is the surprising use of a 1 based index value for X. Index values are 0 based in C and array size can be checked with a < comparison instead of <=.
X = 1;
while (X <= 100) {
if (structure[X].number == -1) {
structure[X].number = number;
structure[X].first_info = position;
structure[X].second_info = position;
break;
}
if (structure[X].number == number) {
if (structure[X].first_info == -1)
structure[X].first_info = position;
structure[X].second_info = position;
break;
}
X++;
}
If structure has 100 elements, the code must be changed to:
X = 0;
while (X < 100) {
if (structure[X].number == -1) {
structure[X].number = number;
structure[X].first_info = position;
structure[X].second_info = position;
break;
}
if (structure[X].number == number) {
if (structure[X].first_info == -1)
structure[X].first_info = position;
structure[X].second_info = position;
break;
}
X++;
}
whileloop?structureis an array of dimension 101 or more,X<100should be the correct condition for thewhile/forloop