Bash program to find A to the power B


Given two number A and B write a shell script to find the value of AB .

Examples:

Input : 
2 4
Output :
2 to the power 4 is 16

Input :
1 0
Output :
1 to the power 0 is 1

Approach

A to the power B (AB) means multiplying A, B times. Using a naive approach to solve this problem.
For Example:-
A = 2 and B = 3
A3 = 8 which comes by multiplying 2 3 times i.e. 2*2*2 = 8 .

BASH

filter_none

edit
close

play_arrow

link
brightness_4
code

# Bash Program to find
# A to the power B
  
# Subroutine to find A
# to the power B
pow()
{
  # value of A
  a=$1
  
  # value of B
  b=$2
  
  # c to count counter
  c=1
  
  # res to store the result
  res=1
  
  #
  if((b==0));
  then
    res=1
  fi
  
  if((a==0));
  then
    res=0
  fi
  
  if((a >= 1 && b >= 1));
  then
    while((c <= b))
    do
      res=$((res * a))
      c=$((c + 1))
    done
  fi
  
  # Display the result
  echo "$1 to the power $2 is $res"
}
  
# Driver Code
  
# input
A=2
B=4
  
# calling the pow function
pow $A $B

chevron_right


Output:

16


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.