1

I've been given the pretty simple task of writing a program that will take two characters and then print the letters inbetween them using a for() loop.

Here's my code:

#include <stdio.h>
int main() {
char a, b;

printf("\nEnter the first character: ");
scanf("%c", &a);

printf("\nEnter the second character: ");
scanf("%c", &b);

for(char i = a; i <= b; i++) {
    printf("%c ", i);
}

return 0;
}

When I run it, I am prompted to enter the first character correctly but when I press enter it only runs the next printf() and then terminates.

No errors or warnings or anything on compilation. Another similar question I found that was apparently solved does not work for me either.

Thanks in advance.

Trekkx
  • 113
  • 1
  • 7

2 Answers2

2

You have to consume the \n in stdin left by first scanf.

Fastest fix

scanf(" %c", &b);

The space before %c tells to scanf to ignore all whitespaces before to read the char.

LPs
  • 16,045
  • 8
  • 30
  • 61
0

If I read your code correctly, by pressing enter, you would enter the second character, which would most probably (depending on the environment) start with a numeric value of 13, which would be smaller than any letter, so the loop's body is executed only once.

Codor
  • 17,447
  • 9
  • 29
  • 56