Prepare for your Next Interview
This is a discussion on What am I doing wrong? Please help within the C and C++ forums, part of the Software Development category; Heres the problem i have: Write a program that reads in a line of input and then prints the line out in reverse order. Recall that you can use scanf() ...
|
|||
|
Heres the problem i have: Write a program that reads in a line of input and then prints the line out in reverse order. Recall that you can use scanf() with the %c specifier to read one character at a time from input and that the newline character (\n) is generated when you press the Enter key.
this is the code i have but it doesnt work. what am i doin wrong. Any help would be greatly appreciated. Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char ch[255];
int index, n, i;
for (index = 0; ch[index] != '\n'; index++)
{
scanf("%c", &ch[index]);
}
n = strlen(ch);
for (i = n - 1; i >= 0; i--)
{
printf("%c", ch[i]);
}
system ("pause");
return 0;
}
Last edited by fallenangel1331 : 06-25-2008 at 11:06 PM. |
| Sponsored Links |
|
|||
|
Re: What am I doing wrong? Please help
Here i made some modifications to ur prm.
1.In 1st for loop index value should be decremented,before checking the condition.Bcoz u r doing post increment. 2.In 2nd for loop im using index value instead of n.i value should point to last element in an array.So i value should be decremented twice(i.e. post increment of i and newline character) #include <stdio.h> #include <string.h> int main(void) { char ch[255]; int index, n, i; for (index = 0; ch[index-1]!='\n' ;index++)/* Index value is decremented*/ { scanf("%c", &ch[index]); } // n = strlen(ch); for (i = index - 2; i >= 0;i--) /* Here i is made to point last character*/ { printf("%c", ch[i]); } system ("pause"); return 0; } is it ok? By Mpandi S. |
| The Following User Says Thank You to Muthupandi_s For This Useful Post: | ||
|
|||
|
Re: What am I doing wrong? Please help
i think you are checking the condition after incrementing index , a for loop is essentially :
for (expr1; expr2; expr3) statement is equivalent to expr1; while (expr2) { statement expr3; } hence you are reading into ch[index] while checking for condition at ch[index+1) , try the following : do { scanf("%c", &ch[index]); printf("\n%c", ch[index]); }while( ch[index++] != '\n'); it should work |
![]() |
|
| Thread Tools | |
| Display Modes | |
|
|
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| The decision I have taken is correct or wrong | Hema2007 | Career Advice | 3 | 07-05-2008 01:46 AM |
| Got connected with wrong password | Geek_Guest | Oracle | 2 | 11-09-2007 11:52 PM |
| Whats wrong in this Descriptive Program? | sutnarcha | QTP | 7 | 10-09-2007 07:58 AM |
| QTP- wrong object recognised... | nusezak | QTP | 1 | 02-14-2007 03:37 AM |
| When things go wrong... | Lokesh M | Geeks Lounge | 2 | 12-11-2006 09:09 PM |