C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Toggle case of characters

C Program: Toggle Case of a String (Upper ↔ Lower)

C

#include <stdio.h>

 

int main() {

    char str[200];

    int i;

 

    // Input string

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);

 

    // Toggle case of each character

    for (i = 0; str[i] != '\0'; i++) {

        if (str[i] >= 'A' && str[i] <= 'Z')

            str[i] = str[i] + 32;   // Convert uppercase to lowercase

        else if (str[i] >= 'a' && str[i] <= 'z')

            str[i] = str[i] - 32;   // Convert lowercase to uppercase

    }

 

    printf("Toggled case string: %s", str);

 

    return 0;

}

Output

 
OUTPUT :
Enter a string: It Developer
Toggled case string: iT dEVELOPER

Explanation

  • Each character in the string is examined:
    • If it’s uppercase, it’s converted to lowercase.
    • If it’s lowercase, it’s converted to uppercase.
  • The program uses the ASCII value difference of 32 for conversion.
  • Non-alphabetic characters remain unchanged.