Skip to main content

Convert case based on first character

Short answer

The function checks first character: if islower(s[0]), all characters converted with toupper(); else with tolower(). The word is read in main(), modified in place, and displayed.

Write a program to read a word from a main function, pass it into a function that will convert all of its characters into upper case if the first character is in lower case and into lower case if the first character is in upper case. Display the converted string from main function.

Logic. convert() first checks the first character: islower(s[0]). If it is lower case, every character is changed with toupper(), otherwise with tolower(). The word is read in main(), converted in the function (the array is passed by address) and displayed in main().

#include <stdio.h>
#include <ctype.h>

void convert(char s[])
{
    int toUpper = islower((unsigned char)s[0]);   /* decided by first character */
    for (int i = 0; s[i] != '\0'; i++)
        s[i] = toUpper ? toupper((unsigned char)s[i]) : tolower((unsigned char)s[i]);
}

int main(void)
{
    char w[50];
    printf("Enter a word: ");
    scanf("%49s", w);
    convert(w);
    printf("Converted: %s\n", w);
    return 0;
}

Sample run

Input: hELlo

Enter a word: Converted: HELLO

Because the first letter h is lower case, the whole word becomes upper case. For an input such as Hello the result would be hello.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →