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.



Input string: Learn at Codeforwin.


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: ");

    printf("String before toggling case: %s", 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;


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)
        if(*str >= 'a' && *str <= 'z')
            *str = *str - 32;
        else if(*str >= 'A' && *str <= 'Z')
            *str = *str + 32;



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

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols. as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>