Computer Science, asked by barbie1138, 10 months ago

write a program in java to calculate the xpower y without math function ​

Answers

Answered by rakeshchennupati143
2

Program:

import java.util.*;

public class XpowerY{

     public static void main(String args[]){

           Scanner sc = new Scanner(System.in);

           System.out.print("Enter 2 numbers : ");

           int num1 = sc.nextInt(),num2 = sc.nextInt();

           System.out.print("\n"+num1+" power of "+num2+" is ");

           while(num2>0){

                 product = num1 * product;

                 num2--;

           }

           System.out.print(product);

     }

}

Output:

Enter 2 numbers : 2 4

2 power of 4 is 16

Explanation:

  • first we have to know how power works for example 2⁴, so 2 will be multiplied by its self 4 times
  • so 2x2x2x2 = 16
  • so if we iterate a loop until the 4 becomes < 0 then we can multiply 2 that many times in loop
  • so product = product * num1 will be iterating until num2 gets < 0 so for that to happen we have to keep a predecrement on num2 so that every time the loop iterates the num2 will be decremented by 1 and at last we will have the 2 power of 4

----Hope you understood my logic in for loop, if you liked it mark as brainliest,it would really help me.   :)


barbie1138: bhai thanx
rakeshchennupati143: mark brainliest if you liked my program :)
Similar questions