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:
- Declare method-level variable
messageand display it - Declare variable
blockVarinside an if block and display it - Use variable
iinside a for loop to display 3 iterations - Show that method-level
messageis still accessible outside blocks
Specifications
- Declare
message = "Hello"at the beginning of the method - Declare
blockVar = "Inside block"inside anif (true)block and display - Use
for (int i = 0; i < 3; i++)to display each value ofi - Display
messageagain 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