Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the loop running infinite times?

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);
        }
    }   
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading