Swift Program – Print Odd Numbers

Print Odd Numbers

To print odd numbers from 1 to n, use for loop with range. The range would be 1...n. And inside for loop, use if condition to check if the number is odd or not.

In the following program, we will take a value of 10 for n, and print odd numbers from 1 to n.

main.swift

import Foundation

var n = 10

for i in 1...n {
    if (i % 2 == 1) {
        print(i)
    }
}

Program Output

1
3
5
7
9

Summary

Summarising this tutorial, we learned how to use for loop with if condition, to print only odd numbers to output.