Dynamic arrays

"Write a program that dynamically allocates a float array of a size specified by the user"

This my code so far, if anyone could check it and give some feedback I would be thankful.

#include <iostream> // include library

using namespace std;

int main() // main function
{
int length;
cout << “Please enter the length of the array: “; // ask user for array
cin >> length;

int *dArray;
dArray = new int[length];

for (
int i = 0;
i < length;
i++);

{
dArray[i] = i;
}

for (
int i = 0;
i < length;
i++;)

{
cout << dArray[i] << “ “;
}

delete [] dArray;

return 0;
}

Last edited on
First, please use code tags - http://www.cplusplus.com/articles/jEywvCM9/

Second, are you sure you wrote this yourself? Because, These quotations are wrong. Looks like quotations you get from copying something that is not from a c++ project.

Third, you shouldnt start with the second step before finishing the first. Have you tried compiling this? because it wont compile. Why would you come here asking for the next step when you havent even tried the first step?
Right ok ignore I mentioned step 2.

Yes I can use code tags, my apologies.

I wrote the code myself, but admittedly I haven't tried compiling it. I really don't understand this much, it's just an attempt.
The formatting is not the best, and you use semicolons at the wrong places. It should look like this -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int length;
		cout << "Please enter the length of the array: "; // ask user for array
		cin >> length;

		int *dArray;
		dArray = new int[length];

		for (int i = 0; i < length; i++)
		{
			dArray[i] = i;
		}

		for (	int i = 0;	i < length;	i++)

		{
			cout << dArray[i] << " ";
		}
		delete[] dArray;
Ok thank you. I'm confused as to why there is no need for a return 0;?

Also if you wouldn't mind could you please explain how I enable the user to input that number of floats? I'm trying to get around that sentence but in honesty I'm not sure what it means entirely
Last edited on
I believe in the new c++11 you dont need to have it. But I always have return 0; I just didint include it in the code above, as you can see I didint include int main() either, just the important parts.
Ok that's very helpful, thank you.

Would you have an idea how I could adapt this code to accept floats?
What would you want the program to do? Cuz if you use integers, it prints out 0,1,2,3,4,5 etc. What would you want it to do with floats?
Topic archived. No new replies allowed.