Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

How to reduce for loops in C++

Task

How can I reduce the following program to 2 for loops and 1 print statement:

for (int i = 1; i <= iter; i++)
    {
        for (int j= 1; j <= row; j++) 
        {
            printf("*");
            for (int k = 1; k <= col; k++)
            {
                printf("_");
            }
            printf("*
");
        }
        printf("


");
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can merge any count of loops, using multiplication and rest from division (just the multiplication has not to overflow).

void f(int iter, int row, int col) {
  for (int i = 0; i < iter * row * col; i++) {
    printf("%s%s%s%s", 
           i % col == 0 ? "*" : "",
           "_",
           i % col == col - 1 ? "*
" : "",
           i % (row * col) == (row * col) - 1 ? "


" : "");
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...