Home > OS >  Why is the loop running infinite times?
Why is the loop running infinite times?

Time:12-12

Friends, my goal is to find the numbers with odd sums from the numbers 1-99 in C language and print them on the screen. To try, I narrowed the scale and wrote 5 instead of 99 in the code. However, there is a problem, this code, which I think works very well in the logic in my head, enters an endless loop. I couldn't find what to do. How do you think I fix this?

The expected output (think 5 instead of 99): "Sum of digits odd: 1 Sum of digits odd: 3"

int main() {
    int n, m, result, temp;

    for (int i = 1; i < 5; i  ) {
        temp = i;

        while (i > 0) {
            m = i % 10;
            result  = m;
            i = i / 10;
        }

        if (result % 2 != 0) {
            printf("%d", temp);
        }
    }   
}

CodePudding user response:

You use i in your loop, and yet use i = i / 10 in that loop antill i is 0. That means, that i gets stuck as 1.

You'll either need another variable for the digit iteration, or to switch your use of i and temp so that i only gets changed by the loop's incrementation:

int main()    
{
  int n, m, result, temp;
  for(int i = 1; i < 5; i  )
  {
    result = 0;
    temp = i;
    while(temp>0)
    {
        m = temp % 10;
        result  = m;
        temp = temp / 10;
    }
    if (result %2!=0)
    {
        printf("%d", i);
    }
  } 
  return 0;
}

Edit: I also missed that you forgot to initialize result with an initial value, so you basically keep adding to a garbage value. You should initialize it with 0 in each iteration.

CodePudding user response:

You make a copy of i in temp.
But then you do not use temp and manipulate i in the inner loop.
Stick with your initial plan and only play with temp in the inner loop.

You probably also want to init/reset result at some point.

CodePudding user response:

You need to reset the value of i after the while loop. As posted, value of i is zero after the while loop.

  •  Tags:  
  • c
  • Related