In: Computer Science
PYTHON:
Using a counter initialized to 0, count how many even numbers are multiples of 3 in a range of numbers 1 to 300. If the counter reaches 20, break out of the loop and stop counting.
The problem can be analyzed first so that it will be easier to implement the Python code.
1. Using a counter, initialized to 0, the even numbers which are
multiple of 3 has to be counted in the range of numbers from 1 to
300. This can be implemented using a for loop. The
loop will run for loop variable 1 to 300 and check if the number or
loop variable is divisible by both 2 (even number) and 3 (multiples
of 3). If the number is divisible then increment the counter.
2. If the counter reaches 20, break out of the loop and stop
counting. This can be implemented by using break
statement. This statement stops the loop from further
execution.
3. Print necessary details to confirm that the counter has reached
20.
The required PYTHON code
is given below:
counter=0
#initializing counter variable
for x in range(1,301):
#loop to check numbers from 1 to 300
if(x%2==0 and x%3==0): #checking if
the number is even & multiple of 3
counter+=1
#if the condition satisfies then increment the count
if(counter==20):
#checking if counter reaches 20
break
#if counter reaches 20 then break the loop and stops the
counting
print("Current Counter =",counter)
#printing the counter
print("Last counted number =",x)
#displaying the last value counted by the counter
print("Counter has reached 20")
Screenshot of the code:
Output:
NOTE: To ensure correct parentheses, check the screenshot of the code. Also, the checking of the "counter==20" line comes under the above " if " statement, so that after updation of the counter, the variable can be checked at that moment.