Hello. I need help with a problem. The task is :
The user inputs a number n, and the program must find the first number bigger than 2010 whose sum of the digits is devisable by n. I don't know why I always get an infinity loop. Thank you for your help! I do it with two for loops. But the result is infinite,
[code]
for(int i=2010; ;i=i+1) {
for(int j=i;j>0;j=j\10) {
sum=sum+j%10;//sum is initialized at the. beginning sum=0 }
if(sum%n==0) { cout<<i;
}
It's an infinite loop all right. That's how you wrote it. You've given the outer loop no way to stop. Maybe you want to add a break somewhere?
And you definitely want to initialize sum to zero inside the outer loop, just before the inner loop (not before the outer loop if that's where it is now).
Your code is really close. Like tpb said you need to initialize 'sum' within the first loop. Other than that you only need a way to break the loop. There is a keyword for that. Also, use the increment operator. Instead of "i=i+1" use "i++."
1 2 3 4 5 6 7 8
for(int i=2010; ;i++) {
int sum = 0;//I added this
for(int j=i;j>0;j=j\10) {
sum=sum+j%10;//sum is initialized at the. beginning sum=0 }
if(sum%n==0) {
cout<<i;
break;//and this
}
If you have learned to use functions, something like this is much more readable:
1 2 3 4 5 6 7 8 9 10
int n;
cin >> n;
for (int i = 2010;; i++)
{
if (digisum(i)%n == 0)
{
cout << i;
break;
}
}
the current digits add to 3.
you need 7 more.
the next one is 2017 ?
dunno that you need a loop for that. Its good practice, but you can just directly find the answer.
You don't need to initialize it inside but you do need to assign it 0 inside so that it doesn't carry over the sum from the previous tested digits. And sum needs to be to 0 for sum += digit; to work.
Sorry, I will type it and explain why I do everything.
int n;
cin>>n;
for(int i=2011; ;i++) { //here i check every number i bigger than 2010
int sum=0;
for(int j=i;j>0;j=j/10) { //finding the digits of i and their sum
sum=sum+j%10;
if(sum&n==0) {
cout<<i; }
}
}