顯示 X 形圖案中數字的 C 程式
請參考下面給出的演算法,瞭解用於顯示 X 形圖案中數字的 C 程式。
演算法
Step 1: Start Step 2: Declare variables Step 3: Read number of rows Step 4: for loop satisfies
- if(i==j || i+j==rows-1)
- print i+1
- Print " "
以 X 形圖案列印數字的邏輯如下 -
for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ if(i==j || i+j==rows-1){ printf("%d",i+1); }else{ printf(" "); } } printf("
"); }
程式
以下是顯示 X 形圖案中數字的 C 程式 -
#include<stdio.h> main(){ int i,j,rows; printf("Enter number of rows:
"); scanf("%d",&rows); for(i=0;i<rows;i++){ for(j=0;j<rows;j++){ if(i==j || i+j==rows-1){ printf("%d",i+1); }else{ printf(" "); } } printf("
"); } }
輸出
當執行以上程式時,它會產生以下結果 -
Enter number of rows:10 1 1 2 2 3 3 4 4 55 66 7 7 8 8 9 9 10 10
廣告