There was an example in my book where it was asked to write a program that prints the number 1 to 100 using 5 columns (Have each number separated from the next by a tab). The solution was as following:
#include "stdio.h"
int main()
{
int i;
for(i=1; i<=100; i++) {
printf("%d\t", i);
if((i%5)==0) printf("\n");
}
return 0;
}
But I can't understand the if((i%5)==0) printf("\n"); statement. Could you explain it for me?
The % operator is the modulus operator (integer division's remainder). So every five loop iterations, your program will output a \n character (new line).
Values will be:
Iteration i%5 value
i=1 1
i=2 2
i=3 3
i=4 4
i=5 0
i=6 1
i=7 2
i=8 3
i=9 4
i=10 0
So, every five prints, a \n (new line) will be printed to the standard output.
Hope it helps.
The if condition checks if the number represented by i is divisible by 5 .
5 % 5 = 0 // remainder
5 / 5 = 1 // quotient
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