2014-07-27 48 views
-5

這個字母圖案是否有任何其他的方式做這個節目用更少的loops.Its沒有多少有效的計劃在C++中

#include <iostream> 

using namespace std; 

int main() { 
    int i,j,n,s; 
    cout<<"Enter the value of n"; 
    cin>>n; 
    for(i=1;i<=n;i++){ 
     for(s=1;s<=n-i;s++){ 
      cout<<" "; 
     } 
     char ch=97; 
     int k=1; 
     for(j=1;j<=(i*2-1);j++) { 
      if (k%2!= 0){ 
       cout <<ch; 
       ch++; 
      } else { 
       cout<<" "; 
      } 
      k++; 
     } 
     cout<<endl; 
    } 
} 

輸出的數量:

Enter the value of n6 
    a 
    a b 
    a b c 
    a b c d 
a b c d e 
a b c d e f 
+2

比少?它看起來應該可以使用嵌套在另一個循環中的一個循環來實現。 – user3553031

+1

更少的循環數?爲什麼不只是以這種格式打印它們:P – P0W

+0

你的問題還不清楚,但我想這可以用一個循環來完成,每一行作爲一個字符串。 –

回答

0

試試下面的代碼 -

#include<stdio.h> 
main() 
{ 
    int i,j,k,num; 
    printf("Enter the number of letter \n"); 
    scanf("%d",&num); 
    for(i=0;i<num;i++) 
    { 
      for(j=num-1;j>i;j--) 
        printf(" "); 
      for(k=0;k<=i;k++) 
        printf("%c ",(97+k)); 
      printf("\n"); 
    } 
} 

樣品的輸入和輸出 -

[email protected]:~/c/basics$ ./a.out 
Enter the number of letter 
4 
    a 
    a b 
a b c 
a b c d 
0
#include <stdio.h> 

int main(){ 
    char *pat = "a b c d e f g h i j k l m n o p q r s t u v w x y z"; 
    int i, n; 
    printf("input n : "); 
    scanf("%d", &n); 
    for(i = 1;i<=n;++i) 
     printf("%*s%.*s\n", n - i, "", (i << 1) - 1, pat); 

    return 0; 
} 

#include <iostream> 
#include <string> 

using namespace std; 

int main() { 
    int n; 
    cout << "Enter the value of n : "; 
    cin >> n; 
    string spaces(n, ' '); 
    string pat("a b c d e f g h i j k l m n o p q r s t u v w x y z"); 
    for(int i=1;i<=n;i++){ 
     cout << spaces.substr(i); 
     cout << pat.substr(0, (i << 1) -1); 
     cout << endl; 
    } 
}