Beginner array with square root

Write a program that declares an array squares of 50 components of type double. Initialize the array so that the first 25 components are equal to the square of the index variable, and the last 25 components are equal to the square root of the index variable. Output the array so that 10 elements per line are printed using two decimal places. All array operations are to be done in main().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
	double list[50];
        double j;
	int i;

	for (i = 0; i < 25; i++)
		list[i] = i*i;

	for (i = 25; i < 50; i++)
		j = i;
		list[i] = sqrt(j);

	for (i = 0; i < 50; i++)
		cout << list[i] << " ";

return 0;
}


I realize that the sqrt() function must use a float or double. I am iterating the array with an integer, and as far as I know it must be an integer so I cant change "i". I am trying to convert "i" into something I can use but it is not working. I have also tried static cast and that didn't work either.
Last edited on
something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
	const int arrSize = 50;
	const int halfway = 25;

	double list[arrSize];	

	for (int i = 0; i < arrSize; i++)
	{
		if(i < halfway)
		{
			list[i] = i*i;
		}
		else
		{
			double d = static_cast<double>(i);
			list[i] = sqrt(d);
		}

		cout << list[i] << ", ";

	}		

	return 0;
}


I am not sure why your static cast didn't work.
It has to be a double to int problem. The compiler is so serious about this. hmm, give me a sec to take a crack at it.
ahh, i get it you can't use the index variable for the the array and your for loop. you need a separate array variable. cheers! list[i] will never work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
	const int arrSize = 50;
	const int halfway = 25;

	double list[arrSize];

	for (int i = 0; i < arrSize; i++)
	{
		if (i < halfway)
		{
			list[arrSize] = i*i;
		}
		else
		{
			double d = static_cast<double>(arrSize);
			list[arrSize] = sqrt(d);
		}

		cout << list[arrSize] << ", ";

	}

	return 0;
}


this works, but there is no comparison arguments... you get 25 true values.. then the num 7. you just need to compare the arguments. cheers!
Last edited on
Topic archived. No new replies allowed.