For Loop Question! need assistance!

Hey guys,
Write a program which accepts as input a positive integer and checks, using the algorithm described below, to see whether or not the integer is divisible by 11. This particular test for divisibility by 11 was given in 1897 by Charles L. Dodgson (Lewis Carroll).
Algorithm:
As long as the number being tested has more than two digits, form a new number by:
• deleting the units digit
• subtracting the deleted digit from the shortened number
The remaining number is divisible by 11 if and only if the original number is divisible by 11.
Heres my code:
#include <iostream>
using namespace std;

int main()
{
int x;
cout << "Enter an integer number: ";
cin >> x ;

int y ;
for ( y = x ; y > 99; y = y / 10 - y % 10 )
;

cout << y << "\n" ;

if ( y % 11 == 0 )
{
cout <<y << " is evenly divisible by 11" ;

}
else
{
cout << y << " is not evenly divisible by 11 " ;

}

return 0;
}
Last edited on
Can you please explain what is meant by deleting the units digit.

Aceix.
I think it means to delete the last digit
Are you really sure you are to use a loop for this?

Aceix.
Yes, since i am currently studying for loops, my teacher wants us to try and use for loops for this
I would be awesome if some can help me out with this :)
I would be awesome if some can help me out with this :)


You would be awesome if you attempted some code on your own.

While (that's right, while) you can do this with a for loop, it isn't well suited to the task. You'd be better off using another sort of loop.
yeah, i am sorry about that, heres the code i attempted:
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter an integer number: ";
cin >> x;


for ( cin >>x ; x >10; x = x / 10 - x % 10 ) {

if ( x%11==0 )
cout << x << " is divisible by 11." << endl;
else
cout << x << " is not divisible by 11." << endl;
}
return 0;

but i dont think it is right though, im hoping that someone can see what i should do about it
That is pretty close. Remember the idea is to reduce the number to 2 digits not 1, and you don't need to test the number until it has been reduced.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

int main()
{
    int x;
    cout << "Enter an integer number: ";
    cin >> x ;

    // reduce the number to 2 digits:
    int y ;
    for ( y = x ; y > 99; y = (y / 10) - (y % 10) )
        ;

    cout << x << " reduced to " << y << ".\n" ;

    if ( y % 11 == 0 )
    {
        cout << "Since " << y << " is evenly divisible by 11, " 
             << x << " must be too.\n" ;
    }
    else
    {
        cout << "Since " << y << " is not evenly divisible by 11, " 
             << x << " must not be either.\n" ;
    }

    return 0;
}


I'd never use a for loop for this, however.

Please see: http://www.cplusplus.com/articles/jEywvCM9/
for instructions on how to use code tags and make your code look all spiffy.
Topic archived. No new replies allowed.