Enzor
Enzor

Reputation: 55

User inputs a number, and program should surround it with charatchers

This is my code, it works but i feel i could do something different

#include <stdio.h>

int main()
{
    int n;
    printf("Input a number [0,9]: ");
    scanf("%d", &n);
    printf("*****\n");
    printf("*****\n");
    printf("**%d", n);
    printf("**");
    printf("\n*****\n");
    printf("*****\n");

    return 0;
}

Is this the best solution or is there something easier?

Upvotes: 0

Views: 61

Answers (2)

0___________
0___________

Reputation: 67546

you can do it a bit more universal way. It will print NCHARS around the number and NLINES lines of FILLER around the number. Any number is covered (including negave ones)

#include <stdio.h>

#define NCHARS      3
#define NLINES      3
#define FILLER      '*'

size_t countdigits(int n)
{
    size_t ndigits = n <= 0 ? 1 : 0;
    while(n) 
    {
        ndigits++;
        n /= 10;
    }
    return ndigits;
}

void printlines(size_t nchars, char ch)
{
    for(size_t before = 0; before < NLINES; before++)
    {
        for(size_t pos = 0; pos < nchars; pos++ )
            printf("%c", ch);
        printf("\n");
    }
}

void printfsurrounded(int n)
{
    size_t nchars = countdigits(n);
    printlines(nchars + NCHARS * 2, FILLER);
    for(int pos = 0; pos < NCHARS; pos++) printf("%c", FILLER);
    printf("%d", n);
    for(int pos = 0; pos < NCHARS; pos++) printf("%c", FILLER); 
    printf("\n");
    printlines(nchars + NCHARS * 2, FILLER);
}

int main(void)
{
    printfsurrounded(4);
    printf("\n");
    printfsurrounded(1024);
    printf("\n");
    printfsurrounded(-233445);
}

https://godbolt.org/z/hz1eq9

Upvotes: 1

pmg
pmg

Reputation: 108938

I tend to do 1 printf() per output line

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

int main(void)
{
    int n;
    printf("Input a number [0,9]: ");
    if (scanf("%d", &n) != 1) exit(EXIT_FAILURE);
    if ((n < 0) || (n > 9)) printf("nope\n");
    else {
        printf("*****\n");
        printf("*****\n");
        printf("**%d**\n", n);
        printf("*****\n");
        printf("*****\n");
    }

    return 0;
}

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

int main(void)
{
    int n;
    printf("Input a number [0,9]: ");
    if (scanf("%d", &n) != 1) exit(EXIT_FAILURE);
    if ((n < 0) || (n > 9)) printf("nope\n");
    else {
        for (int i = 0; i < 5; i++) {
            if (i == 2) {
                printf("**%d**\n", n);
            } else {
                printf("*****\n");
            }
        }
    }

    return 0;
}

Upvotes: 2

Related Questions