Tired of trying

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;
}
Last edited on
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).
1
2
3
4
5
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; 
}


can I ask what in the world are you trying to do with this loop?
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;
  }
}


Last edited on
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.
Last edited on
Why ahould sum be initialized inside!??
Last edited on
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.
I put a break in the if statement
now it is still infinite
Last edited on
You need to show us your code!
Last edited on
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; }
}
}
Last edited on
You need to add a break. And it looks like you've misplaced brace (it's hard to tell because you didn't use code tags).

1
2
3
4
5
6
7
8
9
for (int i = 2011; ; i++) {
    int sum = 0;
    for (int j = i; j > 0; j = j / 10)
        sum = sum + j % 10;
    if (sum & n == 0) {
        cout << i;
        break;
    }
}

Thank you, when I go home I will fix it and let you know if I have more problems.
Topic archived. No new replies allowed.