What am I doing wrong? Please help
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;
}
[/CODE]
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.
Re: What am I doing wrong? Please help
Thank you very much Muthupandi_s it worked great. I really apriciate it. It works great.
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