Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print a shape with * using C

Trying to learn how to code with C.
I’m trying to print a draw according to the amount of lines the user asks. This for an school project.
For example, this if the user asks for a drawing of 7 lines.

****
 ***
  **
   *
   **
   ***
   ****

Or this if the user asks for a 5 lines drawing.

***
 **
  *   
  **
  ***

With some help from Chat GPT (a lot) I’ve got this so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>

int main() {
    int n, i, j, k;

    // Ask the user for a number of lines.
    printf("Insert the numbers of lines to form the draw: ");
    scanf("%d", &n);

    // Validate if the number of lines requested by the user is odd.
    if (n % 2 == 0) {
        printf("The number of lines must be an odd amount.\n");
        return 1; 
    }

    // Print upper boddy of the draw.
    for (i = 0; i < n/2+1; i++) {
        for (j = 0; j < i; j++) {
            printf(" ");
        }
        for (k = 0; k < n/2+1-i; k++) {
            printf("*");
        }
        printf("\n");
    }

    // Print lower body of the draw.
    for (i = n/2-1; i >= 0; i--) {
        for (j = 0; j < i; j++) {
            printf(" ");
        }
        for (k = 0; k < n/2+1-i; k++) {
            printf("*");
        }
        printf("\n");
    }

    return 0; 
}

Problem I get with this is I get something like this instead:

*****
 ****
  ***
   **
    *
   **
  ***
 ****
*****

What do I have to modify?

>Solution :

Essentially the posted code, prints the upper part properly. So let us not disturb it. We need to work only on the lower part of printing.

Here as well, your *s are printed properly. So you would need to think about only the print of spaces which is done by the j loop. Basically, you need to print n/2 (constant) number of spaces for this offset.

// Print lower body of the draw.
for (i = n/2-1; i >= 0; i--) {
    for (j = 0; j < n/2; j++) { // updated this line
        printf(" ");
    }
    for (k = 0; k < n/2+1-i; k++) {
        printf("*");
    }
    printf("\n");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading