how to use two or more iterators to increment inside a for loop

。_饼干妹妹 提交于 2020-01-30 13:21:27

问题


int i,j;
for(i=0;j=10;j>=0;i<10;i++;j--){
   printf("%d %d",i,j);
}

It brings error while executing, how to rectify it and what is the correct syntax for using multiple iterators in for loop


回答1:


A for loop has the following syntax:

for ( expression ; expression ; expression )

There are 3 expressions separated by semicolons. You have 6 expressions separated by semicolons. That's invalid syntax.

You should write it as follows:

for(i=0,j=10; j>=0 && i<10; i++,j--)

For the first expression, separate the two assignments with the comma operator. Similarly for the third expression. For the second, you want both conditionals to be true, so separate them with the logical AND operator &&.

Also, the error you got was not while executing but while compiling.




回答2:


Change for(i=0;j=10;j>=0;i<10;i++;j--){}to for(i=0, j=10; j>=0 && i<10; i++,j--){}




回答3:


You can use comma operator to separate statements in initialization and limit condition for both variables. See below.

int i,j;
for(i=0,j=10;j>=0 && i<10;i++,j--){
   printf("%d %d",i,j);
}

To see Comma operator in the specs at following section

6.5.17 Comma operator Syntax expression:

assignment-expression

expression , assignment-expression



来源:https://stackoverflow.com/questions/46416724/how-to-use-two-or-more-iterators-to-increment-inside-a-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!