0

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;
}
3
  • As a starter, you should use strlen to find string length. Besides you can solve this question without the inner for loop. Commented Dec 5, 2013 at 7:56
  • Please post the erroneous output you get. Commented Dec 5, 2013 at 7:57
  • i should go on until i>=0 unless you want to omit the first character Commented Dec 5, 2013 at 7:57

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0
#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;
}

3 Comments

What is myStrLen? You should define that as well, else this code will not link.
@Anishsane: the person don't want to use built in function so he can make up his own version of myStrLen I believe
strlen is to be used and char revstr[12]={'\0'}..other then this.every thing is fine..thanks buddy..
0

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 ;
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.