How can I reverse an array of characters in c language

Reversing an array of characters https://code.sololearn.com/cNbKE9Lav9YG/?ref=app

15th Oct 2020, 11:10 PM
Amal Gil
Amal Gil - avatar
4 Answers
+ 2
#include<stdio.h> #include<stdlib.h> #include<string.h> int main(){ int i,j,tmp; char str[20]; printf("enter name:"); scanf("%s",str); for(i=0,j=strlen(str)-1;i<j;i++,j--){ tmp=str[i]; str[i]=str[j]; str[j]=tmp; } for(i=0;i<strlen(str);i++) printf("%c",str[i]); }
15th Oct 2020, 11:20 PM
Bahhaⵣ - avatar
+ 1
for( i = 0.......) last for(..... i < strlen(str).....) without - 1 last printf : printf("%c"....)
15th Oct 2020, 11:22 PM
Bahhaⵣ - avatar
16th Oct 2020, 3:45 PM
Briana - avatar
Bahha🐧 's answer is good, but I recommend to store strlen(str) in a variable (in the last for loop), otherwise it will keep calling the function over and over again, it' s different with the first forloop where the length of str stored in j (strlen only called once). This might not be a problem for you if time complexity is not in your concern.
17th Oct 2020, 2:35 AM
LastSecond959 - avatar