Problem with if statement

In my book there was an example where it was proposed to write a program that prints a number from 1 to 100 using 5 columns (each number is separated from the next tab). The solution was as follows:

#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 not understand the statement if ((i% 5) == 0) printf ("\ n"); . Could you explain this to me?

+3
source share
9 answers

The operator %is the module operator (integer division). Thus, every five iterations of the loop, your program displays a character \n(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, \n(new line) will be printed to standard output.

Hope this helps.

+10

if , , i 5.

5 % 5 = 0 // remainder 
5 / 5 = 1  // quotient
+1

, 5 , .

0

% , . ,

if( (i%5) == 0 )
{
    printf("\n");
}

, i, 5, 0 ( i 5), . , i= 5, 10, 15, 20 ..

0

i%5 ( ) 5.

1%5 = 1
2%5 = 2
3%5 = 3
4%5 = 4
5%5 = 0
6%5 = 1
etc...

.

0
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
6 % 5 = 1
.........

% , , . - 5 .

0

1 100, 5, . , ( 1, 2, 3, 4, 5 ).

0

, .

, "", , "".

, , - 5 .: -)

0

(i% 5) , "\n" . 1 '\ t'2'\t'3 '\ t'4'\t'5 '\ ' 6.......

0

Source: https://habr.com/ru/post/1759182/


All Articles