【问题标题】:Program for this Alphabet pattern in c++用 c++ 编写这个字母模式的程序
【发布时间】:2014-07-27 08:03:59
【问题描述】:

有没有其他方法可以用更少的循环来完成这个程序。效率不高

#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

【问题讨论】:

  • 小于什么?看起来应该可以使用嵌套在另一个循环中的一个循环来实现。
  • 循环次数更少?为什么不简单地以这种格式打印它们:P
  • 你的问题不清楚,但我想这可以通过一个循环来完成,每一行都是一个字符串。
  • 请努力,我可以指出你在哪里可以找到类似的代码cprogrammingcodes.blogspot.in/p/pyramid.html

标签: c loops nested-loops


【解决方案1】:

试试下面的代码-

#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");
    }
}

示例输入和输出-

sathish@ubuntu:~/c/basics$ ./a.out 
Enter the number of letter 
4
   a 
  a b 
 a b c 
a b c d 

【讨论】:

    【解决方案2】:
    #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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多