0

I´m currently working on my semester work and this is a piece of my code. As you can see there is a for loop with some if statements where I am working with a structure. I was thinking of converting this for loop onto a while loop but I´m not quite sure how. Maybe someone may give me a hint?

for(X = 1; X <= 100; X++) 
        {
          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;
          }
        }
4
  • 2
    what is the reason you want to convert to while loop? Commented Mar 10, 2018 at 16:07
  • You have an indentation problem after the third if, or you’re missing some braces. Commented Mar 10, 2018 at 16:10
  • 5
    A for loop is much better than a while loop because it keeps all the loop control information on a single line. Commented Mar 10, 2018 at 16:12
  • 1
    And unless structure is an array of dimension 101 or more, X<100 should be the correct condition for the while/for loop Commented Mar 10, 2018 at 16:13

6 Answers 6

2

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++;
}
Sign up to request clarification or add additional context in comments.

3 Comments

By far the best answer here, UV
It is NOT a "a much safer construct". It depends on the situation.
@chqrlie, ah..I see. My mistake.
2

All basic loops have three components:

  • an initializer (an initial value assigned to a variable)
  • a condition (the value we are checking for to stay in the loop)
  • a modifier (something that modifies our variable)

With a for loop you notice all three of those here:

for(X = 1; X <= 100; X++) 

The first component in the parentheses is an initializer (X=1), the next component is the condition (X <= 100), and the last component is the modifier (X++).

We can use the exact same components with a while loop. We just place them differently:

int x = 1; //our intializer
while (x <= 100){ //our condition
      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++; //our modifier
   }

With that said, arrays in C always start at index 0. I kept your code the same as you had it, but generally whether you are using a for loop or while loop you will want to change your initializer and condition as follows:

  • your initializer should likely be x = 0 (not x = 1)
  • your condition should likely be either x < 100 or x <= 99 (not x <= 100)

This is because an array of 100 items will have indexes 0 to 99.

Two more points:

When counting through an indexed array like this the code is usually easier to read as a for loop rather than a while loop. Is there a reason that you were wanting to use a while loop instead?

Based on your indentation it was unclear what should be included in the last if clause. I have added braces to your last if clause to make it easier to read, but maybe other lines should have been included in the braces as well?

Comments

1

You can do this to convert to while loop. But I would suggest to search and understand the loop structures yourself.

X=0;   /* for arrays indexing always starts at 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)  /* adding braces */
        { 
          structure[X].first_info = position;
          structure[X].second_info = position;
          break;
        }
      }
      X++;
}

7 Comments

I would point out that in C the indexing starts at 0 not 1 and the end conditions should be X<100 for an array of dimension 100.
Is it standard to start the indexing at 0 or is it good practice?
Indexing always starts at zero, whether you want to read/write the 0th item, it's up to algorithm.
I wrote my comment, because beginners often make the mistake of declaring an array int arr[10] and loop from 1 to 10, when they should loop from 0 to 9. I assume that this is the case with this example and it's worth pointing that out.
I downvoted you because you give a code-solution without discussing the why/how. The OP doesn't learn from that.
|
0

The for loop construct groups the index variable initialization, loop conditional, and index increment steps of the loop into one statement. So in order to convert a for loop into a while loop, you just need to unwrap this grouping into effectively three separate statements. In general, you can transform any for loop into a while loop using the following algorithm. Take a for loop like so:

for(A;B;C) { /* where A,B,C are valid C statements (e.g., X=0), not variables */
   /* operational code */
}

To the following while loop using the same statements within the A, B, C placeholders:

A;
while(B) {
   /* operational code */
   C;
}

With this algorithm, you should be able to convert any for loop into a equivalent while loop.

Comments

-2

I think this one is pretty simple. Maybe I misunderstood your situation, if then forgive me :)

My approach is like this:

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

2 Comments

What is the var in var X = 1;?
You give a code-solution without discussing the why/how. The OP doesn't learn from that.
-2

Existing code can be converted into while as below

int x =1;
while(x!=100)
{
    //Your code here 
    x++;
}

6 Comments

What is the var?
var is a type like other types like int, string etc only difference is var identifies it's type based on it's value. Here we have assigned 1 to this variable so var will be int type automatically.
var and string are not standard types in C.
Is it specific to C language? We have these types in C#
Those are 2 different languages, my friend. In C, there's no dynamic type binding. stackoverflow.com/questions/9837972/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.