Home > Blockchain >  How to convert number to a star symbol?
How to convert number to a star symbol?

Time:09-16

I want to write a simple application that writes 3 numbers into an array. The numbers should be read in from the keyboard with scanf. The following should be displayed on the screen: If the entered numbers are 1,5,4, the following will be displayed

*
*****
****

My problem stays only in,how to convert number to a star symbol.Thank you!

for (int i = 1; i <= 3;   i) {
    printf("%d ",i);
    for (int j = 1; j <= i;   j) {
        printf("*");
    }
    printf("\n");
}

CodePudding user response:

Take this written in javascript, you should be able to convert it in C for your project :)

The loops are the key, one to scan each element of the input array, and another to print as many * as the value of the array (1, 5 and 4)

var input = [1, 5, 4]; // Let's assume you already have the input array
var output = ""; // You don't need this

for (var i = 0; i < input.length; i  ) {
  for (j = 0; j < input[i]; j  ) {
    output  = "*"; // printf("*");
  }
  output  = "\n"; // printf("\n");
}

console.log(output); // You don't need this

CodePudding user response:

void printArray(int *arr, size_t size)
{
    while(size--)
    {
        for(int i = 0; i < *arr; i  ) printf("*");
        arr  ;
        printf("\n");
    }
}

#define  NNUMBERS   3

int main(void)
{
    int arr[NNUMBERS];

    for(int i = 0; i < NNUMBERS; i  )
    {
        do
        {
            printf("\nEnter %d number:", i); 
        }while(scanf(" %d", &arr[i]) != 1);
    }
    printf("\n");
    printArray(arr,NNUMBERS);
}

https://godbolt.org/z/K63cfrx88

CodePudding user response:

I have two versions. Version 1 is easier and Version 2 is likely more efficient.

Basic version: allocate a string, fill it with N stars and print it.

#include <stdlib.h>

void printNstars(int N)
{
    char* str = (char *) malloc (N 1);
    memset(str,'*',N);
    str[N] = '\0';
    printf("%s\n", str);
}

A more efficient version would be to allocate the array once, and then reuse it. Here is an example. Note, that you need to handle cases with number more than 50.

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

char str[50];

void initStr() {
    memset(str,'*',51);
    // so that one can use printf("%s", str), needed to handle cases N > 50
    str[50] = '\0';
}

void printNstars(int N) 
{
    //handle N > 50, print whole array N div 50 times
    while (N > 50) {
        printf("%s", str); 
        N -= 50;
    }
    
    str[N] = '\0';
    printf("%s\n", str);   
    str[N] = '*';
}

int main()
{
    initStr();
    printNstars(5);
    printNstars(15);
    printNstars(3);    

    return 0;
}
  • Related