facebook like button

01 May, 2011

program 39: Equilateral star triangle

The need:
     This is a simple program to print equilateral triangle of symbol '$'. This program was written to learn managing the output on the screen. After doing its job this program asks the user whether to end or try with other value. Moreover this program was prerequisite for the next program of this blog which is also very good program (a recommended program for you to have a look).

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int j,i,k,l;
    char c;
    do
    {
        printf("Enter the number of stars in the base..");
        scanf("%d",&k);
        for (i=1;i<=k;i++)
        {
            for(l=0;l<(k-i);l++)
                printf(" ");
            for (j=0;j<i;j++)
                printf ("$ ");
            printf("\n");
        }
        printf("\nEnter y to try more...press any other key exit...\t");
    c=getchar();
    c=getchar();
    }
    while(c=='y');
}
 -------------------------------------------- 

The approach: 
This program creates an equilateral triangle on the output screen. First it asks the user to input the number of stars in the base and gives the output and then asks the user whether he wants the program to stop or wants to draw one more triangle. This is done using a do while loop which checks the value of character variable c. c is taken as input at the end of program. Notable point here is that I have written getchar() twice in the program still its only taking only one character at the end. WHY??? Read remarks for this.


Remarks:

1. You can try removing one getchar() statement. what happens???

2. Now try printing the value of variable c after each getchar() statement. what did you see???

3. You see the first value of c is '\n'(new line character). Observe the change in line in the output.(How come??? read all remarks.)

4. Second value of c is the value given by you.

5. I have already told you in previous posts that characters can be anything (digit, alphabet, space, tab, new line etc.) Now note that when you entered number of stars in the base, you must have pressed ENTER key after that. The number had been stored in variable k. Where did the ENTER key(new line) go?? Ans. : That remains in the memory and as soon as new character is required by the program this ENTER is assigned as required character. This is why I have used getchar() twice. Read paragraph 3 of approach in program25 of this blog for more details.

6. One could have used built-in function fflush(stdin); for the same purpose.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply