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 |
main() { int i=0; while(+(+i--)!=0) i-=i++; printf("%d",i); }
9 Answers CSC, GoDB Tech, IBM,
program to find magic aquare using array
1 o 1 1 0 1 0 1 0 1 1 0 1 0 1 how to design this function format in c-language ?
Is the following statement a declaration/definition. Find what does it mean? int (*x)[10];
#include<stdio.h> main() { struct xx { int x=3; char name[]="hello"; }; struct xx *s; printf("%d",s->x); printf("%s",s->name); }
main( ) { void *vp; char ch = ‘g’, *cp = “goofy”; int j = 20; vp = &ch; printf(“%c”, *(char *)vp); vp = &j; printf(“%d”,*(int *)vp); vp = cp; printf(“%s”,(char *)vp + 3); }
main() { char *p; p="%d\n"; p++; p++; printf(p-2,300); }
How we will connect multiple client ? (without using fork,thread)
#define assert(cond) if(!(cond)) \ (fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\ __FILE__,__LINE__), abort()) void main() { int i = 10; if(i==0) assert(i < 100); else printf("This statement becomes else for if in assert macro"); }
void main() { int *i = 0x400; // i points to the address 400 *i = 0; // set the value of memory location pointed by i; }
why do you use macros? Explain a situation where you had to incorporate macros in your proc report? use a simple instream data example with code ?
main() { int *j; { int i=10; j=&i; } printf("%d",*j); }