Loading...

Saturday 31 December 2011

// // Leave a Comment

Printing a Triangle in C Language...

Hi, Welcome back, Today I am back with a New C Program, Which will print an Triangle as below * ** *** **** *****

Code:

#include
#include

void main()
{
int i, j;
clrscr();
for(i=0;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
getch();
}
Now Let's Illustrate above code.

Description:

  • First 2 Lines are Pre-Processor Directives as you are already familiar with them.
  • We started our Main section of Program. with void main(). Void is being used because we are not going to return any values.
  • We have defined two Variables of Integer Type named i and j.
  • clrscr() -- Clear Screen Function is for Clearing the DOS screen which will appear while we Run program.
  • Now We take First for Loop here. Which we will use to print New Rows. Detail : for(i=0;i<=5;i++). [ i=0; Variable i is initialized with Value 0. i<=5; i will continue up to value 5. Because we have to print Asterisks (*) in Five Rows. i++; This Operator is used to Increment value of i by 1 every time.]
  • Once another for loop is used with Variable j. We have used this to print Columns. Details : for(j=1; j<=i;j++). [ j=0; Variable j is initialized with Value 0. j<=i; j will continue up to value of i. (i.e. According to Rows) Because we have to print Asterisks (*) according to Number of Rows. j++; This Operator is used to Increment value of j by 1 every time.]
  • printf("*"); -- This command will print * in the Screen according to loop mentioned in above (No. 6).
  • Printf("\n"); -- This command will print new blank line when needed. i.e. According to first for loop.
  • getch(); -- This is a function which is an Input Function. We use this for input of Passwords or such data which does not display in screen. We have just used this here to Hold Screen. So that we can see the output.

If you have some questions about above tutorial or other questions, You can comment below or directly mail me at john@johnbhatt.com. I will surely help you. Its my promise. Lets Enjoy Learning together.... Ehhhh... Happy New Year 2012....


John Bhatt
P.Yar.B Complex