The for loop operator. General form. Examples of tasks solving

The for loop operator. General form. Examples of tasks solving


Contents



1. Purpose of the for loop operator. General form

The for loop is intended for organizing a cyclic process. Using the for loop, you can organize a cyclic process of any type, in which:

  • the number of loop iterations is known;
  • the number of loop iterations is unknown and is determined based on the fulfillment of a certain condition.

The general form of the for loop operator

for (initialization; condition; expression)
{
    // instructions, statements
    // ...
}

here

  • initialization is an expression that initializes a counter variable. This variable determines the number of iterations that must be performed in the loop;
  • condition – a logical expression that determines the need to perform the next iteration of the loop. If the condition = true, then the next iteration of the loop is performed. If the value of condition = false, then the loop is terminated and the next operator is followed, which follows the for statement;
  • expression – is an expression that changes the value of a counter variable. Changing the value of a counter variable is optional. Also, the counter variable can change its value in the loop body.

If the for loop statement is used for one statement, then curly brackets can be omitted in general form

for (initialization; condition; expression)
    statement;

here statement – one operator or one instruction.

 

2. Varieties of for loop. Examples

In the for loop, you can omit any of its parts (initialization, condition, expression). The following examples demonstrate the versatility of the for loop, which can be used in different ways.

Example 1. In the example, the part that initializes the variable-counter is omitted. It is calculated the sum of

s = 2 + 4 + 8 + … + 100

The code snippet that solves this task is as follows:

// calculate the sum 2+4+8+...+100
int sum = 0;
int i = 0;
// no part of the initialization of the counter variable
for (; i <= 100; i += 2)
    sum += i;
// sum = 2550

Example 2. In the example, the part that checks the condition for the next iteration is omitted. The example calculates the sum of the elements of array A.

// calculate the sum of the elements of array A
double[] A = { 2.5, 1.2, 0.8, 3.3, 4.2 };
double sum = 0;
int i;

// there is no part that checks the condition of the loop
for (i = 0; ; i++)
{
    if (i == A.Length) break;
    sum += A[i];
}
// sum = 12.0

Example 3. In the example, the part of the expression that changes the variable-counter is omitted. Given a real number a and a positive integer n. Calculate:

a × (a+1) × … × (a+n-1)

The code snippet that solves this task

// calculate the multiplication a*(a+1)*...*(a+n-1)
int mult;
int i;
int n, a;
n = 5;
a = 4;
mult = 1;

// the part of increment the variable-counter i is missing
for (i = 0; i < n; )
{
    mult = mult * (a + i);
    i++;
}
// mult = 6720

Example 4. In the example, the for loop does not contain initialization and condition. A positive integer n is given. Determine the maximum digit of this number.

Solving this task using a for loop (an application of the Console Application type)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // determine the maximum digit of n
            int n;
            int t, d;
            int max;

            // input n
            Console.Write("n = ");
            n = Convert.ToInt32(Console.ReadLine());
            t = n;
            max = 0; // maximum digit

            for (; t > 0; ) // the cycle does not contain the initialization and increment of the counter
            {
                d = t % 10;
                if (max < d) max = d;
                t = t / 10;
            }
            Console.WriteLine("Max = {0}", max);
        }
    }
}

The result of executing the above program:

n = 283915
Max = 9

Example 5. In the example, the for loop does not contain conditions and expressions. The exit from the for loop is done using the break statement.

An array B of float numbers is given. Find the position pos of the first element of the array, the value of which is in the range from -5 to +5.

The code snippet that solves this task

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // find the position of the first occurence
            float[] B = { 12.4f, -11.9f, 7.5f, 2.3f, 1.8f };
            int pos;

            for (pos = 0; ; ) // for loop does not contain condition and expression
            {
                if (pos == B.Length)
                    break;
                if ((B[pos] >= -5) && (B[pos] <= 5))
                    break;
                pos++;
            }

            if (pos == B.Length)
                Console.WriteLine("The desired item is not in the array.");
            else
                Console.WriteLine("pos = {0}", pos);
        }
    }
}

The result of the program

pos = 3

Example 6. The example shows an “empty” for loop.

In general, an empty for loop looks like this:

for ( ; ; )
{
    // instructions
    // ...
}

 

3. Examples of a for loop in which the number of iterations is known

