DEV Community

Bala Murugan
Bala Murugan

Posted on

Program: Multiples of 3 or 5

Definition

This program is used to print all numbers from 1 to n that are divisible by 3 or 5.

A number is printed if:

It is divisible by 3, or
It is divisible by 5, or
It is divisible by both 3 and 5.

The program uses a while loop to check each number from 1 to n.

Algorithm:

Step 1: Start
Step 2: Input n
Step 3: Initialize i = 1
Step 4: Check whether i <= n
Step 5: If i % 3 == 0 OR i % 5 == 0, print i
Step 6: Increment i by 1
Step 7: Repeat Steps 4 to 6 until i > n
Step 8: Stop.

Flowchart:

      ┌─────────┐
      │ START   │
      └────┬────┘
           │
           ▼
    ┌─────────────┐
    │  Input n    │
    └──────┬──────┘
           │
           ▼
    ┌─────────────┐
    │   i = 1     │
    └──────┬──────┘
           │
           ▼
       ┌────────┐
       │ i <= n │
       └──┬──┬──┘
        Yes No
         │   │
         │   ▼
         │ ┌─────┐
         │ │ END │
         │ └─────┘
         │
         ▼
 ┌─────────────────┐
 │ i%3==0 OR       │
 │ i%5==0 ?        │
 └──────┬────┬─────┘
      Yes    No
       │      │
       ▼      │
 ┌─────────┐  │
 │ Print i │  │
 └────┬────┘  │
      │       │
      └──┬────┘
         ▼
   ┌─────────┐
   │ i=i+1   │
   └────┬────┘
        │
        └────────► Back to i <= n
Enter fullscreen mode Exit fullscreen mode

code:

n = int(input("Enter n: "))
i = 1

while i <= n:
    if i % 3 == 0 or i % 5 == 0:
        print(i)
    i += 1

Enter fullscreen mode Exit fullscreen mode

Example:

Input:
n = 20
Enter fullscreen mode Exit fullscreen mode
Output:

3
5
6
9
10
12
15
18
20

Enter fullscreen mode Exit fullscreen mode

Top comments (0)