Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with if statement

Tags:

c

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?

like image 880
Sharifhs Avatar asked Feb 13 '26 13:02

Sharifhs


2 Answers

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.

like image 118
Pablo Santa Cruz Avatar answered Feb 16 '26 03:02

Pablo Santa Cruz


The if condition checks if the number represented by i is divisible by 5 .

5 % 5 = 0 // remainder 
5 / 5 = 1  // quotient
like image 44
Praveen S Avatar answered Feb 16 '26 04:02

Praveen S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!