Star Triangle Program in C using for loop

Write "C"  program to print Triangle in star pattern:


To understand this example, you should have knowledge of the following topics:
·     C if Else Statement
·     C For loop
·      C programming operators
C Star pattern  program using For loop:
#include <stdio.h> int main() { int i,j,rows; printf("Enter a number rows: "); scanf("%d",&rows); printf("\n"); for (i = 1; i <= rows; i++) { // loop to print the number of spaces before the star for (j = rows; j >= i; j--) { printf(" "); } // loop to print the number of stars in each row for (j = 1; j <= i; j++) { printf("* "); } printf("\n"); // for new line after printing each row } }
Output:
         *
       *   *
     *   *    *
   *   *    *   *
*   *    *   *    *
Explanation:
  • First three integers "i", "j" and "rows"are declared of type int.
  • Then in the First for loop “i” value is initialized with a value 1.
  • Now “i” value is checked with the condition i < rows that is (rows = User entered value). So the condition is True.
  • Now the loop enters into second for loop and checks the condition j >= i. Where "j = rows". and the condition is True.
  • Now prints space.
  • Now loop enters into third for loop where "j = 1" and checks condition "j <= i"  and prints " * ".
  • Print up to third for loop condition becomes False.
  • when the value of "i"  becomes "greater than entered value" the program terminates.
Share:

Ads

Search This Blog

  • ()
Powered by Blogger.

Strings in C With Syntax, C String Program with output

Strings in C :  Strings can be defined as the one-dimensional array of characters terminated by a null ('\0'). The difference betwee...

Blog Archive