[英]Can nested loop be grabbed on a single loop?
Here is the code: 这是代码:
#include <stdio.h>
int main() {
int i, j;
for(i = 0; i < 10; i++) {
for (j = 0; j < i; j++){
printf("*");
}
printf("\n");
}
return 0;
}
Can the code above be looped on a single loop something like this on bottom? 上面的代码可以像下面这样在单个循环中循环吗? (Though this didn't work for me.) (尽管这对我不起作用。)
#include <stdio.h>
int main() {
int i, j;
for (i = 0, j = 0; i < 10, j < i; i++, j++){
printf("*");
}
printf("\n");
return 0;
}
Yes, it's possible, but you should look up what different operators do (and think about what your code should do, too). 是的,这是可能的,但是您应该查找不同的运算符的工作(并考虑您的代码也应该做什么)。
for (int i = 10; i <= 100; i++) {
if (i % 10 <= i / 10) {
printf("*");
}
if (i % 10 == 0) {
printf("\n");
}
}
Not sensibly. 不明智。 You want to loop over each value of j
for each value of i
, which implies a nested loop. 你要循环的每个值j
的每个值i
,这意味着一个嵌套循环。 Your second example will increment both i
and j
after each iteration, which is very different. 您的第二个示例将在每次迭代后同时增加i
和j
,这是非常不同的。
In principle, you could loop a single variable from 0 to (at least) 45, and do some arithmetic to find the values of i
and j
from that; 原则上,您可以将单个变量从0循环到(至少)45,然后执行一些算术运算以从中找到i
和j
的值; but that would be considerably harder to follow, and probably less efficient, so I won't suggest a way to do that. 但这将很难遵循,而且效率可能会降低,所以我不会建议这样做的方法。
You can use the comma operator for this kind of thing, although your condition part is incorrect. 尽管您的条件部分不正确,但是您可以使用逗号运算符。
It should be 它应该是
for (i = 0, j = 0; i < 10 && /* perhaps || here*/ j < i; i++, j++){
You can write like this but its not readable. 您可以这样写,但不可读。
#include <stdio.h>
int main() {
int i, j;
for(i=0, j=0; j<i? :(printf("\n"), j=0, i++, i<10); j++) {
printf("*");
}
return 0;
}
Give it a try, it will work fine, without any extra iterations. 试试看,它可以正常工作,而无需任何额外的迭代。
int count=1,tmp=1;
for (int i = 1; i <= 10; i++)
{
printf("*");
if (count == i) {
printf("\n");
tmp++;
count+=tmp;
}
}
#include <stdio.h>
int main() {
int i = 10, j = 0, k = 1;
while(j++ < i)
(j == k && j <i) ? (printf("\n"),k+=1,j=0):printf("*");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.