Home > Enterprise >  reversing the string without any predefined function in c
reversing the string without any predefined function in c

Time:03-26

i am using below code, i don't knw what i doing wrong.

#include <stdio.h>
void main()
{

    char a[5];
    char ptr[5] = "hello";
    int i,j,k=0;

    for(i=0;ptr[i] !='\0'&&ptr[i]!=' ';i  ){}
    k=i;
    for(j=0;j<=i;j  )
    {
        a[j] = ptr[k];
        printf("%c %c %d %d %d\n",a[j],ptr[k],i,j,k);
        k--;
    }
    printf("%s %s",a,ptr);
}

Output:

  5 0 5
o o 5 1 4
l l 5 2 3
l l 5 3 2
e e 5 4 1
h h 5 5 0
 hello

CodePudding user response:

I suppose this is what you're looking for.

#include <stdio.h>
int main()
{

    char a[6];
    char ptr[6] = "hello";
    int i,j,k=0;

    for(i=0;ptr[i] !='\0'&&ptr[i]!=' ';i  ){}
    k= i - 1;
    for(j=0;j<i;j  )
    {
        a[j] = ptr[k];
        printf("%c %c %d %d %d\n",a[j],ptr[k],i,j,k);
        k--;
    }
    printf("%s %s",a,ptr);
}

CodePudding user response:

I have edited my answer for undefined length of input string. Have a look :

#include <stdio.h>
#include<string.h>

void main(){
    char a[10];
    char ptr[10];

    scanf("%s", ptr);

    for(int i = 0, j = strlen(ptr)-1; j != -1; i  , j--){
        a[i] = ptr[j];
    }
    printf("%s", a);
}
  •  Tags:  
  • c
  • Related