1
#include <stdio.h>

int c, i, n, digit_cnt = 0, cnt = 0, total = 0;

int main(void)
{
    while (c = getchar())
    {
        if (c == 'E')
            break;
        ++cnt;
        if (c >= '0' && c <= '9')
            ++digit_cnt;
    }

    i = -5;
    n = 50;
    while (i < n)
    {
        ++i;
        if (i == 0)
            continue;
        total += i;
        printf("i = %d and total = %d\n", i, total);
    }
    return 0;
}

I want to avoid using breaks and continues, what are some ways to make these two pieces of codes work the same without using any breaks and continues?

selbie
  • 100,020
  • 15
  • 103
  • 173
YnSkn
  • 125
  • 1
  • 3
  • Depending on context, `return` and `goto` (and sometimes `longjmp()` if you've made an appropriate call to `setjmp()`). Using `goto` is the ubiquitous, always available, alternative, but is often regarded as anathema (certainly in comparison with `break` and `continue`). See also [GOTO: Still considered harmful?](https://stackoverflow.com/q/46586/15168) – Jonathan Leffler Mar 25 '20 at 03:58
  • 1
    I'm curious: Why do you want to avoid break and continue? – Tim Destan Mar 25 '20 at 04:09

2 Answers2

3

If you want to avoid break and continue statements here, rethink the logic of your code.

Instead of testing for E inside the loop and using break, test in the controlling expression for the while statement. Note also that getchar() can return EOF; an input failure causes getchar() to return EOF on subsequent calls, and this would lead the posted code to an infinite loop. You might want to handle EOF after the loop if that is the cause of the exit.

while ((c = getchar()) != 'E' && c != EOF)
    {
        ++cnt;
        if (c >= '0' && c <= '9')
            ++digit_cnt;
    }

Instead of checking to see if i == 0 and then using continue, check to see if i != 0 and then do something:

    if (i != 0) {
        total += i;
        printf("i = %d and total = %d\n", i, total);
    }
ad absurdum
  • 19,498
  • 5
  • 37
  • 60
0

How about this:

int main(void)
{
    while ((c = getchar()) != 'E')
    {
        ++cnt;
        if (c >= '0' && c <= '9')
            ++digit_cnt;
    }

    i = -5;
    n = 50;
    while (i < n)
    {
        ++i;
        if (i != 0)
        {
            total += i;
            printf("i = %d and total = %d\n", i, total);
        }
    }
    return 0;
}
selbie
  • 100,020
  • 15
  • 103
  • 173