-2

I have problems choosing the initialisation and generally understanding the purpose of this program:

LOOP

I tried following:

void main() {
    int a, b, i = 0;
    printf("a\n");
    scanf("%i",&a);
    printf("b\n");
    scanf("%i\n",&b);
}

But what loop to choose?

paddy
  • 60,864
  • 6
  • 61
  • 103
  • 1
    The looping logic in this flowchart is most suited to a _do-while_ construct. – paddy Feb 02 '23 at 03:05
  • I thought so too, but what is the goal of this program ? Does it test if b > a and if it is, it will add z+b? What is the goal of E here. – Artur Kostjuk Feb 02 '23 at 03:13
  • It's dividing `a` by `b` the really slow way. `E` is the quotient, `R` is the remainder. Best guess using google translate is that `E` is "einteilung" which is German for division. – user3386109 Feb 02 '23 at 03:15

1 Answers1

3

As you perform the step z = z - b before the check z < 0 a do-while loop would map most naturally:

#include <stdio.h>

int main() {
    int a;
    int b;
    if(scanf("%d%d", &a, &b) != 2) {
         printf("scanf() failed\n");
         return 1;
    }
    if(b == 0) {
         printf("b cannot be 0\n");
         return 0;
    }
    int i = 0;
    int z = a;
    do {
       z -= b; 
       i++;
    } while(z >= 0);
    int E = i - 1;
    int R = z + b;
    printf("E = %d, R = %d\n", E, R);
}

As @Fe2O3 points out the E and R assignments undos the last step, so I would rework into a for-loop that tests if we need to take the next step before doing it. This would be a different flow chart though.

#include <stdio.h>

int main() {
    int a;
    int b;
    if(scanf("%d%d", &a, &b) != 2) {
        printf("scanf() failed\n");
        return 1;
    }
    if(!b) {
         printf("b cannot be 0\n");
         return 0;
    }
    size_t i = 0;
    for(; a - b >= 0; a -= b, i++);
    printf("E = %d, R = %d\n", i, a);
}

Or simply realizing what the algorithm does and implement it directly:

#include <stdio.h>

int main() {
    int a;
    int b;
    if(scanf("%d%d", &a, &b) != 2) {
        printf("scanf() failed\n");
        return 1;
    }
    if(!b) {
         printf("b cannot be 0\n");
         return 0;
    }
    printf("%d %d\n", a/b, a%b );
}
Allan Wind
  • 23,068
  • 5
  • 28
  • 38