Thread: single for loop --- two conditions??

  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    91

    single for loop --- two conditions??

    How do you write the following as two nested loops?

    Code:
    for (int low = 0, high = n - 1; low < high; low++, high--)

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    1,633
    It can't be written as nested loops without totally changing what it does.
    It is by nature a single-dimensional loop.
    Why do you think you want a double loop?
    Last edited by john.c; 07-14-2021 at 11:10 AM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    General rule: for is only a clever way to write while loops. With your example:
    Code:
    for (int i = 0, j = n - 1; i < j; i++, j--)
      doSomething();
    Is the same as:
    Code:
    /* block, because i and j are local to the loop */
    {
      int i = 0, j = n - 1;
    
      while ( i < j )
      {
        doSomething();
    
        i++, j--;
      }
    }

  4. #4
    Registered User
    Join Date
    Apr 2021
    Posts
    140
    I don't think you want that as two loops, because that would change the behavior in ways you don't expect. However, you could factor the "high" variable out as a function of the "low" variable:

    Code:
     
    for (int low = 0; low < n / 2; ++low) {
         int high = n - 1 - low;
    
        // etc.
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. While loop with multiple conditions.
    By Tmadden49 in forum C Programming
    Replies: 8
    Last Post: 04-09-2020, 05:16 PM
  2. While loop with OR conditions, beginner
    By Paulsim in forum C++ Programming
    Replies: 5
    Last Post: 09-11-2012, 06:59 AM
  3. combined conditions in For loop
    By sjmp in forum C Programming
    Replies: 5
    Last Post: 08-24-2012, 04:35 AM
  4. Multiple conditions for the while loop?
    By Olidivera in forum C++ Programming
    Replies: 6
    Last Post: 04-24-2005, 03:47 AM
  5. While Loop Conditions?
    By ted_smith in forum C Programming
    Replies: 8
    Last Post: 01-17-2005, 10:20 PM

Tags for this Thread