-7

In this the following code , I check if a number ends in an 8 or not and if so I skip it.it The code works correctly; however,s I'd like to do this without hard coding every single number that ends in 8.

    for(number1 = 0; number1 <= number2; number1++){

        if(number1%2 == 0){

            if(number1 == 8 || number1 == 18 || number1 == 28){

                continue;

            }
            else{
                cout << " " << number1<< endl;
            }
        }




    }

2 Answers2

2

Just use modulo. number1 % 10 is a last digit (in decimal for positive number). So just check whether number1 % 10 == 8.

Equivalent code is:

for (number1 = 0; number1 <= number2; number1++) {
    if (number1 % 2 == 0 && number1 % 10 != 8) {
        cout << " " << number1 << endl;
    }
}
Filip Czaplicki
  • 189
  • 3
  • 12
  • why it,s Work?? 'number1 % 10 != 8' – M faras mughal Dec 20 '16 at 02:04
  • Modulo (`%`) divides the number by the amount, and returns the remainder. 18 / 10 = 1, remainder 8. – Tas Dec 20 '16 at 02:08
  • why we should use number % 10 ?? – M faras mughal Dec 20 '16 at 02:31
  • It's basically returning you the remainder of dividing by 10. Since our decimal number system is 10 based, it has the effect of returning the lowest digit of the number. number % 100 would give you the final 2 digits and so on. For 4 or 6 its a simple case of `number % 10 != 4` etc. For `10`, you'd need to bring another digit into the comparison i.e. `number % 100 != 10` – Paul Rooney Dec 20 '16 at 02:46
0

Heres an example of printing all the numbers not ending with 8 in a loop.

The operation x % 10 (modulus) returns the value of the lowest digit. So you can compare it with 8 to get your result.

#include <iostream>

int main(){

    for (int i = 0; i < 20; i++){
        if (i % 10 != 8){
            std::cout << i << '\n'; 
        }
    }
}
Community
  • 1
  • 1
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61