In: Computer Science
Write a program that repeatedly generates a random integer in the range [1, 100], one integer at a time, and displays the generated numbers on the screen according to the following rules:
1
6
34
67
88
44
32
Note: Attach your cpp file to this question.
Code:
#include<iostream> // header file for input output operation
#include <ctime> // for random number generation
using namespace std;
int main(){
srand ( time(NULL) ); // setting srand to get random different number each time code is executed
int number, array[1000], flag= 0, count = 0, value = 0; // value variable is used to decide the series is increasing or decreasing
while (flag != 1){ // while loop till flag is set to 1 (flag variable used to check the rules)
number = rand()%100 + 1; // generating the random number
array[count] = number; // assigning to array
if(count == 0){ // checking if first number is already entered or not
count++; // increasing the counter value
continue; // skiping all other statements
}
if(count == 1 && number == array[0]){ // checking if first number id equal to second number
flag = 1; // setting the flag
continue;
} // end of if
else if( count == 1 && number < array[0]){
value = -1; // seting the value -1 for decreasing series
}
else if( count == 1 && number > array[0]){
value = 1; // seting the value 1 for increasing series
}
else{
if( count > 1 && value == -1 ){ // decreasing series
if (number >= array[count -1]){ // checking if number is greater than or equal to last entered number
flag = 1; // setting the flag
} // end of if
if (flag == 1){
for (int i=0;i<count;i++) // loop to print the array contant
cout << array[i] << endl; // printing element
} // end of if
}
else if(count > 1 && value == 1){ // increasing series
if (number <= array[count -1]){ // checking if number is less than or equal to last entered number
flag = 1; // setting the flag
} // end of if
if (flag == 1){ // if flag is set
for (int i=0;i<count;i++) // loop to print the array contant
cout << array[i] << endl; // printing element
} // end of if
}
}// end of else
count++;
} // end of while
return 0;
}
Sample output:
* you need to run the code again and again repidly to get best result. to get these result I have to run too many times as again and again system is generating number like big,lower,big and lower,big,lower
Note: Please let me know if you have any doubt or there is any change required in the code.