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 |
prog. to produce 1 2 3 4 5 6 7 8 9 10
write a c program to print magic square of order n when n>3 and n is odd?
#define square(x) x*x main() { int i; i = 64/square(4); printf("%d",i); }
4 Answers Google, HCL, Quick Heal, WTF,
How will you print % character? a. printf(“\%”) b. printf(“\\%”) c. printf(“%%”) d. printf(“\%%”)
main() { int i=3; switch(i) { default:printf("zero"); case 1: printf("one"); break; case 2:printf("two"); break; case 3: printf("three"); break; } }
void main() { int i=5; printf("%d",i+++++i); }
#include<conio.h> main() { int x,y=2,z,a; if(x=y%2) z=2; a=2; printf("%d %d ",z,x); }
main() { static int var = 5; printf("%d ",var--); if(var) main(); }
main() { int i=400,j=300; printf("%d..%d"); }
Write out a function that prints out all the permutations of a string. For example, abc would give you abc, acb, bac, bca, cab, cba. You can assume that all the characters will be unique.
5 Answers IITR, Microsoft, Nike,
typedef struct error{int warning, error, exception;}error; main() { error g1; g1.error =1; printf("%d",g1.error); }
#define clrscr() 100 main() { clrscr(); printf("%d\n",clrscr()); }