简体   繁体   中英

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

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 < end ; i+=flag){
    //parsing logic with index
}
    
    

The formatting... it burns!!

Jokes aside, try this:

int M = 100;
char input = 'U';
for (size_t i = 10; i < M & i > 0; ) {
    printf("i: %ld\n", i);
    if (input == 'U') ++i;
    else if (input == 'D') --i;
}

I don't know what M is but this should at least give you the structure of your solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM