Lucas Pontes
Lucas Pontes

Reputation: 33

C: How to add a character to another character / set of characters?

Let's say I have a char with a value of 42 (*). I need to print this character in n lines, with n defined by the user. However, for each line shift, another * must be printed. If the user inputs "6", then the result would be like that:

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

I was thinking of making the program repeat the print and jump a line n times, adding another * to the char at the end of each loop. Is there any command that would turn * into ** and then into * and so on?

Upvotes: 0

Views: 237

Answers (3)

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

Try this:

 void print_n_chars(char c, size_t count)
 {
     char *buffer;
     size_t i;

     buffer = malloc(count + 1);
     memset(buffer, 0, count + 1);

     for (i = 0; i < count; i++)
     {
         buffer[i] = c;

         printf("%s\n", buffer);
     }

     free(buffer);
 }

This algorithm has O(n) performance, which is better then O(n^2/2) with two loops.

Edit: fixed name typo, added performance comments

Upvotes: -1

karan
karan

Reputation: 8853

you can use nested for loop for this purpose...

for(i=0;i<n;i++)     //n is your user value
{
    for(j=0;j<=i;j++)
         {
          printf("%c",your_char);     //print char here
         }
    printf("\n");                    //for going to next line
}

the top for loop will handle the row while the inner for loop will deal with the column...

Upvotes: 2

jwodder
jwodder

Reputation: 57590

You don't need to do any string manipulation. For each line, if the line number is i, just print out a single asterisk (with putchar() or the like) i times, followed by a newline.

Upvotes: 7

Related Questions