878854. The Else if Statement

Basic

The Else if Statement

Summary

The else if statement is a fundamental concept in programming that allows you to perform specific actions based on multiple conditions. This problem requires you to implement an algorithm using the else if statement to achieve a specific outcome.

Detailed Explanation

The else if statement is used when you need to check for multiple conditions and execute different blocks of code for each condition. In this problem, we will use the else if statement to solve a classic programming problem.

Let's consider the following scenario: You are given an integer N, and you need to print all numbers from 1 to N that are not divisible by either 3 or 5.

Here is the step-by-step breakdown of the solution:

  • Initialize a variable i to 1.
  • Use a loop to iterate until i is greater than N.
  • Inside the loop, use an else if statement to check if i is divisible by 3 or 5. If it is, print "Not a multiple" and increment i.
  • If i is not divisible by either 3 or 5, print i and increment i.

This solution uses the else if statement to achieve the desired outcome.

Time complexity: O(N) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static void main(String[] args) {
        int N = 20; // change this value as needed
        for (int i = 1; i <= N; i++) {
            if (i % 3 != 0 && i % 5 != 0) {
                System.out.println(i);
            }
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.