The method printEvenNumber() below should print even numbersfrom 2 to 10. Howeve
ID: 3611213 • Letter: T
Question
The method printEvenNumber() below should print even numbersfrom 2 to 10. However, there is a programming error in thismethod. public void printEvenNumber() { int i=0; while(i!=11){ i=i+2; System.out.println(i); } } Describe what happens when the method printevenNumber() isinvoked? Describe the programming error in it. Rewrite the method printEvenNumber() so that it now printscorrectly all even numbers from 2 to 10. Keep the while statementwhen rewritiong the method. please give comments with your simplest code. Thanks The method printEvenNumber() below should print even numbersfrom 2 to 10. However, there is a programming error in thismethod. public void printEvenNumber() { int i=0; while(i!=11){ i=i+2; System.out.println(i); } } Describe what happens when the method printevenNumber() isinvoked? Describe the programming error in it. Rewrite the method printEvenNumber() so that it now printscorrectly all even numbers from 2 to 10. Keep the while statementwhen rewritiong the method. please give comments with your simplest code. ThanksExplanation / Answer
Describe what happens when the methodprintevenNumber() is invoked?It results in an infiniteloop.
The reason is while loop never terminates as i never equals 11.
Every time you are adding 2 to i. Initially i is zero. in the nextstep i=2, next step i=4...therefore i is always even and it neverequals 11.
Therefore while loop never terminates and ther will be an infiniteloop.
Describe the programming error in it.
Theprogramming error is in the line while(i !=11)
Every time you are adding 2 to i. Initially i iszero. in the next step i=2, next step i=4...therefore i is alwayseven and it never equals 11. Therefore while loop never terminatesand ther will be an infinite loop.
Rewrite the method printEvenNumber() so that it nowprints correctly all even numbers from 2 to 10. Keep the whilestatement when rewritiong the method.
public void printEvenNumber() { int i=0; while(i < 10){ //now while loop terminates when ibecomes 10
i=i+2; //adds 2 to i
System.out.println(i); //prints i
} }
IN the above function while loop runs for 5 times
1) when i= 0..it prints 2
2) when i= 2..it prints 4
3)when i= 4..it prints 6
4) when i= 6..itprints 8
5) when i=8 ..it prints 10
6) when i=10..it terminates as 10 is not less than 10
Therefore it prints all the even numbers from 2 to 10
public void printEvenNumber() { int i=0; while(i < 10){ //now while loop terminates when ibecomes 10
i=i+2; //adds 2 to i
System.out.println(i); //prints i
} }
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.