Reputation: 125
#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?
Upvotes: 1
Views: 5061
Reputation: 21364
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);
}
Upvotes: 3
Reputation: 104569
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;
}
Upvotes: 0