C - Multiply char by int

26,157

Solution 1

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

Solution 2

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.

Share:
26,157
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    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.

  • Grzegorz Szpetkowski
    Grzegorz Szpetkowski over 9 years
    In C character constants are of type int. You probably confusing with C++.
  • ftynse
    ftynse over 9 years
    Well, I may have oversimplified. But an explanation of what is an implementation-defined behavior and how it is supposed to work for 'ab' or for multibyte characters does not belong to this question. For curious, stackoverflow.com/questions/20764538/type-of-character-const‌​ant
  • Tim Čas
    Tim Čas over 9 years
    @ftynse: Type of character constants is not implementation-defined. It is always int (C99, 6.4.4.4p10); for wide constants, it is wchar_t (p11).
  • chux - Reinstate Monica
    chux - Reinstate Monica over 9 years
    @ftynse The sizeof('a') == sizeof(int) - this is not a implementation-defined behavior issue. "An integer character constant has type int."
  • Arkku
    Arkku over 9 years
    Using printf to in a loop to print individual characters is overkill; here putchar would suffice.
  • Admin
    Admin over 9 years
    Even though I chose another answer to my question, I did like your explanation. Thank you!
  • Admin
    Admin over 9 years
    Never knew of the putchar function before now, Thanks!