Given an array of characters which form a sentence of
words, give an efficient algorithm to reverse the order of
the words (not characters) in it?

Answer Posted / abdur rab

#include <stdio.h>

void reverse_string ( char* cp_string, int start, int end )
{
if ( cp_string && ( start < end ) ) {
*( cp_string + start ) ^= *( cp_string +
end )
^= *( cp_string + start ) ^= *(
cp_string + end );
reverse_string ( cp_string, ++start, --
end );
}
}


int main ( int argc, char* argv [] )
{
char ca_array [12]={"Hello World"};
char* cp_ptr = NULL;
char* cp_ptr_temp = NULL;

printf ( "\n Before Reverse :%s", ca_array );

reverse_string ( ca_array, 0, strlen ( ca_array ) -
1 );

cp_ptr_temp = cp_ptr = ca_array;
while ( NULL != ( cp_ptr_temp = (char*) strchr (
cp_ptr_temp, ' ' ) ) ) {
reverse_string ( cp_ptr, 0, ( cp_ptr_temp -
cp_ptr ) - 1 );
cp_ptr = ++cp_ptr_temp;
}
// change the final word
reverse_string ( cp_ptr, 0,
( ( strlen ( ca_array ) - 1 ) - (
cp_ptr - ca_array ) ) );

printf ( "\n After Reverse by Words :%s",
ca_array );
return ( 0 );
}

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain which of the following operators is incorrect and why? ( >=, <=, <>, ==)

594


When is the “void” keyword used in a function?

816


What is C language ?

1514


What is null pointer in c?

579


write a c programming using command line argument,demonstrate set operation(eg;union,intersection,difference) example output is c:>setop 12 34 45 1 union 34 42 66 c:>setop 12 34 1 42 66 c:>setop 12 34 diff 12 56 67 78 setop 12 34

1616






Can main () be called recursively?

613


Describe how arrays can be passed to a user defined function

765


Why is struct padding needed?

619


Find the second largest element in an array with minimum no of comparisons and give the minimum no of comparisons needed on an array of size N to do the same.

700


Is a house a mass structure?

632


i have to apply for rbi before that i need to know the the syllabus for the entrance questions. whethet it may be aps or techinical

1823


What is && in c programming?

663


Can you mix old-style and new-style function syntax?

648


write a c program thal will find all sequences of length N that produce the sum is Zero, print all possible solutions?

2394


What is file in c language?

566