ı have problem with this program because ı want

cin>> number;
int count[number]={0};
...
..
..
for ( ............ )
count=count +1;


ı could not such a segment in my program.
my aim is that for each entered number , ı will count something

ı want to learn this.

devc++ says there is a variable problem that can not change

Recommended Answers

All 6 Replies

will this help??

#include <iostream>
#include <string>


using namespace std;

int main()
{
	// counting forward from 0 to 500 using a FOR loop

	
	for (int n = 0; n < 501; ++n)
		cout << "Counting: " << n << endl;
	cout << endl;


	// COUNTING FROM 0 TO 500 USING A DO FUNCTION AND A WHILE combined
	int lownum = 0, highnum = 501;

	do
	{
		cout << "Counting : " << lownum++ << endl;
		cout << endl;
	} while (lownum < highnum);
	
	system("PAUSE");
	return 0;
}

cin>> number;
int count[number]={0};

The problem with this is that when you declare an array it must be of a constant size. You would have to declare count as an int pointer and dynamically allocate memory.

int size;
cin >> size;
int *count = new int[size];

There are couple of option you can choose from :

OPTION #1: Use buffer

const int MAX_SIZE = 1000;
int bufferLength = 0;
int buffer[MAX_SIZE] = {0};

cin >> bufferLength ;

if(bufferLength > MAX_SIZE){ cout << "Error: size to large\n"; return 1; }
for(int i = 0; i < bufferLength; ++i){
  //do things with buffer
}

OPTION #2 : dynamic array

int *buffer = 0;
int length = 0;
cin >> length;
buffer = new int[length];

for(int i = 0; i < length; ++i){
 //do stuff with buffer
}

delete buffer; //release unused memory

OPTION #3 : std::vector

int length = 0;
cin >> length;
std::vector<int> buffer(length,0);

for(int i = 0; i < buffer.size(); ++i){
 //do stuff with buffer
}

Option #3 is by far the best, in my humble but correct opinion.

Yes thanks your attention.
I will keep to work:)

I think option 2 is pretty reasonable for me, because ı dont have information about buffer.size()

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.