Home > database >  Implementing a loop based on a flowchart
Implementing a loop based on a flowchart

Time:02-02

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?

CodePudding user response:

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