Filling an Array

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;
}
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
@ wildblue: That would still try to go out of bounds. Better after the edit.
Last edited on
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
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.
The question is:
Use a loop to fill the "degTheta" array with values ranging from 0 degrees to 90 degress in steps of 5.
You could use a smaller array size than you have. You need 19 array elements to get from 0 to 90.
Okay thank you
Topic archived. No new replies allowed.