Java. Loops for, while, do … while. Examples of use. Solving of tasks using loops




Loops for, while, do … while. Examples of use. Solving of tasks using loops


Contents


Search other websites:

 1. Why do programming languages use loops?

In solving problems, often there is a need for multiple executions of the same sequence of actions (operators). Moreover, the number of actions is often unknown. It depends on the input data, the intermediate results obtained, and so on.

To ensure the repeatability of the computational process in the Java programming language, loop operators are introduced. The sequence of statements that must be executed at a time in a loop statement is called iteration.

2. What kinds of loop statements are used in the Java language?

The Java language has exactly the same basic loop statements as other programming languages (C++, C#, Pascal and others):

  • loop with the parameter ‘for’;
  • loop with the precondition ‘while’;
  • loop with a postcondition ‘do..while’.

Each of the above statements of the loop has its own syntax and features of using.

3. What is the general form of the ‘while’ statement?

The general form of the ‘while’ loop

while (conditional_expression)
{
    // body of the loop
    // ...
}

The while loop works as follows. If the condition value is true, then the loop body is executed. As soon as the value of the condition becomes false, the execution of the cyclic process is terminated and the program executes the statement following the ‘while’ statement.



4. What is the general form of the ‘for’ loop statement?

The ‘for’ loop operator is a fairly common construction. In the Java programming language, the for statement has different variants of the description. In the most common case, the loop operator has the form:

for (initialization; condition; increment)
{
    // body of the loop
    // ...
}

where

  • initialization – initial assignment of the value of a variable (variables), which takes part in the condition and increment. The initialization is performed only once. A variable that participates in a condition and increment is called a loop control variable;
  • condition – conditional expression according to the syntax of the Java language. The condition should be involved (not necessarily) the loop control variable. If the condition value is true, then the loop body is executed. If the value of the condition becomes false, the execution of the cycle is terminated and control is passed to the next after ‘for’ statement. In the Java language, the condition in the for statement of the for loop is an obligatory element;
  • increment – The action (operation) that is performed on the loop control variable. The increment can change the loop control variable both in ascending order and in descending order by a various value. After performing the increment, the condition is checked with further execution (or not execution) of the body of loop.

The loop operates according to the following principle. First, the loop control variable is initialized (once). Then the condition is checked. If the result of the condition is true, then the body of the loop is executed. After executing the loop body, the loop control variable increments by a certain amount. The loop is terminated when the condition value is false.

5. What is the general form of the ‘do..while’ loop statement?

The ‘do..while’ loop should be used in cases where you need to perform the loop body at least once. The general form of the ‘do..while’ loop is:

do
{
    // the body of loop
    // ...
}
while (condition);

The cycle operates according to the following principle. The body of the loop is executed first. Then the condition is checked. If the result of the condition is true, then the loop body is executed again. If the result of the condition is false, then the loop exits and the control is passed to the next statement of the ‘do..while’ loop.

6. Examples of solving the tasks using the ‘while’ loop operator

Example 1. By using the while loop it is needed to determine the sum

2 + 4 + 6 + … + 2·n

A snippet of code that solves this task (data input is omitted)

// the 'while' loop - calculating the sum
int i;
int n;
int sum;

// input n
// ...

i=1;
sum=0;
while (i<=n)
{
    sum += 2*i;
    i++;
}

Example 2. Calculate:

This task can be solved in two ways:

  • using recursion. In this case, you need to implement your own function, which will receive the input values 1, 3, …, 103;
  • using an iterative process, for which the ‘while’ loop is ideally suited. In this case, you need to perform calculations from the end to the beginning. This means that you need to change the counter value from 103 to 1 (103, 101, 99, …, 3, 1).

A snippet of code that solves this task with a while loop (second method):

// the 'while' loop - calculation a complex expression
int i; // variable-counter: i = 103, 101, 99, ..., 1
int n = 103; // lower bound
float res; // result

i=n; // initialization
res = i;

while (i>1)
{
    res = 1 / res;
    i-=2;
    res = i + res;
}
res = 1/res;

7. Examples of solving of tasks using a loop ‘for’

Example 1. Using the for loop, write a code snippet that finds the sum for the given n:

5 + 10 + 15 + … + 5·n

A snippet of code that solves this task

int i, n;
int sum; // result

// input n
// ...

sum = 0;

// the 'for' loop
for (i=1; i<=n; i=i+1 )
    sum += 5*i;

Example 2.

A natural number n is given. Calculate:

A snippet of code that solves this task (the input of n is omitted):

int k, n;
double sum; // result

// ввод значения n
// ...

sum = 0;

// the 'for' loop
for (k=1; k<=n; k++)
    sum += Math.sqrt(k);





8. Examples of solving of tasks using the ‘do..while’ loop

Example 1. Calculate the expression with an accuracy of 6 decimal places:

A snippet of code that solves this task

// the 'do..while' loop
int i;
double eps = 1e-6; // required precision
double t;
double sum;

i=0;
sum = 0;

do
{
    i++;
    t = 1.0/(i*i);
    sum = sum + t;
}
while (t>eps);
// Result: sum = 1.6439345666815615

Example 2. It is needed to calculate the largest positive n for which the condition is satisfied:

3·n2 – 730·n < 0

A snippet of code that solves this task:

int n;
int t;

n=0;

do
{
    n++;
    t = 3*n*n - 730*n;
}
while (t<0);

n--;
// n = 243


Related topics