Question

Write a program in C++ or Java which determines the scope of the control variable declared...

Write a program in C++ or Java which determines the scope of the control variable declared in a while loop. Your program must determine whether the control variable is visible after the loop’s body. Make sure that you compile and execute your program.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.*;

class ControlVar
{
public static void main(String args[])
{
Scanner input=new Scanner(System.in);
int sum=0;

while(true)
{
int a;
System.out.print("Enter the positive values of a (enter any negative value to exit): ");
a=input.nextInt();
if(a<0)
{
break;
}
sum=sum+a;
}
System.out.println("Sum of the all a values: "+sum);
}
}

/*

The scope of the control variable declared in a while loop is private(local). So it means that you can declare a variable inside while loop but if you try to use that variable outside the loop then it will give or show the error, stating cannot find the symbol.

so The control variable is not visible after the loop's body.

*/

If a (control variable) is not used outside the while loop then it will not have the errors and executes perfectly.

But,

If a (control variable) is used outside the while loop then it will show the error, stating cannot find the symbol

Add a comment
Know the answer?
Add Answer to:
Write a program in C++ or Java which determines the scope of the control variable declared...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT