Print Even Numbers
To print even 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 even or not.
In the following program, we will take a value of 10 for n, and print even numbers from 1 to n.
main.swift
import Foundation
var n = 10
for i in 1...n {
if (i % 2 == 0) {
print(i)
}
}
Program Output
2
4
6
8
10
Summary
Summarising this tutorial, we learned how to use for loop with if condition, to print only even numbers to output.