Anass Sbiyyaa
Anass Sbiyyaa

Reputation: 3

while loop fundamentals thirteens.cpp

I don't understand why the output starts from 13 in the following program. I want to understand the change of value in counter and why it outputs 13 first.

#include <iostream>

using namespace std;

int main()
{
    int counter = 0;
    while (counter < 100)
    {
        counter++;
        if (counter % 13 == 0 ){
            cout << counter << " ";
        }
    }
    return 0;
}

Upvotes: 0

Views: 87

Answers (4)

Pias Roy
Pias Roy

Reputation: 46

int counter = 0;
while (counter < 100)
{
    counter++;
    count<<counter<<endl;
}

This code will show the values of counter from 1 to 100.
But as you have added a condition of counter % 13 == 0, it means that the value of counter will be shown only if counter is divisible by 13. In other words, the only multiples of 13 up to 100 will be shown in the output.

PS: '%' is a modular operator. A % B equals to A - (floor(A/B)*B)

Upvotes: 0

tcmsh
tcmsh

Reputation: 41

'%' operator gives the remainder of a division operation. So any number from 1 to 99 which will we be divisible with 13 will be printed(not 0, because you are incrementing counter as soon as the loop starts, so 0 value doesn't enter the if statement).

If you want to check for 0 too, put counter++ after the if statement.

Upvotes: 0

DynasticSponge
DynasticSponge

Reputation: 1431

There are two operators for integer division... '/' gives you the number of times the right hand operand goes into the left hand operand

'%' gives you the remainder when the right hand operand can no longer go into the left hand operand

You are using modulus division '%'.

Your first time through the loop:

  • right hand is 13
  • left hand is 1
  • 1 divided by 13 is: 0 remainder 1
  • 1 != 0 so no console output

Your second time through the loop:

  • right hand is 13
  • left hand is 2
  • 2 divided by 13 is: 0 remainder 2
  • 2 != 0 so no console output

Your thirteenth time through the loop:

  • right hand is 13
  • left hand is 13
  • 13 divided by 13 is: 1 remainder 0
  • 0 = 0 , console output of current counter which is 13

You will only get console output when 13 can go into the counter multiple times, with no remainder.

Upvotes: 0

VanQator
VanQator

Reputation: 53

Ask yourself: What is the first number that divided by 13 gives rest equal 0? Notice that incrementatnion is before conditional statement. So, for first iteration counter is equal 1 for conditional statement.

Upvotes: 3

Related Questions