User has to input [a,b] range and I have to declare array of size 400 and program should output random numbers from this range. I am new at this and can you tell me some tips how can I do it. The code I have so far is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include<cstdlib>
usingnamespace std;
int main () {
int a,b;
cin>>a>>b;
srand(time (NULL));
int array[400];
cout<<array[rand()];
}
In your main you are creating a second random number, this is going to cause some problems for you later I assume.
also,
in your for loop your logic is a bit wrong. You are basically assigning the 400th index your random number every time your loop runs. You are trying to assign 1 value to EVERY index, not 1 value to 1 index every time. It should look like this::
1 2 3 4 5 6 7 8
int a = 1, b = 10;
int array[400];
for (int i = 0; ((i<a) && (i<b)); i++)
{
array[i] = getRandom(a, b);
cout << array[i];
}
Notice how I am also sending the 'getRandom' function your variables 'a' and 'b'. You have to do this, otherwise you are just going to get compilation errors or irrelevant data.
#include <iostream>
#include<cstdlib>
usingnamespace std;
int getRandom(int a,int b){
srand( time(NULL) );
if(rand()>a && rand()<b){
return rand();
}
}// it says that here is an error
int main () {
int a = 1, b = 10;
int array[400];
for (int i = 0; ((i<a) && (i<b)); i++)
{
array[i] = getRandom (a, b);
cout << array[i];
}
}
to have an array full of random integers you need to use a for loop and know how the rand function works. when the rand statement creates a random number it goes from 0 and on. when you use % it divides it by the HighNum and returns the remainder, then it adds LowNum.
In your getRandom function, have you considered what might happen if your 'if' statement fails? You have a return only for if this 'if' statement runs.
Your use of getRandom() shows you don't understand how functions work. The error you are getting is likely something to the tune of "not all control paths return a value".
Consider the following execution path:
You enter getRandom(), with a=100 and b=200.
You seed the RNG with the time.
You call rand() for the first part of the condition; suppose it returns 50.
Well, that's certainly less than or equal to a (100), so we don't enter the if statement.
But then we hit the end of the function, and while it was declared to return an int, we aren't returning anything!
See the issue?
Even if that wasn't the problem, each of your calls to rand() is separate and independent so if you are (as it seems) using this to generate a random number between a and b, it will fail because each of the calls to rand() will likely return a completely different number.
Thank you very much for help I see now my mistakes and it is better not to use functions when I do not know them well. Thankyou very much you have been very helpful