Right triangle star pattern in C
In programming, particularly in the C programming language, one popular exercise is to create different patterns using different symbols or characters. One such pattern is the right triangle star pattern, which involves printing a triangle made up of asterisks (*) or any other desired character. In this article, we’ll explore how to create the right triangle star pattern in C.
The right triangle star pattern is a pattern made up of asterisks, arranged in a triangle shape. The triangle is made up of lines of increasing length, where the first line contains one asterisk, the second line contains two asterisks, and so on. Here’s an example of what the right triangle star pattern looks like:
* ** *** **** *****
To create this pattern in C, we’ll use nested loops. The outer loop will control the number of lines in the triangle, while the inner loop will control the number of asterisks printed on each line.
Here’s the code to create the right triangle star pattern in C:
#include <stdio.h> int main() { int i, j, rows; printf("Enter the number of rows: "); scanf("%d", &rows); for(i=1; i<=rows; i++) { for(j=1; j<=i; j++) { printf("*"); } printf("\n"); } return 0; }
Let’s break down this code. First, we declare three variables: i, j, and rows. i and j will be used in the nested loops, while rows will be used to determine the number of lines in the triangle.
Next, we prompt the user to enter the number of rows they want in the triangle using printf() and scanf(). We store this value in the rows variable.
We then start our nested loops. The outer loop runs rows times, which will determine the number of lines in the triangle. The inner loop runs i times, which will determine the number of asterisks printed on each line. Inside the inner loop, we use printf() to print an asterisk.
After the inner loop completes, we use printf() to print a newline character (\n). This will move the cursor to the next line and start a new line in the triangle.
Once the outer loop completes, the program exits.
This code will produce the right triangle star pattern, as shown in the example above, with the number of rows determined by the user.
In conclusion, creating patterns using symbols or characters is a fun exercise in programming, and the right triangle star pattern is just one example. By using nested loops in C, we can easily create this pattern and produce a visually appealing output.