Search code examples
c#loopsfor-loopcursor-position

How can I draw a diagonal line with Console.SetCursorPosition c#?


I need to do a function that received 3 entiers: horizontal and vertical position of the beginning of the line, as well as its length, and draws the diagonal line descending to the left. I don't understand how i can do the diagonal line. I have done a loop for do a horizontal line but I don't know what i need to change for draw a diagonal line.

For the horizontal line, I have done:

    static void LigneHorizontale(int posh, int pov, int longueur)
    {

            for (int i = 0; i < longueur; i++)
            {
                Console.SetCursorPosition(posh+i, pov);
                Console.WriteLine("-");
            }
    }

Solution

  • You need to set a CursorPosition to a given location, then need to draw a horizontal line.

    Like,

    public static void LineHorizontale(int x, int y, int length)
    {
        //This will set your cursor position on x and y
        Console.SetCursorPosition(x, y);
    
        //This will draw '-' n times here n is length
        Console.WriteLine(new String('-', length));
    }
    

    if you want to print diagonal line then use \ instead of - and increase x and y position.

    something like,

        public static void LineDiagonal(int x, int y, int length)
        {
    
            for(int i = 0; i < length; i++)
            {
                //This will set your cursor position on x and y
                Console.SetCursorPosition(x+i, y+i);
    
                //This will draw '\' n times here n is length
                Console.Write(@"\");
    
            }
        }
    

    Output:

    enter image description here

    enter image description here