Skip to main content

Section 10.2 for and if together

You can nest an if statement inside a loop or a loop inside an if statement.
Take a look at the following example which prints out those numbers between 0 and 29 that are divisible by 3. Make sure to try to understand how the code accomplishes this task.

Compile and run the code below in your own C environment.

#include <stdio.h>
int main(void)
{
    int i;
    int p = 3;
    
    printf("Printing numbers divisible by %d: \n", p);
    
    for (i=0; i<p*10; i++){
        if (i%p==0)
            printf("\n%d\n", i);
        else
            printf("-");
    }
    return(0);
}

Investigate 10.2.

Is there a difference between the two following scenarios, if the same statements are used within each element?