Simple for loop is not working

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int j;
int answer;
cout << "Enter j:" << endl;
cin >> j;
for (int i=0;i<=j-1;i++)
{
answer += (int)pow(5,i);
}
cout << answer;
}

I'm trying to write a program that does 5^0 + 5^1 + 5^2 + 5^3 + 5^(j-1) all the way up to whatever the user inputs for j. However, it is giving me a huge number, which does not make sense.
You forgot to initialize answer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int j;
long double answer=0;
cout << "Enter j:" << endl;
cin >> j;
for (int i=0;i<=j-1;i++)
{
answer += (float)pow(5.0,i);
}
cout << "the answer is:"<<answer<<endl;
return 0;
}
Topic archived. No new replies allowed.