C Program to Print Reverse Words in a Line String

In this c programming example we will learn how to print reverese words in line string

Algorithm

  1. Take an array of char which we need to print the string words
  2. Calculate length of the char array
  3. take temp array with specified length
  4. Now loop the char array and take individual character and store into temp array
  5. Print the reverse char array

 

Simple C example to print reverse words in line string

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

int string_length(char s[]) {
   int i=0;

   while(s[i]!='\0')
      i++;

   return i;    
}

void string_reverse(char st[]) {
    
   int i,j,len;
   
   char ch;

   j = len = string_length(st) - 1;
   
   i = 0;

   while(i < j) {
       
      ch = st[j];
      
      st[j] = st[i];
      
      st[i] = ch;
      
      i++;
      
      j--;
   }
}

int main (void) {
    
   char line[] = "C Programming Examples for beginners";
  
   int i,j,n;

   n = string_length(line);
   
    char reverse[n],temp[n];
    
    reverse[n]="";

   for(i = 0; i < n; i++) {

      for(j = 0; i < n && line[i]!=' '; ++i,++j) {
          
         temp[j] = line[i];
         
      }
      
      temp[j] = '\0';

      string_reverse(temp);

      strcat(reverse, temp);
      
      strcat(reverse, " ");
   }
   
   printf("Input String - %s\n", line);
   
   printf("Reversed Words String - %s\n",reverse);
   
   return 0;
}

 

Output

Input String - C Programming Examples for beginners

Reversed Words String - C gnimmargorP selpmaxE rof srennigeb  

 

 

Subscribe For Daily Updates