C program to toggle case of each character in a string

Write a C program to toggle case of each characters of a string using loop. How to change case of each characters of a string in C programming. Program to swap case of each characters in a string using loop in C. Logic to reverse the case of each character in a given string in C program.

Example

Input

Input string: Learn at Codeforwin.

Output

Toggled case string: lEARN AT cODEFORWIN.

Required knowledge

Basic C programming, Loop, String, Function

Must know -

Logic to toggle case of a given string

Below is the step by step descriptive logic to toggle or reverse case of a given string.

  1. Input string from user, store it in some variable say str.
  2. Run a loop from start of the string to the end. Say the loop structure is while(str[i] != '\0').
  3. Inside the loop for each lowercase characters convert it to uppercase and vice versa.

Program to toggle case of a string

/**
 * C program to toggle case of each character in a string
 */

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

/* Toggle case function declaration */
void toggleCase(char * str);


int main()
{
    char str[MAX_SIZE];

    /* Input string from user */
    printf("Enter any string: ");
    gets(str);

    printf("String before toggling case: %s", str);

    toggleCase(str);

    printf("String after toggling case: %s", str);

    return 0;
}


/**
 * Toggle case of each character in given string
 */
void toggleCase(char * str)
{
    int i = 0;

    while(str[i] != '\0')
    {
        if(str[i]>='a' && str[i]<='z')
        {
            str[i] = str[i] - 32;
        }
        else if(str[i]>='A' && str[i]<='Z')
        {
            str[i] = str[i] + 32;
        }

        i++;
    }
}

You can also use pointers in the toggleCase() function, which is pretty much straightforward and optimal. Let us re-write the above toggleCase() function using pointers.

void toggleCase(char * str)
{
    while(*str)
    {
        if(*str >= 'a' && *str <= 'z')
            *str = *str - 32;
        else if(*str >= 'A' && *str <= 'Z')
            *str = *str + 32;

        str++;
    }
}

Output

Enter any string: Learn at Codeforwin.
String before toggling case: Learn at Codeforwin.
String after toggling case: lEARN AT cODEFORWIN.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>