Wednesday, August 17, 2022

[FIXED] How to skip certain numbers in a for-loop?

Issue

I started practicing a for loop in C and so far I understand the main principle behind it. But I can't figure out how to get the following output:

1 2 3  5 6 7  9 10 11 ...

I managed to print 1 to 12 with the following for loop but how can I skip 4 and 8 or how to skip any number in general?

for(int i = 1; i < 12; i++)
{
    printf("%d", i);
}

Solution

the simplest solution would be to check with an if statement for any values that you don't want. if you have a rule like not printing all numbers that are divisible by 4 you can make your if statement like this

if(i % 4 == 0)
{
   //print
}

there is no way to do it specifically with the for loop expression.



Answered By - Gilad
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.