Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
Problem Statement - Output writing – Possible Random Numbers Series
Go through the C++ code below and find out the possible outputs from the suggested options (i) to (iv). Assume all the required header files are already being included in the code.
void main()
{
const int LOW=25;
randomize();
int p=5, number;
for(int i=1; i<=4; i++)
{
number=LOW+random(p);
cout<<number<<":";
p--;
}
}
(i) 29:26:25:25: (ii) 24:28:25:26
(iii) 29:26:24:28 (iv) 29:26:25:25:
Solution
TC++ #5591
Possible outputs could be
(i) 29:26:25:25
and
(iv) 29:26:25:26:
Notes
const int LOW=25;
An unchangeable value LOW has been initialised to 25
randomize();
This will allow random number generation process.
int p=5, number;
Integer p with initial value has been been initialised and number has been declared
for(int i=1; i<=4; i++) //This will run loop for 4 times.
number=LOW+random(p);
Since value of P would be 5 to 2 in decreasing order the possible random values on R.H.S could be 29 to 25 (25+4 to 25+0). When it is 2 number could be 25 or 26 when it is 5 the number could be 29/28/27/26/25 on R.H.S. . So the values would be from 29 to 25. The possible value chart could be
First pass of loop (p=5)| 29,28,27,26,25 Second pass of loop (p=4)| 28,27,26,25 Third pass of loop (p=3)| 27,26,25 Fourth pass of loop (p=2) | 26,25
cout<<number<<“:”;
This will print the possible values of number as explained above Based on possible value chart only option (i) and option (iv) are possible.
Presence of 24 in the option (ii) and (iii) also rule out the possibility of them as answers. So process of eliminating answers can also work well in this case.
Remember that random number generation is 1 less than the maximum value passed to random function. So random(1) will be 0, random(2) would be 0 or 1, random(3) would 0, 1 or 2, random(4) would 0, 1, 2 or 3