How can I get this output by running a for loop
the logic is that after the multiples of 2, "This" will b printed, after the multiples of 3, "Is" will b printed and after the multiples of 5, "Java" will b printed.
pls help with code

1
2 This
3 Is
4 This
5 Java
6 This Is
7
8 This
9 Is
10 This Java
11
12 This Is
13
14 This
15 Is Java
16 This
17
18 This Is
19
20 This Java

Recommended Answers

All 2 Replies

Use the mode (%) operator inside a for loop like so :

final int MAX = 100;
for(int i = 1; i  < MAX; ++i){
  if(i % 2 == 0 ) /* if i is a multiple of 2 */
   { //do stuff    }
else if(i % 3 == 0 )/* if i is a multiple of 3 */
       {// do stuff   }
else if( i % 5 == 0 ) /* if i is a multiple of 5 */
          { //do stuff       }
}

You would not want to use else if, because if a number is a multiple of say 2 and 5, it will only print "This" istead of printing "This Java".

TJ

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.