1

I found this program for reversing this program online.

I have just started learning C.

I am not able to understand few things here.

  1. Why while is ended with ;
  2. what does while(str[++i]!='\0'); mean?
  3. Is rev[j++] = str[--i]; same as writing j++; and i--; inside the while loop?

This is the program:

#include<stdio.h>
int main(){
    char str[50];
    char rev[50];
    int i=-1,j=0;

    printf("Enter any string : ");
    scanf("%s",str);

    while(str[++i]!='\0');

    while(i>=0)
     rev[j++] = str[--i];

    rev[j]='\0';

    printf("Reverse of string is : %s",rev);

    return 0;
}
Shafi
  • 1,850
  • 3
  • 22
  • 44
  • Perhaps this question will clear up "++i" and "i++" conventions: http://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i – user161778 Apr 09 '16 at 14:14
  • --i means i is decreased before the whole expression is completed, i-- means i is decreased after the whole expression is completed. – totoro Apr 09 '16 at 14:14
  • Please always use braces. It saves a possible error in the future. – Ed Heal Apr 09 '16 at 14:28

8 Answers8

4
    while(str[++i]!='\0');

is equivalent to

    while(str[++i]!='\0')
       /*do nothing*/;

which is equivalent to

    ++i;
    while (str[i]!='\0') {
      ++i;
    }

and

    while(i>=0)
      rev[j++] = str[--i];

is equivalent to

    while (i>=0) {
        --i;
        rev[j] = str[i];
        ++j;
    }

Note that i is decremented before the statement since --i is a pre-decrement, whereas j is incremented after the statement since j++ is a post-increment.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
2

I'll try to answer as best as i can...

  1. Why while is ended with ;

This is valid syntax, it's often used to cause the program to wait at that line until a certain flag is set in an embedded scenario. In this case it's used to find the length of the string. All strings are terminated with a null character, which is '\0', and the preincrement on i means that after that line i will hold the value for the length of the string. Effectively its equivalent to this:

/* If the ith position of the string is not the end */
 while (str[i] != '\0') {
     /* Increment i and repeat */
     i = i + 1;
}

The main concept here is the difference between postincrement and preincrement operators - might be worth reading up on that.

  1. What does while(str[++i]!='\0'); mean?

See above.

3.Is rev[j++] = str[--i]; same as writing j++; and i--; inside the while loop?

If you're asking if its in the while loop, its entirely equivelant to:

while(i>=0) { rev[j++] = str[i--]; }

Since there is only a single operation in the while loop the brackets aren't needed. Just a note, and this is entirely subjective, but the majority of coding standards I've come accross use brackets even in this scenario.

Your questions seem to be related mainly to the syntax of C - it might be worth getting a book out or watching some tutorials to familiarise yourself with it.

S.Curly
  • 31
  • 6
1
  1. The ; is there to close the loop
    2: while(str[++i]!='\0'); means "Go throuch each char of str until the \0 char is reached".\0 is the ending char of a string
    3: Yes
BPC
  • 96
  • 1
  • 8
0

First of all, while(str[++i]!='\0'); increments i until it finds the last character. In C all strings end with \0 or NULL (both are the same).

The second one, no. It is not the same --i than i++.

Check the following code snipet:

int a,b,x=10,y=10;

a = x--;
b = --y;

At the end of execution, a = 10 but b = 9. This is because --y is a pre-decrement. It decrements the value first and then assigns its value to b.

Felipe Sulser
  • 1,185
  • 8
  • 19
0

Here's a commented version of the program:

// Include standard input output functions
#include<stdio.h>
// declares the main function. It accept an undefined number
// of parameters but it does not handles them, and returns an integer
int main(){
    // declares tho arrays of 50 characters initialized with random values
    char str[50];
    char rev[50];
    // declare and initialize two integer variables
    int i=-1,j=0;

    printf("Enter any string : ");
    scanf("%s",str);

    // executes the ';' instruction while the condition is satisfied.
    // ';' is an empty statement. Thus do nothing.
    // The only action executes here, is the increment of the i variable with
    // a preincrement. Because the i variable was initialized with
    // -1, the first control start checking if str[0] != '\0'
    // If the  post increment operator was used, the variable must
    // have been initialized with 0 to have the same behaviour.
    while(str[++i]!='\0');

    // at the end of the previous while, the i variable holds the
    // str lenght + 1 (including the '\0')

    // starting from the end (excluding the '\0', using the pre-decrement on the i variable)
    // assign to rev[j] the variable of str[i], then (post increment)
    // increment the j variable
    while(i>=0)
     rev[j++] = str[--i];

    // now j is equals to str lenth +1
    // therefore in this position add the null byte
    rev[j]='\0';

    // print result
    printf("Reverse of string is : %s",rev);

    // return 0 to the OS
    return 0;
}
nessuno
  • 26,493
  • 5
  • 83
  • 74
0
  1. ; means the end of a statement in c.

    while(condition)
    {
        //do something
    }
    

    do something means at least one statement should be executed. For this the ; is used here.

  2. while(str[++i]!='\0'); '\0' represents end of the string. Here the loop is terminated at the end of the string and ++i increases i.

  3. Is rev[j++] = str[--i]; same as writing j++; and i--; inside the while loop?
    Yes. But as --i increases i before executing rev[j++] = str[--i] so i-- should be before rev[j] = str[i] and j++ increases j after executing rev[j++] = str[--i] so j++ should be after rev[j] = str[i]

Shafi
  • 1,850
  • 3
  • 22
  • 44
0

The key here is understanding the difference in behaviour between prefix (++i), and postfix (i--) operators.

The prefix operator will increment its operand (i), and then evaluate to the new value.

The postfix operator will evaluate to its operands current value, and then increments the operand afterwards.

As for:

int i = -1;

while (str[++i] != '\0');

This is a loop with no block, because all of the statements can be expressed in the conditional. On each iteration:

  • Increment i by one.
  • Get the char at the position i evaluates to.
  • continue if it is not the NUL character.

This might be better understood when written as:

int i = -1;

do {
  i++;
} while (str[i] != '\0');

The result of this operation is that i now holds the position of the NUL character in the string, since all valid character strings must end with the NUL character.

In the next section of the program, the prefix operator is used again to immediately get the character one position before the NUL character, and then one position before that, and so on, until we get the first character of the string, and then we're done.

while(i>=0)
     rev[j++] = str[--i];
Oka
  • 23,367
  • 6
  • 42
  • 53
0
  1. Why while is ended:

    while(str[++i]!='\0')

Once str is an asciiz string it ends with a '\0' character. So while will end whenever the while reaches the end of the string.

  1. The line above means:

=> ++i : Increments the string index before getting the corresponding character.

=> Checks if str[index] != '\0' // End of the string reached

On the end of while the i variable will contain the string length (excluding the '\0' character).

It would be easier to use this:

i = strlen(str);
  1. Is rev[j++] = str[--i]; same as writing j++; and i--; inside the while loop?

No.

This line is the same as:

while(i>=0)
{
    i = i - 1;
    rev[j] = str[i];
    j = j + 1;
}

--i : Gets the string character after decrementing i. If you changed to i-- the code would get the str[i] before decrementing i, but it is not what you want.

Jorg B Jorge
  • 1,109
  • 9
  • 17