
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate the Power of a Number in Java
Read the base and exponent values from the user. Multiply the base number by itself and multiply the resultant with base (again) repeat this n times where n is the exponent value.
2 ^ 5 = 2 X 2 X 2 X 2 X 2 (5 times)
Problem Statement
Given a number, write a program in Java to calculate the power of the number ?
Input
Enter the base number :: 12 Enter the exponent number :: 2
Output
Result of 12 power 2 is 144
Steps to calculate the power of a number
- Import the Scanner class.
- Create the PowerOfNumber class and main() method.
- Initialize a Scanner object to read user input.
- Prompt and read the base number, and store it in the base.
- Initialize a temporary variable temp with the value of base.
- Prompt and read the exponent number, store it in exp.
- Use a for loop to multiply temp by itself exp-1 times.
- Print the result of the base raised to the power of the exponent.
Java program to calculate the power of a number
Below is the Java program that calculates the power of a number by taking the base and exponent as inputs from the user ?
import java.util.Scanner; public class PowerOfNumber { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the base number ::"); int base = sc.nextInt(); int temp = base; System.out.println("Enter the exponent number ::"); int exp = sc.nextInt(); for (int i=1; i<exp; i++){ temp = temp*temp; } System.out.println("Result of "+base+" power "+exp+" is "+temp); } }
Output
Enter the base number:: 5 Enter the exponent number:: 2 Result of 5 power 2 is 25
Code explanation
The program uses the Scanner class to read these inputs. The base number is stored in the variable base, and a temporary variable temp is initialized with the same value. The exponent is stored in the variable exp. The program uses a for loop that runs from 1 to one less than the exponent. In each iteration, temp is incorrectly multiplied by itself instead of being multiplied by the base. Finally, the result is printed, showing the base raised to the power of the exponent. Note that the calculation logic is flawed because it should multiply temp by base in each loop iteration instead of squaring temp.