Kawsar_Ahmed Kawsar_Ahmed - 1 day ago 4
C Question

How does this conditional part work?

In this program, there are two

for
loops. In every
for
loop the conditional part is
text[i][0]
and
text[i][j]
. I don't understand this kind of conditional part. How is this is run or how does it work?

#include<stdio.h>

int main(void)
{
char text[][80] = {

"When","in","the",
"course","of","human",
"events",""
};

int i,j;

for(i=0; text[i][0]; i++){
for(j=0; text[i][j]; j++)
printf("%c", text[i][j]);
printf(" ");
}

printf("\n%c", text[0][0]);

return 0;
}

Answer

In all loops, the test is whether or not the condition evaluates to true; the loop continues unless the condition evaluates to false or zero.

In the first loop, the condition is equivalent to:

test[i][0] != 0

which might also be written:

test[i] != '\0'

since test[i] is a char * and test[i][0] is the first character in the string and the data is initialized with an empty string "" as the last entry in the array, so the only character in that string is '\0'.

In the second loop, the condition checks whether:

test[i][j]` != 0;   // Or '\0'

This evaluates to false when the end of the string is reached. The whole of the inner loop would be better replace by a simple:

printf("%s ", test[i]);

It might be better to omit the trailing blank; there are many ways to do that, but they all involve a test or assignment.

Comments