# Tasks for the "While" Loop

Below is a detailed explanation of simple tasks to help those of you who don’t have any experience in programming and are taking your first steps in this field. After you look at these tasks, 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; } } } |

**Commentary:**

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. **We can solve this problem by means of the "while" loop.

Also, the last number is 98 (i.e. we can specify 98 in the loop). We do this with the help of this line:

1 |
while (a <= 98) { |

Before the "while" loop, we write:

1 |
int a = 7; |

Why do we write this? Because we have a sequence of numbers that starts with 7.

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

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

And with the help of this line,

1 |
a+=7; |

we increase the variable by 7. Please note that a+=7 is the same as a = a+7. These are shortcut arithmetic operations. We talked about them in the 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; } } } |

**Commentary:**

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.

In other words, **we are dealing with a 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 + " "); |

And we need to multiply the variable by 2 each time the code is run and that's why we write the following in the code:

1 |
n*=2; |