Clilstore Facebook WA Linkedin Email
Login

This is a Clilstore unit. You can link all words to dictionaries.

Loop statements

In some programs, depending on certain conditions, some of the commands should be repeated several times. Commands engaged in such actions are called commands of repetition (loops). In C, as well as in other programming languages, there are statements working with loops:

for loop

while loop

do-while loop

 

For loop

For loop statement format:

for (expression_1; expression _2; expression _3)

statement;

Expression_1is performed only once at the beginning of the loop. It is usually defines the initial value of theloop parameter (initializes the loop parameter). Expression_2 is a loop execution condition. Expression _3 usually definesa change in the loop parameter, statement - the loop body, which can be simple or compound. In the latter case, braces are used.

For example: segment of the program for counting n!:

p=1;

for (i=1; i<=n; i++)

p=p*i;

This segment can be written in a different way:

for (p=1; i=1; i<=n; i++)

p=p*i;

i.e., put the initial value ofрin the loop statement.

Some elements in for statement can be absent, however, semicolons separating them shall be present.

p=1; i=1;

for (; i<=n; i++)

p=p*i;

The loop body can be placed inside brackets, then after the closing bracket it is required to place a sign ;

for (p=1; i=1; i<=n; p=p*i, i++); or

for (p=1; i=1; i<=n; p*=i++) ;

Example 17. Find the sum and the product of all even numbers from 1 to 20.

#include

#include

main()

{ int i; unsigned long int S=0, P=1;

for (i=2; i<=20; i=i+2)

{S+=i;

P*=i;}

cout<<"S="<<S<<"P="<<P;

getch();

}

As a result, two values will be displayed on the screen: S=110 P=3715891200.

In Pascal, in for loop, the step can be equal only to 1, here the step can be any kind.

Example 18. Define all divisors of the entered number.

main()

{ int i, n;

cout<<”Enter number”; cin>>n;

for (i=1; i<=n; i++)

if (n%i==0) cout<<”i=”<<i;

}

Example 19. Display the multiplication table for the entered number.

main()

{ int x,i;

cout<<"Enter number ";cin>>x;

for (i=1; i<=9; i++)

{cout<<x<<"*"<<i<<"="<<i*x;

cout<<"\n";}

getch();

}

While loop

While loop statement format:

while (expression) statement;

The loop will repeat its execution until the value of the expression is non-zero, i.e. the loop condition enclosed therein is true.

Example 20. The program displays two-digit numbers, which are divisible by 5, but not divisible by 10. And also counts the number of them. The result of program is shown in Figure 5.

main()

{ int x, k=0;

x=10;

while (x<=99)

{if (x%5==0 && x%10!=0)

{cout<<"\n x="<<x; k++;}

x++;}

cout<<"\n k="<<k;

getch();

}

 

Clilstore

Short url:   https://clilstore.eu/cs/6248