"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Declaring Loop Control Variables Inside the for

Declaring Loop Control Variables Inside the for

Published on 2024-08-01
Browse:816

Declarando Variáveis de Controle de Laço Dentro do for

Concept

  • It is possible to declare the control variable directly in the for loop declaration.
  • This is useful when the variable is only needed within the loop itself.

Benefits

  • Improves code readability and organization.
  • Limits the scope of the variable to the loop, reducing the possibility of errors.

Example

  • The following program calculates the sum and factorial of the numbers from 1 to 5, declaring the control variable i within the for:
// Declara a variável de controle de laço dentro de for.
class ForVar {
    public static void main(String args[]) {
        int sum = 0;
        int fact = 1;
        // calcula o fatorial dos números até 5
        for(int i = 1; i 



Important
The scope of the variable declared within the for is limited to the loop.
Outside the for, the variable is not accessible:

// Declaração correta dentro do for
for (int i = 0; i 



Use and Limitations

Declare the variable inside the for when it is not needed outside the loop.
If you need to use the variable outside the loop, declare it before for:

int i; // Declarada fora do laço
for (i = 0; i 



Exploration

Test variations of the for loop to better understand its flexibility and behavior.

Release Statement This article is reproduced at: https://dev.to/devsjavagirls/declarando-variaveis-de-controle-de-laco-dentro-do-for-3kg5?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3