'using for loop iteration (decrement or increment )based on user input in C program

i am writing code to do some operation with array. requirement is to read the array and set the value. if user set input as U need to start the array from index to last and copy the values. if user set input as D need to start the array from index last to zero index and copy the values.

except looping condition everything is same inside the loop. so trying to optimize the code into single loop is it possible in C like below or any other suggestion .

char input = 'U';

if (input == 'U')
   for (size_t i = 0; i < M; i++)
    {
else if (input == 'D')
   for (size_t i = M; i < 0; i--)
  {
     //parsing logic with index;
  }
 


Solution 1:[1]

We can use single loop and can use start, end & flag variables to achieve this.

start denotes the starting of loop

end denotes the ending of loop

flag denotes the increment and decrement

char input = 'U';

size_t flag = 1;
size_t start = 0, end = M;

//if input is 'D' default if set to match input U
if (input = 'D'){
    start = M;
    end = 0
    flag = -1
}
//single loop
for (size_t i = start ; ; i+=flag){
    if(input == 'D' && i <= end) break;
    else if(input =='U' && i >= end)break;
    //parsing logic with index
}
    
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1