Search code examples
c++parametersreturnsubroutinepow

Subroutine, without using pow, and with parameter and return


i don't understand what is wrong with my code it needs to have parameters and return, in c++

#include <bits/stdc++.h>

int p(int,int);

int main() {
  int a,b,c;
  scanf("%d",&a);
  scanf("%d",&b);
  printf("%d\n",c);
  return 0;
}

int p(int a,int b){
  int t,i,c=1;
  for(i=1;i<=b;i++){
    t=a;
    c=c*t;
    return t;
  }
}

here's the input: 2 4

the output: 16


Solution

  • I expect you meant to write this code

    int p(int a,int b){
      int t,i,c=1;
      for(i=1;i<=b;i++){
        t=a;
        c=c*t;
      }
      return t;
    }
    

    In your version the return statement is inside the for loop.

    And as has been pointed out, you probably meant this

    printf("%d\n",p(a,b));
    

    instead of this

    printf("%d\n",c);