Argarak
Argarak

Reputation: 93

C - Multiply char by int

Before I ask my question let me just say that I am a newbie to C, and do not know how to do a lot in it.

Anyway, the problem is that I need to print a specific number of characters. I first used Python, because that was a language that I was familiar with, and wrote this very simple program.

x = 5    
print('#' * x)

This is what I want to achieve, but in C. Sorry if this is a duplicate or a stupid question, but I have been puzzled and without answers, even after looking on the internet.

Upvotes: 8

Views: 36582

Answers (3)

bottaio
bottaio

Reputation: 5093

First of all, use printf function. It allows you to format your output in the way you like. The way to get result you required is a for loop.

int i, x = 5;
for (i = 0; i < x; i++)
    printf("#");

Upvotes: 0

M.M
M.M

Reputation: 141638

for ( size_t ii = 0; ii < 5; ++ii )
    putchar('#');

Upvotes: 5

ftynse
ftynse

Reputation: 797

Use a loop to print it multiple times.

In C, a symbol between '' has a type char, a character, not a string. char is a numeric type, same as int but shorter. It holds a numerical representation of the symbol (ASCII code). Multiplying it with an integer gives you an integer.

A string, contained between "" is an array of characters. The variable will store a pointer to the first character.

Upvotes: 4

Related Questions