0

I am having a hard time understanding the following code:

if ((number % 10)> max) //rem of 10
{
    max = (number % 10);
}
number /= 10;

Could you please help me with this?

2
  • 1
    Aren't you understanding how if works or what the operators do ? Explain what are you trying to achieve.
    – Mahesh
    Sep 18, 2011 at 7:23
  • % gives remainder, number /= 10 is same as number = number/10
    – Alok Save
    Sep 18, 2011 at 7:24

4 Answers 4

3

I guess the code you posted is the body of a loop, like this:

int max = 0;
while (number != 0) {
    if (number % 10 > max) {
        max = number % 10;
    }
    number /= 10;
}

This loop finds the largest decimal digit of number. E.g. if number==152, you will get max==5 after the loop.

1

If the last digit of number is larger than max:

if ((number % 10)> max)

Then max equals the last digit

max = (number % 10);

Remove the last digit

number /= 10;

When you put this in a loop, it let's you find the largest digit in the number.

1
  • (number % 10), gives remainder of number on dividing by 10.
  • (number % 10) > max, means if the remainer is greater than max.

So if the remainder is greater than max, them make max the remainder as:

       max = (number % 10); 

And number/=10 is a shorthand of

 number = number/10; //same as number /= 10;

which divides number by 10, and saves the quotient in number.

There are other shorthands in C++ as well:

 a += x; // a = a + x;
 a -= x; // a = a - x;
 a *= x; // a = a * x;
 a %= x; // a = a % x; //if a and x are integral type, if they're built-in type.

If the type of a is class, then you can overload all these operators for your class.

0

The following code does the same job but in a more understandable way. It also runs faster as the number of divisions, which are computationally expensive, is minimized (each % in your code implicitly involves a division).

// given: a positive integer 'number'
// sought-for: the maximum decimal digit in 'number'
int maxReminder = 0;
while (number != 0) {
    // find the quotient of the division of 'number' by 10
    int divQuotient = number/10;
    // find the reminder of the division above
    int divReminder = number - divQuotient*10;
    if (divReminder > maxReminder) {
        // 'divReminder' is the new maximum reminder
        maxReminder = divReminder;
    }
    // prepare for the next iteration
    number = divQuotient;
}
// 'maxReminder' now holds the sought-for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.