Logic to reverse string in c programming

WBahn

Joined Mar 31, 2012
33,016
Does it look better
It's better, but it still isn't formatted particularly well.

But notice the huge, glaring difference between the original code and your new code.

To help you see it, I've properly formatted both:

Here's the revised version:

C:
/*
Program  - Reverse String
Author   - Parth
Language - C Language
Date     - 09/02/2018
IDE      - GCC
*/

#include <stdio.h>

int main(void)                 
{
    char number [10];
    char reverse[10];

    printf("Enter the Number = ");

    scanf("%s",number);

    int i = -1;
    int j =  0;

    while (number[++i] != '\0')
        ; // Empty loop
 
    while (i >= 0)
    {
        reverse[j++] = number[--i];
        reverse[j] = '\0';
    }

    printf("Reverse of  a string = %s",reverse);

    return 0;
}
And here's the original code.

C:
#include <stdio.h>

int main(void)
{

    char number [10];
    char reverse[10];

    printf("Enter the Number = ");

    scanf("%s",number);

    int i=-1;
    int j=0;

    while(number[++i]!='\0')
        ; // Empty loop
     
    while(i >= 0)
        reverse[j++] = number[--i];

    reverse[j] = '\0';

    printf("Reverse of  a string = %s",reverse);

    return 0;
}
Do you see the difference?

In this version the line "reverse[j] = '\0';" is NOT in the loop. It only looks that way because of the sloppy formatting. In your new code, by taking the time to format it, you realized that if how it appeared is what you wanted, that you needed to enclose both statements in curly braces.

But that leaves the question of whether the original code that you copied from someplace MEANT to have that line in the loop of not. If it did, then your original formatting led you to think that you had put it in the loop when in reality you hadn't. If it didn't, then the sloppy formatting led you to think that it was and led you to "fix" the code while, in reality, you were messing it up.

Do you start to see why we are always after you to properly format your code?

It turns out, in this case and purely by coincidence, that either way works. Can you see and explain why?
 
Last edited:

Thread Starter

Parth786

Joined Jun 19, 2017
642
It's better, but it still isn't formatted particularly well.

Do you start to see why we are always after you to properly format your code?
Thanks a lot for helping me Did you see my post #17 I tried my best to properly format code But still I made a mistake

You spent a lot of time on me to help me I feel bad when I do not give the results as per your expectations. I am curious to know about my performance Am I average learner or too poor. Can you tell me whether I am improving my programming skill's or not.
 
Top