gpt4 book ai didi

c - 如何使用 1 个循环在 C 中打印等边三角形?

转载 作者:行者123 更新时间:2023-11-30 21:05:01 24 4
gpt4 key购买 nike

我想以等边形式打印序列************

对于给定的输入 n(此处为 5),在 C 中使用单个循环。

#include<stdio.h>

我尝试使用正常方法,即使用一个外循环和一个内循环来打印相应的元素。现在,我的目标是通过使用 1 个循环来降低时间复杂度。

for(int i=n;i>0;i--)
{
for(int j=0;j<n-i;j++)
printf(" ");

for(int j=0;j<i;j++)
{
printf("* ");
}
printf("\n");
}

最佳答案

你可以试试这个

#include <stdio.h>

int main()
{
int i, j, rows;

/* Input number of rows to print */
printf("Enter number of rows : ");
scanf("%d", &rows);

/* Iterate through rows */
for(i=1; i<=rows; i++)
{
/* Print leading spaces */
for(j=i; j<rows; j++)
{
printf(" ");
}

/* Print star */
for(j=1; j<=(2*i-1); j++)
{
printf("*");
}

/* Move to next line */
printf("\n");
}

return 0;
}

输出

Enter number of rows: 5
*
***
*****
*******
*********

关于c - 如何使用 1 个循环在 C 中打印等边三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57059785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com