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 |
What is "far" and "near" pointers in "c"...?
What is your nationality?
main() { int i = 0xff ; printf("\n%d", i<<2); } a. 4 b. 512 c. 1020 d. 1024
#define max 5 #define int arr1[max] main() { typedef char arr2[max]; arr1 list={0,1,2,3,4}; arr2 name="name"; printf("%d %s",list[0],name); }
given integer number,write a program that displays the number as follows: First line :all digits second line : all except the first digit . . . . Last line : the last digit
There were 10 records stored in “somefile.dat” but the following program printed 11 names. What went wrong? void main() { struct student { char name[30], rollno[6]; }stud; FILE *fp = fopen(“somefile.dat”,”r”); while(!feof(fp)) { fread(&stud, sizeof(stud), 1 , fp); puts(stud.name); } }
C program to print magic square of order n where n > 3 and n is odd
Program to find the largest sum of contiguous integers in the array. O(n)
typedef struct error{int warning, error, exception;}error; main() { error g1; g1.error =1; printf("%d",g1.error); }
Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list)
3 Answers Disney, Google, ZS Associates,
main() { printf("%d", out); } int out=100;
void main() { while(1){ if(printf("%d",printf("%d"))) break; else continue; } }