Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating an array backwards in For loop condition to stop at 0 when using unsigned integers causing infinite loop

Tags:

c

size-t

I have a loop that has to go from j to 0 (inclusively). My j variable is of type size_t which is usually unsigned.

My code:

#include<stdio.h>
#include<conio.h>

#define SIZE 100

int main(){
    char str[SIZE];
    size_t i=0;
    size_t j;
    puts("Enter any string");
    scanf("%s",str);
    while(str[i]!='\0'){
        i++;
    }


    for(j=i-1;j>=0;j--){

        printf("%c",str[j]);
    }


    getch();
    return 0;
}

I get an infinite loop. If I remove the equality of zero it outputs the reverse of string without the first letter. so what's the problem here?

like image 661
mojtaba al moussawi Avatar asked Jan 25 '16 11:01

mojtaba al moussawi


3 Answers

for(j=i; j>0; j--) {
    printf("%c", str[j-1]);
}

Would be another option.
For a beginner maybe easier to understand.
But the other answers would be better.

edit: i'd say the best would be for(j=i; j-- > 0;) by l3x.
decrementing j after checking if it is greater then 0.

Using a do{}while() loop would also work.

j = i;
do {
   j--;
   printf("%c", str[j]);
} while (j > 0);
like image 106
Flikk Avatar answered Oct 11 '22 12:10

Flikk


size_t is an unsigned integer and it's never going to be less than 0. So the condition in for loop is always true:

for(j=i;j>=0;j--)

You can modify the condition to (a bit ugly though):

for(j=i; j-- > 0;){
   ...
}

Note that in your condition, you are printing the \0 null byte too, which is a non-printable character. (since the j starts with a value equal to the string length). The above condition takes care of that too.

Also:

  • you can use strlen()instead of looping over it yourself.
  • Check the return value of scanf() if input reading wad successful.
like image 6
P.P Avatar answered Oct 11 '22 11:10

P.P


You could change j from size_t to long this makes sure all the data still fits and you can reach the -1 value.

Another option is to end the for loop with the following statement:

for (j = i - 1;;--j)
{
    // code
    if (j == 0) break;
}

as a side-note: your first while loop does the same as the strlen() in string.h.

like image 6
3limin4t0r Avatar answered Oct 11 '22 12:10

3limin4t0r