Simple Divisibility Rule Checklist Problem

Hello,

I am having an issue printing the result of a program in which a number tests for divisibility by 11. Here is the code. I was wondering if anyone can help me with this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Testing if a number is divisible by 11.

#include <iostream>
using namespace std;

int main() {
    int n = 76945;
    int count = 4;
    int sum = n % 10;
    
    for(int i = n / 10; i >= 0; i /= 10) {
        if(count % 2 == 0) sum = sum + (i % 10);
        else sum = sum - (i % 10);
        count--;
    }
    if(sum % 11 == 0) cout << "The number is divisible by 11";
    else cout << "The number is not divisible by 11";

    return 0;
}
it does what you said, line 16+ are fine.
the question is, what number are you testing? What sum is supposed to be is unclear; any number % 11 == 0 is divisible by 11, but I got nothing on what the rest of the code is going on about
if you want to know if n is divisible by 11, just say n%11 ==0 and get rid of all the sum stuff.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main()
{
   int n;
   cout << "Enter a number: ";   cin >> n;
   
   // The quick way
   cout << n << ( n % 11 ? " is not " : " is " ) << "divisible by 11\n";
   
   
   // The just-for-the-hell-of-it way
   int sum = n % 10, parity = -1;
   for ( int i = n / 10; i; i /= 10, parity = -parity) sum += parity * ( i % 10 );
   cout << "The number" << ( sum % 11 ? " is not " : " is " ) << "divisible by 11\n";
}

Enter a number: 131615
131615 is divisible by 11
The number is divisible by 11
Topic archived. No new replies allowed.