[英]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.
如果用户将输入设置为 U 需要从索引开始到最后一个数组并复制值。 if user set input as D need to start the array from index last to zero index and copy the values.
如果用户将输入设置为 D 需要从索引最后一个到零索引开始数组并复制值。
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.
因此,尝试将代码优化为单循环是否可以在 C 中,如下所示或任何其他建议。
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 、 end和flag变量来实现这一点。
start denotes the starting of loop start表示循环的开始
end denotes the ending of loop end表示循环的结束
flag denotes the increment and decrement flag表示递增和递减
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.我不知道 M 是什么,但这至少应该为您提供解决方案的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.