user2980181
user2980181

Reputation:

string reverse with loop and array in c

I just want to reverse a string using for loop and array. Don't want to use any predefined function. I used the following code but its near to nothing. Please share some good suggestions.

int main(){
char a[]="this is a man";
char b[30];
int p= sizeof(a)/sizeof(a[0]);
for(int i=p-1;i>0;i--){
    for(int j=0;j<p;j++){

   b[j]=a[i];
     }
    }

 printf("array is %s",b);
 return 0;
}

Upvotes: 0

Views: 13142

Answers (3)

codeomnitrix
codeomnitrix

Reputation: 4249

#include<stdio.h>

int main(){

char str[] = "str to rev";
char revstr[12]={'\0'};
int i, j;
int length = strlen(str);
j = 0;
for(i = length-1; i>=0; i--){
  revstr[j] = str[i];
  j = j + 1;
}

printf("%s", revstr);

return 0;
}

Upvotes: 0

MOHAMED
MOHAMED

Reputation: 43518

1) In your first for loop, you have to reach 0 (i>=0)

for(int i=p-1;i>=0;i--){

2) The a[p-1] contains the null termination('\0') of your string a[]. And the null termination should not be included in the array reverse procedure. So in your first loop you should start from p-2 and not from p-1.

And after finishing the reversing you have to add a '\0' (null terminator) at the end of your b array

b[j]='\0'; // add this
printf("array is %s",b);
return 0;

3) And as said in the other answers, you have to use only one loop and not 2 loops.

int i,j;
for (i=p-2, j=0; i>=0; i--,j++) {
    b[j]=a[i];
}
b[j]='\0';
printf("array is %s",b);

Upvotes: 1

Abhineet
Abhineet

Reputation: 5389

Using while loop::

void main()
{
 char str[100],temp;
 int i,j=0;

 printf("nEnter the string :");
 gets(str);

 i=0;
 j=strlen(str)-1;

 while(i<j)
     {
     temp=str[i];
     str[i]=str[j];
     str[j]=temp;
     i++;
     j--;
     }

 printf("nReverse string is :%s",str);
 return(0);
}

Using for loop::

void StrRev(char *str)
{
 int i, len, endpos;

 len = strlen(str);
 endpos = len-1;

 for(i = 0; i < len / 2; i++)
 {
   char temp = str[i];
   str[i] = str[endpos - i];
   str[endpos - i] = temp ;
 }
}

Upvotes: 0

Related Questions