How to loop a Char using WHILE

Hello everyone,
i need some help. How do i use a WHILE loop on a Char . e.g,
if i want to loop a char string ‘-’ 20 times

char dash = ‘-’;
while(dash <= 20) {

printf("%c\n", dash);
dash++;
}
The above code wont run. pls help

Do you want dash printed 20 times?

Currently the code doesn’t run because the ascii value of '-' is 45, which is already more than 20. We can check this with printf("%d\n", '-');

If you want to print the string 20 times you’ll need a value set to 0. Alternatively if you want to print the char 20 times, and increment each time, you could have your condition be something like dash <= '-' + 20

Hello there, thanks for your time. Using the second option you stated prints out numbers and not the Char ‘-’ 20 times. This dash line below is what i am trying to achieve.

--------------------.

many thanks

The point is that it prints numbers. Behind the scenes the character '-' is just the number 45.
Using it as the variable in your loop the loop will never run because 45 is not less than or equal to 20. You’ll need to store the character separate from the variable being used in the loop.

One other point is that your printf() has a newline character in it so you won’t get that dash.

It does beg the question why your using a loop as opposed to puts("--------------------");?
But that’s just a curiosity.

Thank you. I have just started learning C in school and part of my assignment is to loop ‘-’ 20 times.
According to you, if i store char ‘-’ in a separate variable, the how do i link it to the say ‘number’ variable that will loop 20 times. it seems confusing

Oof, if this is part of school assignment, we can’t help with it here.

No problem, i will get there
I thank you anyway

1 Like