How would I incorporate an array into a loop. I need to guess numbers randomly b
ID: 3673561 • Letter: H
Question
How would I incorporate an array into a loop. I need to guess numbers randomly but bound them by previous terms which screams array to me. I have a program that will do it, but it sometimes repeats numbers twice and that is why I want to store them to an array so the while loop will never show those numbers again. I have it check whether the random number is too big or too small, I just need the array part so I don't print the same number twice if I change the direction I am going. I am writing this in c++ using namespace std.
Explanation / Answer
Good Wishes,
First let me give you the code.
PROGRAM:
#include <iostream>
using namespace std;
int main ()
{
int status=0,random_no;
char carry_on='y';
int * array = (int*)malloc(sizeof(int) * 1);
cout<<array[0];
while(carry_on=='y')
{
random_no=rand();
for(int j=0;j<array.length;j++)
{
if(random_no==array[j])
{
status=1;
break;
}
}
if(status==1)
{
array = (int*)realloc(array, sizeof(int) * ((array.length)+1));
array[j]=random_no;
status=0;
}
else
continue;
cout<<"do you want to generate more random numbers(y/n)";
cin>>carry_on;
}
for(int j=0;j<array.length;j++)
{
cout<<array[j]<<endl;
}
}
EXPLAINATION:
Initially I created an array and allocated memory to it using malloc() of size 1.
int * array = (int*)malloc(sizeof(int) * 1);
Then using rand() function I generated random numbers.
Initial number is allocated to a[0].
Then I used a while loop to generate more random numbers until ther user inputs no('n') .
Each time a random number is generated I checked to see if it has being previously generated or not.
if it is not generated previously then i set the status to 1 and break the loop and then dynamically increase the size of te loop and add it to the array.
random_no=rand();
for(int j=0;j<array.length;j++)
{
if(random_no==array[j])
{
status=1;
break;
}
if(status==1)
{
array = (int*)realloc(array, sizeof(int) * ((array.length)+1));
array[j]=random_no;
status=0;
}
If it has being previously generated I just generated another using the condition status=0
else
continue;
As you asked I incorporated an array into a loop. I did a guess to generate numbers randomly and bound them by previous terms which screams array back. No repeation of numbers occured because previous numbers were stored in an array and checked to see each time whether the generated random number was previously generated.
Hope this is clear.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.