Skip to content
Programs · Program 6-18

Q.Program 6-18: Program to find prime numbers between 2 to 50 using nested for loops.

Punjab PsebTextbookSubjective· 3mImportance★★★★★est
56% · 22/39 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Nest the prime test inside a sweep: the outer loop offers every number 2–50, the inner loop searches 2…num−1 for a divisor and breaks on success, and the for…else clause prints the number precisely when the search failed — output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47.

The idea. Program 6-14 tested one number for primality; wrapping that test inside an outer loop tests a whole range. This example also introduces Python's loop-else: the else block of a for loop runs only if the loop finished without hitting break — a perfect fit for "no divisor was found, so the number is prime", with no flag variable needed.

# Program 6-18: prime numbers between 2 and 50 using nested for loops
print("Prime numbers between 2 and 50 are:")
for num in range(2, 51):          # candidate numbers 2..50
    for i in range(2, num):       # possible divisors 2..num-1
        if num % i == 0:
            break                 # composite: stop testing this num
    else:
        print(num, end=" ")       # ran to completion: num is prime

Expected output

Prime numbers between 2 and 50 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

How the for…else behaves (trace of two candidates)

numInner loopbreak?else runs?Printed
9i = 2 (rem 1), i = 3 (rem 0)yes, at i = 3no—
11i = 2…10, no remainder is 0noyes11

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.