c-programming

Simple C programs
git clone git://git.laack.co/c-programming.git
Log | Files | Refs

exponentiation.c (711B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 
      4 int _powerRecurse(int current, int original, int n){
      5     if(n == 1){
      6         return current;
      7     }
      8     else{
      9         return _powerRecurse(current * original, original, n - 1);
     10     }
     11 }
     12 
     13 int power(int m, int n){
     14     if(n == 0){
     15         return 1;
     16     }
     17 
     18     if (n < 0){
     19         printf("Negative exponents not supported.\n");
     20         exit(-1);
     21     }
     22 
     23     return _powerRecurse(m,m,n);
     24 }
     25 
     26 int main(int argc, char** argv){
     27 
     28     if(argc != 3){
     29         printf("Usage: exp {base} {exponent}\n");
     30         return -1;
     31     }
     32 
     33     int base = atoi(argv[1]);
     34     int exp = atoi(argv[2]);
     35 
     36     int result = power(base,exp);
     37 
     38     printf("%d^%d = %d\n", base, exp, result);
     39 
     40     return 0;
     41 }