Home > Enterprise >  why does this program work even if i declare a variable in a for loop
why does this program work even if i declare a variable in a for loop

Time:11-17

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        int count=0;
        Scanner sc = new Scanner(System.in);
        System.out.println("enter 8 numbers");
        for(int i = 0; i<8; i  ){
            int x =sc.nextInt();
            if (x%2==0){
                count = count  1 ;
            }
        }
        System.out.println("the number of even number is :" count);

    }
}

i was expecting the program to fail because you cant declare a variable multiple times

CodePudding user response:

you're not declaring the variable multiple times. every time that block of code within the for loop executes, the declarations are creating new variables. i<8 means you are creating 8 blocks of code, which means 8 different int x are created.

  •  Tags:  
  • java
  • Related