- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to display numbers in the form of Triangle using C#?
To display numbers in the form of Triangle, firstly consider a two dimensional array.
int[,] a = new int[5, 5];
For a triangle, you need to consider spaces as shown below −
1 1 1 1 2 1 1 3 3 1
Then loop through to set the triangle with 1s on the left and right as in the following code −
Example
using System; class Demo { public static void Main() { // two dimensional array int[,] a = new int[5, 5]; for (int i = 0; i < 5; i++) { for (int k = 7; k > i; k--) { // prints spaces Console.Write(" "); } // loop to print the triangle for (int j = 0; j < i; j++) { if (j == 0 || i == j) { a[i, j] = 1; } else { a[i, j] = a[i - 1, j] + a[i - 1, j - 1]; } Console.Write(a[i, j] + " "); } Console.WriteLine(); } Console.ReadLine(); } }
Output
1 1 1 1 2 1 1 3 3 1
Advertisements