Swift Program to Find Power of a Number

1. Introduction

Finding the power of a number is a basic arithmetic operation that involves multiplying the number by itself a certain number of times. In this guide, we will learn how to raise a number to a power using a Swift program.

2. Program Overview

The program will utilize a base number and an exponent. It will then raise the base number to the power of the exponent. For example, if the base is 2 and the exponent is 3, the result will be \(2^3 = 2 * 2 * 2 = 8\).

3. Code Program

// Define the base and the exponent
let base = 5
let exponent = 3

// Function to compute the power of a number
func power(base: Int, exponent: Int) -> Int {
    var result = 1
    for _ in 1...exponent {
        result *= base
    }
    return result
}

let computedPower = power(base: base, exponent: exponent)
print("\(base) raised to the power of \(exponent) is: \(computedPower)")

Output:

5 raised to the power of 3 is: 125

4. Step By Step Explanation

1. let base = 5 and let exponent = 3: We start by specifying the base number and its exponent. Here, we'll raise 5 to the power of 3.

2. The power function calculates the result by initializing a result variable to 1. Then, using a loop that runs for the number of times specified by the exponent, we repeatedly multiply the result by the base.

3. The for-loop _ in 1...exponent iterates the multiplication process exponent number of times.

4. After computing the power using our function, we display the output with a print statement, showcasing the base, the exponent, and the result.

This simple looping method provides an easy and clear way to compute the power of a number in Swift, especially for small exponent values.


Comments