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.
Answers were Sorted based on User's Feedback
/*in 2n comparisons*/
#include<iostream.h>
#include<string.h>
#include<stdio.h>
int count=0;
void rev_word(char str[20],int m,int n)
{
int i,l,k;
k=n-m+1;
if(k%2==0)
l=(k/2-1);
else
l=k/2;
k=n;
for(i=m;i<=m+l;i++)
{
char t=str[i];
str[i]=str[k];
str[k]=t;
k--;
}
}
int main()
{
char str[100];
int i,j=0;
cout<<"\n\nenter string:";
gets(str);
rev_word(str,0,strlen(str)-1);
for(i=0;i<=strlen(str);i++)
{
if(str[i]==' '||str[i]=='\0')
{
rev_word(str,j,i-1);
j=i;
while(str[j]==' ')
j++;
i=j;
}
}
cout<<"\n\nsentence with order of words reversed is:";
cout<<str;
return 0;
}
Is This Answer Correct ? | 2 Yes | 0 No |
Answer / prabhakar
//Simple String Reverse
#include<stdio.h>
#include<string.h>
char str1[50],str2[50];
main()
{
printf("\nEnter The String:");
gets(str1);
rev(str1);
}
rev(char s[20])
{
int i=0,a=0,j=0,k=0;
a=strlen(s);
b:
a--;
while(s[a]!=' '&a>=0)
{
str2[i]=s[a];
a--,i++;
}
str2[i]='\0';
j=strlen(str2)-1;
while(str2[k]!='\0')
{
printf("%c",str2[j]);
j--,k++;
}
printf(" ");
if(a>=0)
{
goto b;
}
printf("\n\n");
}
Is This Answer Correct ? | 0 Yes | 0 No |
#include"math.h" void main() { printf("Hi everybody"); } if <stdio.h> will be included then this program will must compile, but as we know that when we include a header file in "" then any system defined function find its defination from all the directrives. So is this code of segment will compile? If no then why?
main() { float i=1.5; switch(i) { case 1: printf("1"); case 2: printf("2"); default : printf("0"); } }
void main() { int *mptr, *cptr; mptr = (int*)malloc(sizeof(int)); printf(ā%dā,*mptr); int *cptr = (int*)calloc(sizeof(int),1); printf(ā%dā,*cptr); }
how to delete an element in an array
Write a program to receive an integer and find its octal equivalent?
main() { char p[ ]="%d\n"; p[1] = 'c'; printf(p,65); }
Program to find the largest sum of contiguous integers in the array. O(n)
create a C-code that will display the total fare of a passenger of a taxi if the driver press enter,the timer will stop. Every 10 counts is 2 pesos. Initial value is 25.00
Is the following code legal? struct a { int x; struct a *b; }
main() { int i=10; i=!i>14; Printf ("i=%d",i); }
int i=10; main() { extern int i; { int i=20; { const volatile unsigned i=30; printf("%d",i); } printf("%d",i); } printf("%d",i); }
find A^B using Recursive function