Mar 30, 2014 at 6:58pm Mar 30, 2014 at 6:58pm UTC
Hi
I'm trying to fill out an array from 0 to 90 in increments of 5, however once I get to 45, the next number is a large random number and the program terminates. Not sure why this is happening. Can someone please help me out with this?
#include <iostream>
using namespace std;
int main()
{
double degTheta[50];
for(int i=0; i<=90; i+=5)
{
degTheta[i] = i;
cout << i << endl;
}
return 0;
}
Mar 30, 2014 at 7:31pm Mar 30, 2014 at 7:31pm UTC
You've declared an array with 50 elements, so the valid element subscripts run from 0 to 49. Your loop then tries to access up to 90, so that's out of bounds.
I'd probably run the loop from 0 to < 50 and do something like degTheta[i] = 5*i.
Last edited on Mar 30, 2014 at 7:31pm Mar 30, 2014 at 7:31pm UTC
Mar 30, 2014 at 7:33pm Mar 30, 2014 at 7:33pm UTC
@ wildblue : That would still try to go out of bounds. Better after the edit.
Last edited on Mar 30, 2014 at 7:36pm Mar 30, 2014 at 7:36pm UTC
Mar 30, 2014 at 7:38pm Mar 30, 2014 at 7:38pm UTC
This is what I meant. Maybe I'm misunderstanding what he wants to do?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
using namespace std;
int main()
{
double degTheta[50]; // edit can be size 19
for (int i=0; i<50; i++) //edit - can loop to <19
{
degTheta[i] = 5*i;
cout << i << "\t" << degTheta[i] <<endl;
}
return 0;
}
0 0
1 5
2 10
3 15
4 20
5 25
6 30
7 35
8 40
9 45
10 50
11 55
12 60
etc.
Last edited on Mar 30, 2014 at 8:46pm Mar 30, 2014 at 8:46pm UTC
Mar 30, 2014 at 7:41pm Mar 30, 2014 at 7:41pm UTC
No you have it about right, the edits on this site don't always show up right away so I think we ninja'd each other.
Mar 30, 2014 at 8:37pm Mar 30, 2014 at 8:37pm UTC
The question is:
Use a loop to fill the "degTheta" array with values ranging from 0 degrees to 90 degress in steps of 5.
Mar 30, 2014 at 8:44pm Mar 30, 2014 at 8:44pm UTC
You could use a smaller array size than you have. You need 19 array elements to get from 0 to 90.