-2

I have to print the following pattern in C# -

  A B C D E F G F E D C B A
    A B C D E F E D C B A
      A B C D E D C B A
        A B C D C B A
          A B C B A
            A B A
              A

I'm able to print the pattern in C but not in C# because the character input does not work in C#. I tried converting it but I'm not able to convert it properly and facing the problems with for loops. Please tell me how to write equivalent C# code. Thanks in advance.

C code is:

#include<stdio.h>
#include<conio.h>
int main()
{
  char ch,r,c;
  int sp;
  printf("\nEnter last character of triangle : ");
  scanf("%c",&ch);
  if(ch>='a' && ch<='z')
      ch=ch-32;
  printf("\n");
  for(r='A'; 'A'<=ch; ch--,r++)
  {
    for(sp=r; sp>'A'; sp--)
       printf(" ");
    for(c='A'; c<=ch; c++)
       printf("%c",c);   
    for(c=ch-1; c>='A'; c--)
       printf("%c",c);
    printf("\n");
  }
  getch();
  return 0;
}

Edited

My C# Code:

public class Pascal_Triangle
    {
        public void printPascal()
        {
            char ch, r, c;
            int sp;
            Console.WriteLine("\nEnter last character of triangle : ");
            ch = Convert.ToChar(Console.ReadLine());
            if (ch >= 'a' && ch <= 'z')
                ch = Convert.ToChar(ch - 32);

            for (r = 'A'; 'A' <= ch; ch--, r++)
            {
                for (sp = r; sp > 'A'; sp--)
                    Console.WriteLine(" ");
                for (c = 'A'; c <= ch; c++)
                    Console.Write(c);
                for (c = Convert.ToChar(ch - 1); c >= 'A'; c--)
                    Console.Write(c);
            }
                Console.ReadLine();
        }
    }

The Output I'm getting:

enter image description here

4

1 回答 1

2

C# 确实支持遍历字母表...

char c = 'A';
++c;

c将增长到'B'的地方

但当然,您不能增加/减少字符串,只能增加/减少一个字符。

你的代码太复杂了,试试这个。很容易理解,一步一步来。

        Console.WriteLine("\nEnter last character of triangle : ");
        char ch = Convert.ToChar(Console.ReadLine());

        if (ch >= 'a' && ch <= 'z')
        {
            ch = Convert.ToChar(ch - 32);
        }


        int numberOfLines = ch - 'A' + 1;
        var graphic = "";

        for (var i = 0; i < numberOfLines; i++, ch--)
        {
            var line = "";
            var tmp = "";

            for (var j = 0; j < i; j++)
            {
                tmp += " ";
            }
            line += tmp;

            for (var j = 'A'; j < ch; j++)
            {
                line += j.ToString();
            }
            for (var j = ch; j >= 'A'; j--)
            {
                line += j.ToString();
            }

            line += tmp;              
            graphic += line + "\n";
        }

        Console.WriteLine(graphic);
        Console.ReadLine();
于 2013-09-14T23:37:09.340 回答