×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to reverse every word of the given string

Here, we are going to learn how to reverse every word of the given string in C programming language?
Submitted by Nidhi, on July 17, 2021

Problem statement

Read a string and then reverse every word of the given string using C program.

C program to reverse every word of the given string

The source code to reverse every word of the given string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to reverse every word of given string

#include <stdio.h>
#include <string.h>

int main()
{
    char str[64];
    char words[6][10];
    char temp;

    int i = 0;
    int j = 0;
    int k = 0;
    int ii = 0;
    int l = 0;

    printf("Enter string: ");
    scanf("%[^\n]s", str);

    while (str[i] != 0) {
        if (str[i] == ' ') {
            words[k][j] = '\0';
            k++;
            j = 0;
        }
        else {
            words[k][j] = str[i];
            j++;
        }
        i++;
    }
    words[k][j] = '\0';

    for (i = 0; i <= k; i++) {
        l = strlen(words[i]);

        for (j = 0, ii = l - 1; j < ii; j++, ii--) {
            temp = words[i][j];
            words[i][j] = words[i][ii];
            words[i][ii] = temp;
        }
    }

    printf("Result: \n");
    for (i = 0; i <= k; i++)
        printf("%s ", words[i]);
}

Output

RUN 1:
Enter string: Hello World
Result: 
olleH dlroW

RUN 2:
Enter string: Google Yahoo Bing
Result: 
elgooG oohaY gniB 

RUN 3:
Enter string: IncludeHelp.com
Result: 
moc.pleHedulcnI 

Explanation

In the main() function, we created a string str and read the value of str from the user. Then we reverse each word of the string and print the result on the console screen.

C String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.