Home > Software engineering >  all multiples of 3 from 1 to 100 by a for loop in c
all multiples of 3 from 1 to 100 by a for loop in c

Time:11-23

for (int x = 3; x <= 100; x%3 == 0; x   ) {
 printf("%d\n", x);
}

I'm using the book "how to program C" by Deitel and there is this exercise, for this for loop, and they want me to fix it and get the output of all multiples of 3.

I've solved this with an if statement. But im curious if there is another way to fix it within the loop.

what i did was this :

for (int x = 3; x <= 100;  x   ) {

 if(x%3 == 0){
      printf("%d\n", x);
   }

}

CodePudding user response:

You can add 3 instead of 1 after each iteration, so that it will guarantee to be a mutiple of 3

Something like this:

for (int x = 3; x <= 100; x  = 3) 
{
    printf("%d\n", x);
}
  • Related