Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading