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

Implementing a loop based on a flowchart

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

LOOP

I tried following:

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

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?

>Solution :

As you perform the step z = z -b before the check z < 0 a dowhile 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 pointed 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 );
}
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