سؤال

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

هل كانت مفيدة؟

المحلول

C# does support looping through alphabet...

char c = 'A';
++c;

Where c would grow to 'B'

But of course, you can't increase/deacrease a string, only a character.

Your code is a way too complicated, try this. It's easy to understand, just go step by step.

        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();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top