Example 1. Calculate the sum of all integers from 100 to 200.

A fragment of a program that solves this task using the for loop is as follows:

// calculate the sum
int sum;
int i;
sum = 0;
for (i = 100; i <= 200; i++)
    sum += i;
// sum = 15150

Example 2. Given a positive integer n. Develop a program that calculates the following sum

The code snippet that solves this task

// calculate the sum
double sum;
int i;
int n;
n = 10;
sum = 0;
for (i = 1; i <= n; i++)
    sum = sum + 1.0 / i;
// sum = 2.92896825396825

Example 3. Recurrent relations. The sequence of numbers a0, a1, a2, … is obtained according to the formula:

Given a positive integer n. Get a1, a2, …, an.

The text of the program that solves this task is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // get a1, a2, ..., an
            double a0, ak;
            int k;
            int n;

            n = 10;
            a0 = 1;
            k = 0;

            Console.WriteLine("a[{0}] = {1}", k, a0);
            for (k = 1; k <= n; k++)
            {
                ak = k * a0 + 1.0 / k;
                Console.WriteLine("a[{0}] = {1}", k, ak);
                a0 = ak;
            }
        }
    }
}

As a result of executing the above code, the following result will be displayed.

a[0] = 1
a[1] = 2
a[2] = 4.5
a[3] = 13.8333333333333
a[4] = 55.5833333333333
a[5] = 278.116666666667
a[6] = 1668.86666666667
a[7] = 11682.2095238095
a[8] = 93457.8011904762
a[9] = 841120.321825397
a[10] = 8411203.31825397

 

4. Examples of a for loop in which the number of iterations is not known

Example 1. Given a real number a. Calculate the smallest n such that

Solving of task for an application of Console Application type

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // the for loop in which the number of iterations is not known in advance
            int n;
            double a;
            double t;
            Console.Write("a = ");
            a = Convert.ToDouble(Console.ReadLine());

            // calculation loop
            for (n = 1, t = 0; t < a; n++)
                t = t + 1.0 / n;
            Console.Write("n = {0}", n - 1);
        }
    }
}

Running this program will give the following result

a = 2
n = 4

Example 2. Given the number a (1<a ≤ 1.5). Calculate the smallest n such that in the sequence of numbers

the last number is less than a.

Below is a solution for an application of the Console Application type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // find the smallest n
            int n;
            double a;
            double t;

            Console.Write("a = ");
            a = Convert.ToDouble(Console.ReadLine());

            // in the initialization part two expressions are placed
            for (n = 2, t = 1 + 1.0 / n; t >= a; n++)
                t = 1 + 1.0 / n;
            Console.WriteLine("n = {0}", n-1);
        }
    }
}

As can be seen from the above code, in the for loop in the initialization part there are two expressions separated by a comma:

for (n = 2, t = 1 + 1.0 / n; t >= a; n++)
    t = 1 + 1.0 / n;

Program execution for some value a may be, for example, the following

a = 1.3
n = 4

 

5. The concept of a nested loop for

The for loop can be nested in any other control statement that can be:

  • conditional statement if;
  • the switch operator;
  • the for loop operator;
  • the while loop operator;
  • the do…while loop operator.

The number of nested levels is unlimited.

 

6. Examples of solving of tasks in which the for loop is nested in other cycles

Example 1. In the example, the for loop is nested in another for loop.

Print the numbers in the following view:

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

The code snippet that solves this problem to add the type of Console Application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // another for loop is nested in a for loop
            for (int i = 1; i <= 5; i++)
            {
                for (int j = 1; j <= i; j++)
                    Console.Write("{0} ", i);
                Console.WriteLine();
            }
        }
    }
}

Example 2. The for loop is nested in a while loop. Find all integers in the interval from 1 to 300, wherein exactly 5 divisors.

A snippet of code that solves this task

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            // find all numbers from 1 to 300 in which exactly 5 dividers
            int num;
            int i, k;

            num = 1;
            while (num <= 300)
            {
                k = 0;
                for (i = 1; i <= num; i++) // the for loop is nested in while loop
                if (num % i == 0) k++;
                    if (k == 5)
                Console.WriteLine("{0}", num);
                num++;
            }
        }
    }
}

The result of the program

16
81

 


Related topics