I have two “equivalent” programs in C and in C++ that have different outputs.
They should print step by step all the powers of a “base” between 0 and “exp”
test.c is:
#include <stdio.h>
int power(int b, int e) {
int p = 1;
for (int i = 0; i < e; i++) {
printf("%d^%d = %dn", b, i, p);
p = p * b;
}
return p;
}
int main() {
int base = 2, exp = 3;
printf("%d^%d = %dn", base, exp, power(base, exp));
return 0;
}
output:
2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
test.cpp is:
#include <iostream>
using namespace std;
int power(int b, int e) {
int p = 1;
for (int i = 0; i < e; i++) {
cout << b << "^" << i << " = " << p << endl;
p = p * b;
}
return p;
}
int main() {
int base = 2, exp = 3;
cout << base << "^" << exp << " = " << power(base, exp) << endl;
return 0;
}
output:
2^3 = 2^0 = 1
2^1 = 2
2^2 = 4
8
Can anybody please tell me why does this happen?
Why does the “cout” print the first part before executing the function?
Thank you in advance
New contributor
Francesco Antropoli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1