# Tasks on the while loop

The following is the detailed explanation of the simplest tasks to help those of you who don’t have any experience in programming and just start to break fresh ground in this field. After looking into them it will be much easier to move on to more complex problems.

**Task No.1**

It is necessary for the program to display the following sequence of numbers:

7 14 21 28 35 42 49 56 63 70 77 84 91 98

**Solution:**

1 2 3 4 5 6 7 8 9 |
public class Test { public static void main(String[] args){ int a = 7; while (a <= 98) { System.out.print (a+" "); a+=7; } } } |

**Comments to the task:**

We need to display the following sequence of numbers: 7 14 21 28 35 42 49 56 63 70 77 84 91 98

As you can see, the first number is 7. Then 7 is added to each subsequent number:

7+7 =14

14+ 7 = 21

21+7 = 28 and so on.

**This is a loop. **This problem can be solved by means of the while loop. The last number is 98, i.e. we can specify 98 in the loop. We did it with the help of this line:

1 |
while (a <= 98) { |

We write the following before the while loop:

1 |
int a = 7; |

Why would we write it? Because we have the sequence of numbers starting with 7.

With the help of this line we display the numbers to the console:

1 |
System.out.print (a+" "); |

And with the help of

1 |
a+=7; |

we increase the variable by 7. Please note that a+=7 is the same as a = a+7. These are so-called shortcut arithmetic operations. We talked about them in out article “Basic operations with variables in Java”.

**Task No.2 **

It is necessary to display the following sequence of numbers:

1 2 4 8 16 32 64 128 256 512

**Solution:**

1 2 3 4 5 6 7 8 9 |
public class Test { public static void main(String[] args){ int n = 1; while (n <= 512) { System.out.print (n + " "); n*=2; } } } |

**Comments to the program:**

As we can see, there is a pattern in the sequence 1 2 4 8 16 32 64 128 256 512.

The first number in the sequence is 1, and each subsequent number is multiplied by 2:

1*2 = 2

2*2 = 4

4*2 = 8

8*2 = 16 and so on.

That is, **we deal with the loop.**

Since the first number of the sequence is 1, we write the following before the loop:

1 |
int n = 1; |

The loop need to be executed as long as n is less than or equal to 512. In order to do this, we write this line:

1 |
while (n <= 512) { |

We display the sequence of numbers to the console with the help of this line:

1 |
System.out.print (n + " "); |

Each time the numbers need to be multiplied by 2, that’s why we write the following in the code:

1 |
n*=2; |

## Leave a Reply