fahima chowdhury fahima chowdhury - 6 days ago 4x
C Question

Working process of logical NOT operator in if(!(i%6))

int main(void)


int i;
char ch;

/*display all numbers that are multiples of 6*/
for(i=1; i<10000; i++){
printf("%d, more?(Y/N)", i);
ch= getche();
if(ch=='N')break; /* stop the loop*/

return 0;

Aim of program: Program will print multiple of 6. And a key press can stop the execution of the program.

How program works: In for loop, system will check value of i against the given condition. If the value of i is smaller than 10000, statements under for will be executed.
The first statement under for loop is a if statement. When the condition of if statement is true, all the statements under if will be executed. Again, when the condition becomes false, all statements will skipped.

For example: when i = 6, system will check against the condition in for. It is true 6 is smaller than 100000. Next if statement will start execution. If if statement becomes true then value of i will print by the system.

My question: What is exactly the meaning of the condition in if(!(i%6))? How it's check whether value of i is multiple of 6 or not?

Thank you in advance.


The if statement requires an expression that gives a boolean value. When a numerical value is converted to a boolean value, 0 becomes false and any other value becomes true. So, in

if (i % 6)

do_it() will be executed whenever the value of i % 6 is not zero, i.e., for all values of i that are not divisible by 6.

Adding the negation produces the opposite result:

if (!(i % 6))

when i % 6 is 0, the boolean value of the remainder is false, and the negation, effectively !0, is true; when i % 6 is not 0, the boolean value of the remainder is true, and the negation is false. So do_it() will be called whenever i % 6 is 0, i.e., for all value of i that are divisible by 6.