Answer to Question #5077 in C++ for ghiwa

Question #5077
Let n = akak-1ak-2…a1a0 be an integer and t = a0 – a1 + a2 - … + (-1)kak. It is known that n is divisible by 11 if and only if t is divisible by 11. For example, suppose n = 8784204. Then t = 4 – 0 + 2 – 4 + 8 – 7 + 8 = 11. Since 11 is divisible by 11, it follows that 8784204 is divisible by 11. If n = 54063297, then t = 7 – 9 + 2 – 3 + 6 – 0 + 4 – 5 = 2. Because 2 is not divisible by 11, 54063297 is not divisible by 11. Write a function that takes as input an integer and that return a Boolean indicating whether the integer is divisible or not by 11. Write a program to test your function.
1
Expert's answer
2012-06-21T07:24:18-0400
#include <iostream>

#include <stdio.h>




using namespace std;




bool test(int n){

int t = 0;

int i = 1;

if(n < 0){

n = -n;// n shold be positive

}

while(n > 0){

t += (n) * i;

i *= -1;

n /= 10;

}

return !(t % 11);

}




int main(){

int val;

cout<<"Input n: ";

cin>>val;

bool res = test(val);

bool control = !(val);//true - if val is divisible by 11, else otherwise.

cout<<"Test result: "<<res<<" Control result: "<<control<<endl;

system("pause");

return 0;

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS