Arrays

Hi i'm relatively new to C++ and I've been asked to randomly fill an array with 100 positive integers with values between 0 and 99. Could someone please help me?

this is what i have so far and i know it's terribly wrong.

#include <iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
const int aSize=10;

int main()
{
a[i]=rand();
srand(time(0));
int a[aSize];
for (int i=0;i<aSize;i++)
cout<<endl;

cout<<a[i];
return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
const int aSize=10; //I thought you wanted 100 integers not 10?

int main()
{
    a[i]=rand(); //where does 'a' come from?
    srand(time(0));
    int a[aSize];
    for (int i=0;i<aSize;i++)
    cout<<endl; //why are you looping this statement?

    cout<<a[i]; //where does 'i' come from?
    return 0;
}


How I would do it:
main function
    seed the random generator
    define a constant integral type for size of array with value 100
    make array with size declared above
    loop through array
        for current array index set random value modulus 100
    ...
Last edited on
i guess i didn't understand what you were suggesting i should do so this is what i have so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
const int aSize=100;	
int array[aSize];
int main()
{

	for (int i=0;i<aSize;i++)
	{ 
		array[i]=(rand()% 99+0);
		if ((i+1)%20==0)
			cout<<array[i]<<" "<<endl;
		else
			cout<<array[i]<<" ";

	}
	return 0;
}


is this ok?
Last edited on
- "aSize" and "array" should be inside of main.
- you need to srand at the beginning of main.
- %99 doesn't quite fulfill the whole range.
After that I think it *should* be fine. Does it actually work?
Last edited on
If I were you, I would ask myself these questions:

1). Why do you need ctime?
2). Is there a way of presenting array[aSize] without writing aSize?
3). What range of variables does %99 (mod 99) give? Does adding 0 to this do anything?
4).What do the logical operators do? Are they needed here?

I hope this helps.
yes thank you for all your help... i've now managed to complete it.
This is how I did it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*

Fills an array with 100 random positive integers with values between 0 and 99.

*/

#include <iostream>
#include <cstdlib>
using namespace std;

int main(){

	int atr[100];

	for(int i=0; i < 100; i++){	atr[i]=rand() % 100;	
					cout << atr[i] << ' ';	}

	cout << '\n';

return 0;

}


I hope it looks similar to yours.
Topic archived. No new replies allowed.