Czech version
logolink

< Back to the list of lessons

For Cycle

AlgortimyContent of the lesson:

  • FOR Cycle in C
  • FOR Cycle Syntax in C
  • Examples of FOR Cycles
  • Connection Between WHILE and FOR cycles
  • Reversed FOR Cycle
  • Factorial
  • Multiplying - Individual Task

FOR Cycle in C

The FOR cycle can be (as well as the WHILE cycle) used to repeat a set of commands. This cycle is used very often so we have to deal with it. The FOR cycle is being used in situations when we know the number how many times should a command be done.

FOR Cycle Syntax in C

The syntax of the FOR cycle is:

Basic FOR cycle syntax in C
for (variable = lowerborder; contidionforend; change)
{
	command
}

The process

The FOR cycle is being executed using the following steps:

  1. the value lower_limit is assigned into the variable variable
  2. if the value of variable is lower than or equal to the value upper_limit the body of the cycle is executed
  3. after finishing the set of commands, the value of variable is automatically increased by one and the cycle is repeated from the first step
FOR cycle in C
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int cislo;
    
    for (cislo = 1; cislo <= 5; cislo++)
    {
    	printf("%d\n", cislo);
    }
    
    getchar();
    return 0;
} 

This programs writes five numbers from one to five (you will see 1, 2, 3, 4, 5 each on a new line) and it follows these steps:

  1. It assigns the value 1 into the cislo variable and UNTIL the cislo variable is lower than or equal to 5 it DOES the instruction from step 2.
  2. Write the value of the cislo variable.
  • At first the FOR cycle sets the value of the variable cislo to 1 and then it checks if cislo <= 5. This is true in the first step so the cycle continues.
  • The number 1 is written in the first step (the value of cislo).
  • The cycle returns to its beginning, increases cislo by one and checks if cislo <= 5. This is true because the value of cislo is 2 so the cycle is launched again.
  • The previous steps are repeated until the condition cislo <= 5 is valid. Then the cycle is terminated and the program continues executing the readln command - it will wait until enter is pressed.

Examples of FOR Cycles

Sum of Five Numbers

Consider a simple program to compute the sum of five numbers. The program assigns the variable soucet to zero and then the FOR cycle is repeated five times. In every pass it requires an input number from user and adds it to the value of the variable sum. After the cycle ends, the variable sum stores the final sum of five inserted numbers.

Sum of Five Numbers
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int i, cislo, soucet;
    
    soucet = 0;
    
    for (i = 1; i <= 5; i++)
    {
    	printf("Zadej cislo: ");
        scanf("%d", &cislo);
    	soucet = soucet + cislo;
    }
    
    printf("Soucet zadanych cisel je %d.\n", soucet);
    
    getchar();
    return 0;
} 

We can improve the program to inform an user about the number of the current pass ("Enter number 1, ... Enter number 2" etc.) We can use the i variable (from the for cycle) to solve this problem. You can use this variable anytime during the execution of the cycle.

Changing the request text
printf("Zadej %d. cislo: ", i);
Sum of Five Numbers
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int i, cislo, soucet;
    
    soucet = 0;
    
    for (i = 1; i <= 5; i++)
    {
        printf("Zadej %d. cislo: ", i);
        scanf("%d", &cislo);
    	soucet = soucet + cislo;
    }
    
    printf("Soucet zadanych cisel je %d.\n", soucet);
    
    getchar();
    return 0;
} 

Think about the properties of this program. It really computes the sum of five numbers, but this is the only good thing it does. A huge disadvantage is that this program can handle exactly five numbers (not more or less) so compared to the variation using the WHILE cycle, it is much worse. This property of the FOR cycle was fully illustrated here - you have to know the number of passes to be able to use the FOR cycle. Is it possible to improve the program to be at least able to set the number of values to insert?

You can define a new variable and set let the user set its value after the start. Then you can use it inside the condition of the FOR cycle.

The sum of given number of values
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int i, cislo, pocetcisel, soucet;
    
    soucet = 0;
    
    printf("Zadej pozadovany pocet cisel: ");
    scanf("%d", &pocetcisel);
    
    for (i = 1; i <= pocetcisel; i++)
    {
        printf("Zadej %d. cislo: ", i);
        scanf("%d", &cislo);
    	soucet = soucet + cislo;
    }
    
    printf("Soucet zadanych cisel je %d.\n", soucet);
    
    getchar();
    return 0;
} 

The Sum of Any Number of Values

Using cycles you are able to write a program which can handle a previously known number of values. However, we might want to write a program which would be able to handle any number of values (we would not know the number before launching our program) - you know that this is possible using the while cycle.

It is also possible to use the for cycle but you would have to set a high value in the condition to allow the user to set really "any" number of values. Then you would have to break the cycle (using the break command inside it) which could be a solution but it is useless.

When can the for cycle be used? In case you really know the exact number of passes which should be executed. You will use the for cycle when handling and sorting arrays. This cycle is explained because it is used very often but it does not have such possibilities as the while cycle. It is also true that you can write any algorithm using the while cycle and if...then conditions only.

Connection Between WHILE and FOR cycles

Every for cycle can be re-written using a while cycle.

Basic syntax of the FOR cycle in C
for (proměnná = dolnímez; podmínkaproukončení; změna)
{
	příkazy
}
The FOR cycle re-written using the WHILE cycle
  while (dolni_mez<=horni_mez)
  {
    posloupnost-příkazů;
    dolni_mez := dolni_mez + 1;
  }

Reversed FOR Cycle

In the end you should know that it is possible to reverse any for cycle in Pascal.

The Syntax of the reversed FOR cycle in C
for (proměnná = horní_mez; proměnná >= dolní_mez; proměnná--)
{
	posloupnost příkazů
}

Factorial

Individual Task: Create a program to compute the factorial from any inserted natural number. Use the FOR cycle.

You can find the definition of a factorial in the Internet so try to explain its meaning at first. Then you can write the program.

Factorial
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int cislo, faktorial, nasob;
    
    printf("Zadej cislo: ");
    scanf("%d", &cislo);
    
    faktorial = 1;
    
    for (nasob = 1; i <= cislo; i++)
    {
        faktorial = faktorial * nasob;
    }
    
    printf("Faktorial je %d\n", faktorial);
    
    getchar();
    return 0;
} 

Try to examine if your program works properly and in case you find any problem, try to fix it.

Individual Task I

Create a program which outputs to screen every multiple of 7 from the interval of 1..20. The result should be a written sequence of numbers (7, 14, 21, 29, ... ,140). Use the FOR cycle.

Individual Task II

Create a program to find the maximum from any number of inserted values. Use the FOR cycle.

Individual Task III

Create a program which outputs the small multiplication table - multiples of numbers 1..10 formatted in a well-arranged table. Allow the user to set the maximum number n for the table. Use the FOR cycle.

Questions

  1. Explain the syntax of the FOR cycle.
  2. Which basic properties has the FOR cycle?
  3. Describe the difference between the FOR cycle and the WHILE cycle.
webdesign, xhtml, css, php - Mgr. Michal Mikláš