Home > Net >  How to make a traingle of characters based on user input
How to make a traingle of characters based on user input

Time:07-22

I'm CS newbie, and I'm currently taking an introductory course in C. I need to understand how to print a right triangle of * which base and heigth are given by user input.

Since I don't know how to print a character one more time for every row, I thought I could use a space character before starting a new line. But when I write this code:

#include <stdio.h>
#include <stdlib.h>

int main ()
{
    char s[80];
    int a, i, j;

    fgets(s, sizeof(s), stdin);
    a = atoi(s);

    if (a == 0) 
        printf("No print\n");
    for (i = a - 1; i >= 0; i--) {
        for (j = 1; j <= a - i; j  ) {
            printf("*\n");
        } 
        printf("%c", ' ');
    }
    return 0;
}

the output is a lot of asterisks (the right number of asterisks I'd like the output to have) and only one last, final space. Is there something I can do to modify my code, or a better way to write it for solving the same problem? (My professor don't want us to use scanf yet).

EDIT: Okay, I changed the braces, thanks a lot. Now the output for 4 is:

4
*
 *
*
 *
*
*
 *
*
*
*

but I still can't figure out why. Maybe I put the braces in the wrong place?

CodePudding user response:

I didn't read the whole explanation, but I read this: you want to create a triangle and you have written source which looks like:

for (...
    for (...
        printf("*\n");
    ...
    printf(...) // no \n

The \n is a newline character and makes sure that, after having written an asterisk, you immediately jump to the next line. Obviously you can't create a triangle like that: you must at least have some characters, next to each other, before going to the next line.

So I would suggest something like:

for (...
    for (...
        printf("*");
    ...
    printf(... "\n") // \n present in this statement.

CodePudding user response:

Your code is correct, just adjust printf statement and newline '\n' Code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char s[80];
    int a, i, j;

    fgets(s, sizeof(s), stdin);
    a = atoi(s);

    if (a == 0) 
        printf("No print\n");
    for (i = a - 1; i >= 0; i--) {
        for (j = 1; j <= a - i; j  ) {
            printf("*");
        } 
        printf(" \n");
    }
    return 0;
}
  •  Tags:  
  • c
  • Related