+ 2

Can you guide me where am i going wrong

This program is to print reverse of string https://code.sololearn.com/cTGwghAJPbzj/?ref=app

11th Sep 2020, 2:27 PM
Prashant Pandey
Prashant Pandey - avatar
9 Réponses
+ 3
#include <stdio.h> #include<string.h> int main() { int i,j=0,p; char s[100],rev[100]; printf("enter your string:"); //gets(s); //gets works but use fgets fgets(s,100,stdin); p=strlen(s);//s[p] ='\0'; printf("length=%d",p); for(i=p-1;i>=0;i--) //I = p-1 must { //while(j<p-i) //you don't added braces to include j++ so it's infinite loop, i added, but actually no need of while loop here.. So causing to fail the code actually... { rev[j]=s[i]; j++; } } printf("your rev string is:%s",rev); return 0; }
11th Sep 2020, 2:41 PM
Jayakrishna 🇮🇳
+ 1
take the code jayakrishna posted and add rev[p]=0; to end the string
11th Sep 2020, 3:06 PM
Nils R
Nils R - avatar
0
Thanks
11th Sep 2020, 2:51 PM
Prashant Pandey
Prashant Pandey - avatar
0
Okay nils thanks nils
11th Sep 2020, 3:19 PM
Prashant Pandey
Prashant Pandey - avatar
0
Can you tell me Jayakrishna🇮🇳 why is while loop not working or why while is causing trouble please
11th Sep 2020, 3:19 PM
Prashant Pandey
Prashant Pandey - avatar
0
the while loop would start in the first itaration of your for loop, then execute until j becomes p. after that every iteration of your for loop does nothing because yor while condition is always false. i see what you intended, but you don't need the while loop and its condition because in the last iteration of Jayakrishna's for loop j will be p and execution stops after that.
11th Sep 2020, 3:28 PM
Nils R
Nils R - avatar
0
Thanks nil
11th Sep 2020, 3:39 PM
Prashant Pandey
Prashant Pandey - avatar
0
Prashant Pandey I already added explanation in code as comments... In your original code, you don't have any braces around while, so only next one statement belong to while so j++ not belong while so condition is true always, makes infinite loop.. Check again that.. In the code above, I put braces, the while condition is j<p-I, only adding one to j condition becoming false.. Only there is only one iteration happening, hence no need of loop.. So I commented. Without or with while is same there...
11th Sep 2020, 6:44 PM
Jayakrishna 🇮🇳
0
Thanks
12th Sep 2020, 1:42 AM
Prashant Pandey
Prashant Pandey - avatar