Skip to main content

Display characters between given ranges

Short answer

Read two characters, swap if out of order, then loop from start to end printing each character separated by spaces.

Write a C program to display all characters between a given ranges.

Characters are stored as ASCII codes, so a char variable can be used in a for loop like an integer. The loop starts at the first character and goes up to the last one, printing each. If the user gives the range in reverse order, the two are swapped.

#include <stdio.h>
int main(void)
{
    char start, end, ch;
    printf("Enter starting and ending characters: ");
    scanf(" %c %c", &start, &end);
    if (start > end)
    {
        ch = start; start = end; end = ch;   /* swap if given in reverse */
    }
    for (ch = start; ch <= end; ch++)
        printf("%c ", ch);
    printf("\n");
    return 0;
}

Output for the range D to L:

Enter starting and ending characters: D E F G H I J K L

The same program with a and e prints a b c d e, and with 0 and 9 prints the digits.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →