嵌套循环在 C 中创建模式(不是菱形)

Nested loops creating pattern (not diamond) in C

因此,对于我的作业,我必须输入长度和宽度,并根据输入打印出“*”的模式。最小高度为 7,仅增加奇数,宽度为 6 的任意倍数。

使用高7宽12输出的基本格式:

************
************
***   ***   
   ***   ***
***   ***  
************
************  

所以基本上第一行和最后两行是笔直穿过整个宽度,奇数行包含 3 个星号后跟 3 个空格,直到到达宽度的末端。偶数行以 3 个空格开头。

我已经想出如何使用以下代码打印前两行:

do 
    {
        printf("*");
        ++i;
    }while(i<width);

    printf("\n");

    do 
    {
        printf("*");
        ++j;
    }while(j<=width);
    printf("\n");

但我这辈子都想不出使用基本嵌套循环打印出内部图案的正确方法。我问了一个不熟悉C但用Java写了一个基本程序的程序员朋友。我不知道 Java 并尝试翻译它,但注意到两种语言之间的逻辑存在很大差异,这让我很头疼。这是他的代码:

// LOGGING
var consoleLine = "<p class=\"console-line\"></p>";

console = {
    log: function (text) {
        $("#console-log").append($(consoleLine).html(text));
    }
};


// PATTERN PARAMETERS
var rows = 6;
var cols = 7;

// hard code a space so html respects it
var space = "&nbsp;"

console.log("cols: " + cols + " rows: " + rows);

for (y = 0; y < rows; ++y) {
    var line = "";
    for (x = 0; x < cols; ++x) {

        // First two and last two rows do not have patterns and just print filled
        if (y == 0 || y == 1 || y == rows - 1 || y == rows - 2) {
            line += "*";
        } else {
            if (y % 2 == 0) {
                // Even row
                line += x % 6 < 3 ? "*" : space;
            } else {
                // Odd row
                line += x % 6 >= 3 ? "*" :  space;
            }
        }
    }
    console.log(line);
}

请帮助我或指出正确的方向!!我在网上搜索过,但似乎找不到有效的解决方案!

Edit-忘了说所有"printf"一次只能打印一个字符...比如单个*

编辑编辑 - 我成功了!!!!非常感谢大家,非常感谢您的投入和指导!这是我拥有的完美运行的东西:

for (y = 0; y < height; ++y) 
    {
    printf("\n");

    for (x = 0; x < width; ++x) 
        {
        // First two and last two rows do not have patterns and just print filled lines
        if (y == 0 || y == 1 || y == height - 1 || y == height - 2) 
           {
           printf("*");
            }
        else 
        {
            if (y % 2 == 0)
            {
              if(x%6<3)
                {
                    printf("*");
                }
                else
                {
                    printf(" ");
                }

            } else {
                // Odd row
                if(x%6>=3)
                {
                    printf("*");
                }
                else
                {
                    printf(" ");
                }
        }
        }

    }
printf("\n");

编写一个带有 3 个参数 n,a,b 的函数,它交替打印 n 组,每组 3 个参数 ab。您可以调用此函数来打印 4 种不同的线条。您可以循环打印中间部分。玩得开心!

更简单的选择:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
    int row, col, height = atoi(argv[1]), cols = atoi(argv[2]);
    for (row = 0; row < height; row++) {
        for (col = 0; col < cols; col++) {
            putchar(row < 2 || row >= height - 2 ||
                  col % 6 / 3 == row % 2 ? '*' : ' ');
        }
        putchar('\n');
    }
}