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.

Example:
Input string: I love C programming!
Output: i LOVE c PROGRAMMING!

Required knowledge

Basic C programming, Loop, String, Function

Program to toggle case of each character

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

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


/* Function declaration */
void toggleCase(char * string);



int main()
{
    char string[MAX_SIZE];
    int i = 0;

    /* Reads a string from user */
    printf("Enter any string: ");
    gets(string);

    printf("String before toggling case: %s\n", string);

    toggleCase(string);

    printf("String after toggling case: %s\n", string);

    return 0;
}




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

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

        i++;
    }
} 


Output
Enter any string: I love C programming!
String before toggling case: I love C programming!
String after toggling case: i LOVE c PROGRAMMING!

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment