C#: Display a triangle
Write a C# Sharp program that takes a number and a width also a number. It then displays a triangle of that width using that number.
Sample Solution:-
C# Sharp Code:
using System;
public class Exercise2
{
public static void Main()
{
// Prompt user to input a number
Console.Write("Input a number: ");
// Read and store the entered number
int num = Convert.ToInt32(Console.ReadLine());
// Prompt user to input the desired width
Console.Write("Input the desired width: ");
// Read and store the entered width
int width = Convert.ToInt32(Console.ReadLine());
// Initialize height to the value of width
int height = width;
// Loop through each row based on the given height
for (int row = 0; row < height; row++)
{
// Loop through each column based on the given width
for (int column = 0; column < width; column++)
{
// Print the number provided by the user
Console.Write(num);
}
// Move to the next line after printing a complete row
Console.WriteLine();
// Decrement the width after each row is printed
width--;
}
}
}
Sample Output:
Input a number: 2 Input the desired width: 5 22222 2222 222 22 2
Visual Presentation:
Flowchart:
C# Sharp Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C# Sharp program that takes three letters as input and display them in reverse order.
Next: Write a C# Sharp program that takes userid and password as input (type string). After 3 wrong attempts, user will be rejected.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics