C#: Display a triangle
C# Sharp Basic Data Types: Exercise-2 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/csharp-exercises/data-types/csharp-data-type-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics