001-006-018

Variable Scope and Blocks

Easy

Problem Description

Variable Scope and Blocks

In this problem: You will create a program that demonstrates how variable scope (accessibility range) differs based on declaration location. You will declare variables at method level, inside blocks, and inside for loops to verify scope rules.

Learning Objective: Understand the relationship between variable declaration location and scope

Overview

Create a program that verifies the following scope rules:

  1. Declare method-level variable message and display it
  2. Declare variable blockVar inside an if block and display it
  3. Use variable i inside a for loop to display 3 iterations
  4. Show that method-level message is still accessible outside blocks

Specifications

  • Declare message = "Hello" at the beginning of the method
  • Declare blockVar = "Inside block" inside an if (true) block and display
  • Use for (int i = 0; i < 3; i++) to display each value of i
  • Display message again at the end

Output Format

message: Hello
blockVar: Inside block
i: 0
i: 1
i: 2
message is still accessible: Hello

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up