Home >Backend Development >C#.Net Tutorial >How to print rhombus with for loop in c language
C language for loop printing diamond method: use two for loops to implement conditional judgment, the code is [int i,j;for(i=0; i=n-i-1&&j
C language for loop printing diamond method:
Method 1 (printing mainly with loop )
#include <stdio.h> void print(int n) { int i,j; for(i=1; i<=n; i++) { for(j=1; j<=n-i; j++) { printf(" "); } for(j=n-i+1; j<n+i; j++) { printf("*"); } printf("\n"); } for(i=n-1; i>=1; i--) { for(j=1; j<=(n-i); j++) { printf(" "); } for(j=n-i+1; j<n+i; j++) { printf("*"); } printf("\n"); } } void main() { int n; printf("---------开始打印符号---------\n"); printf("请输入数字:"); scanf("%d",&n); print(n); printf("---------结束打印符号---------\n"); }
Method 2: (Two fors, judge and implement based on conditions)
#include <stdio.h> //输出格式 void print(char ch) { putchar(ch); } //星号 void printstar(int n) { int i,j; //行,列 for(i=0; i<2*n-1; i++) { for(j=0; j<2*n-1; j++) { if(i<n) { if(j>=n-i-1&&j<n+i) { print('*'); } else { print(' '); } } else { if(j>=i-n+1&&j<3*n-i-2) { print('*'); } else { print(' '); } } } print('\n'); } } void main() { int n; printf("---------开始打印符号---------\n"); printf("请输入数字:"); scanf("%d",&n); printstar(n); printf("---------结束打印符号---------\n"); }
Explanation: (2n-1)—(n-i-1) = n i
( 2n-1) — (-(n-i-1)) = 3n-i-2
Result:
##Related learning recommendations:
The above is the detailed content of How to print rhombus with for loop in c language. For more information, please follow other related articles on the PHP Chinese website!