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?
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);
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:
strlen()
instead of looping over it yourself.scanf()
if input reading wad successful.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With