04/03/2019

Design * triangle in C-Programming

Design  *  triangle in C-Programming:

  Here we Design a triangle with "*". You have to give number of rows and it will print that triangle including given number of rows with element "*". See the picture below, its looks like this.
Design  *  triangle in C-Programming

Important Tools:

1. for-loop


You can also see:

2. Find the Transpose of a Matrix

Code:

Design  *  triangle in C-Programming


#include<stdio.h>
int main()
{
  int i,j,n;
  printf("Enter the number of row:");
  scanf("%d",&n);
  for(i=0;i<n;i++)
  {
    for(j=0;j<=i;j++)
    {
      printf("*");
    }
    printf("\n");
  }
}

Output:

The output is given below:

You can also see:

1. Find the largest number in C-Programming
2. Print a MATRIX in C-Programming using array


Explanation:

1. First we use the header package <stdio.h>. To know more visit Header Package.
2. We use 3 integers variable i,j and n.
3. Then we used n for store the value of row number and we used i and j for for-loop.
4. Lets see how for-loop works here with an example. So the code is-
  for(i=0;i<n;i++)
  {
    for(j=0;j<=i;j++)
    {
      printf("*");
    }
    printf("\n");
  }
here let n=3, then first it will take i=0 and enter in the first for-loop. After that it will enter in 2nd for-loop with the initial value of j=0 and it will print a * . Again it will exist from 2nd for-loop and take a new line and again go to the 1st for-loop. Therefore it will take i=1 check the condition that is less than 3 and enter into the loop, then it will enter into the 2nd for loop and  take j=0 and print a * and again it will go into 2nd loop and increment the value i.e j=1 which is equal to 1 and again it will print a *. So it will print two * side by side. Now it again go to the first loop and take i=2 and will enter in the 2nd for-loop and it will do that same thing 3 times for j=0,j=1 and j=2, then it will exists from 2nd loop and finished here because first for-loop does not work for i=3.  

1 comment: