Search code examples
cnested-loops

for loop inside a for loop with if else condition


for (x = 0; x < 4; x++) {
    for (int a = 22; a <= 62;) {
        if (isCooked[x] == 1) {
            gotoxy(a,3); printf("cooked");
            gotoxy(a,4); printf("%-10s",food[userServings[x]]);
            a += 12;
        } else {
            gotoxy(a,3); printf("!");
            gotoxy(a,4); printf("%-10s",food[userServings[x]]);
            a += 12;
        }
    }
}

input output

May I ask whats wrong with loop above and conditions. I'm trying to print the name of the 4 vegetables that I have chosen. By using gotoxy I want to print them on the given coordinates on my loop.


Solution

  • Instead of a second loop, you should just compute the gotoxy coordinate:

    for (x = 0; x < 4; x++) {
        int a = 22 + x * 12;
    
        if (isCooked[x] == 1) {
            gotoxy(a, 3); printf("cooked");
            gotoxy(a, 4); printf("%-10s", food[userServings[x]]);
        } else {
            gotoxy(a, 3); printf("!     ");
            gotoxy(a, 4); printf("%-10s", food[userServings[x]]);
        }
    }