altayyyy
altayyyy

Reputation: 9

Using if while creating for loop

I am getting a number from the user to print a pattern in C language. If the number is an odd number there is no problem; but, if the number is an even number, codes are printing 1 block more! So, I want to check whether the number is an even number in my for loop.

I tried this code but it didnt work:

for (i = 1; i <= numb + 2; i++) {

    if (numb% 2 == 0) {
        numb+= 1;
    }

    for (j = 0; (numb % 2 == 0) ? (j < numb) : (j < numb+ 1); j++) {

        if (i % 2 == 0) {
            printf("* %d * ", j);       
        }
        else {
            printf("***** ");
        }

    }
    printf("\n");
}

Upvotes: 0

Views: 55

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51815

The problem is the syntax of your second statement (the conditional "test") in your for loop. You need to rearrange the code so this is a single statement:

for (j = 0; j < ( (numb % 2 == 0) ? numb : numb + 1 ); j++) {
    ...
}

Upvotes: 1

Related Questions