- 2072 Kartik · 5 marks
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)
Related questions
- Copy string converting lower to upper using pointer · Computer Programming, chapter 9 · asked 3×
- Rewrite string characters alphabetically · Computer Programming, chapter 7
- Display characters between given ranges · Computer Programming, chapter 5
- Pass student array; display passed students · Computer Programming, chapter 7
- Correct program: character arrays · Computer Programming, chapter 7
- Correct program: case array and average · Computer Programming, chapter 3
- Display N characters using default arguments · Object Oriented Programming, chapter 3
- 8086 ALP: display only alphabetic characters · Microprocessor, chapter 3
- 8086 ALP: alternate case display · Microprocessor, chapter 3
- 8085 ALP: add upper and lower nibbles · Microprocessor, chapter 2