-1

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

Benjam
  • 1,401
  • 2
  • 16
  • 22
shioares
  • 5
  • 3
  • 2
    where are you calling to your function? – yaodav Jul 05 '20 at 11:34
  • also, there isn't one thing in the code to make it c++ and not c so maybe you need to update the tag, and also don't use [#include](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – yaodav Jul 05 '20 at 11:41
  • The `c` in `main`and the `c` in `p` are different variables. Also, `return t;` is the same as `return a;`, since they always have the same value. That is, you have the equivalent of `int p(int a, int b) { return a;}`, but with undefined behaviour if `b` is less than 1. – molbdnilo Jul 05 '20 at 11:41
  • Actually i made the changes jonh made, and put return c; and worked fine, anyway, thanks for your informations guys. – shioares Jul 05 '20 at 11:52

1 Answers1

1

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);
john
  • 85,011
  • 4
  • 57
  • 81