0% found this document useful (0 votes)
4 views15 pages

cp lab 11

This document outlines Lab 11 for Computer Programming-I at the University of Engineering and Technology Lahore, focusing on random number generation and screen statements in C language. It covers the use of loops, the rand() function for generating pseudo-random numbers, and various programming tasks including a number guessing game and a simple math quiz. Additionally, it explains screen customization techniques using system commands and provides code examples for practical implementation.

Uploaded by

ayenawall15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views15 pages

cp lab 11

This document outlines Lab 11 for Computer Programming-I at the University of Engineering and Technology Lahore, focusing on random number generation and screen statements in C language. It covers the use of loops, the rand() function for generating pseudo-random numbers, and various programming tasks including a number guessing game and a simple math quiz. Additionally, it explains screen customization techniques using system commands and provides code examples for practical implementation.

Uploaded by

ayenawall15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Department of Mechatronics and Control Engineering

University of Engineering and Technology Lahore

LAB 11: RANDOM NUMBERS & SCREEN STATEMENTS


IN C LANGAUGE
MCT-142L: Computer Programming-I Lab

OBJECTIVE:
This lab will introduce loops available in C Language Program. At the end of this lab, you should be able to:

• Understand and use the concept of Random Number generation


• Understand and use different Screen Statements

APPARATUS:
• Laptop\PC with following tools installed
o Visual Studio Code with C/C++ and Code Runner Extensions
o C/C++ mingw-w64 tools for Windows 10

Random Numbers:
Random number generation is required in many applications e.g. games. In rolling a regular six-sided die, the program
should return a random number 1 to 6 and in playing card game a random card out of 52 should be generated. They are
also needed in modern cryptographic protocols that provide computer security, communication privacy, and
authentication.

Generating a true random number is not easy. In computational world, these numbers are generated by some
deterministic computation, but they look random and are good enough for most of the applications that require random
numbers. The programs which generate random numbers are known as pseudo-random number generators.

Generating Random Numbers in C

In C, the rand() function is part of the standard library (stdlib.h). It generates a pseudorandom integer within a
specific range.

Here is the program which generates a random number:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
// Seed the random number generator with the current time
srand(time(NULL));

// Generate a random number

1|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

int randomNum = rand();

printf("Random Number: %d\n", randomNum);

return 0;
}

Different parts are explained here:

Seed in Pseudorandom Number Generation:

What is a Seed?

In the context of pseudorandom number generation, a "seed" is an initial value used to kickstart the random number
generator. Pseudorandom number generators, like the one in C's rand() function, follow an algorithm to produce a
sequence of numbers. If you start with the same seed, you'll get the same sequence of pseudorandom numbers every
time you run the program.

srand() and the Need for Seeding:

Why Seed Matters?

Seeding is crucial to introducing unpredictability into the sequence of pseudorandom numbers. Without a seed, the
pseudorandom number generator might start at the same point every time, leading to predictability. By changing the
seed, you change the starting point of the sequence, making the numbers appear more random.

srand(time(NULL)); Explained:

Using Time as a Seed

time(NULL) returns the current time in seconds since the epoch (January 1, 1970). Using the current time as a seed
is effective because it changes every second, ensuring a different seed for each program run.

The srand() Function:

srand() is the function responsible for setting the seed for the pseudorandom number generator. It takes an integer as its
argument, which serves as the seed value.

Combining srand() with time(NULL):

srand(time(NULL)); combines the two concepts above. time(NULL) provides a constantly changing seed value
based on the current time. srand() uses this time-based seed to initialize the pseudorandom number generator.

Now run this code which generate the random numbers three times and observe the output:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

2|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

int main() {
// Seed the random number generator with the current time
srand(time(NULL));

// Generate and print three random numbers


for (int i = 0; i < 3; i++) {
printf("Random Number %d: %d\n", i + 1, rand());
}

return 0;
}

How to generate a Random Number within a specific range:

Suppose if you want to generate a number in range 1-10, you can use the modulus operator to achieve this. The code
below generates three random numbers in the range 1-10.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
// Seed the random number generator with the current time
srand(time(NULL));
int x;

// Generate and print three random numbers


for (int i = 0; i < 3; i++) {
x=rand()%10+1;
printf("Random Number %d: %d\n", i + 1, x);
}

return 0;
}

Modify the above code so that it generates random numbers in the range 11-30.

TASK 11.1: Number Guessing Game


Write a program that will generate a random number between 5 and 10 (both
inclusive) and will ask user to guess that number. If user guesses wrong,
it will ask him to guess again until the user guesses the correct number.
Also display number of trials user has taken to guess the number.

Important: Once a random number is generated, it should not be changed


during guesses from user.

3|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

I have selected a number between 5 and 10

Guess what is it: 5


No, it is wrong!
Guess what is it: 7
Sample Output 1 No, it is wrong!
(Suppose computer
Guess what is it: 8
generated 6)
No, it is wrong!
Guess what is it: 6
Yes, you guessed it right

You tried 4 times to guess the number

TASK 11.2: Number Guessing Game


Modify above program such that the random number generated is from 0 to
100 (both inclusive) and after each guess from user, if it is not correct,
tell him the number is above the guessed value or below that.

I have selected a number between 0 and 100

Guess what is it: 5


No, it is ABOVE 5
Guess what is it: 22
No, it is ABOVE 22
Guess what is it: 44
Sample Output 1 No, it is BELOW 44
(Suppose computer
Guess what is it: 40
generated 38)
No, it is BELOW 40
Guess what is it: 35
No, it is ABOVE 35
Guess what is it: 38
Yes, you guessed it right

You tried 6 times to guess the number

TASK 11.3: Two Dice Simulation


There are two regular dice, both are rolled, and sum of the outputs is
noted. The player will repeat this process n number of times and the sum
will be noted for each trial. If the sum is greater than or equal to 7,
for more than 50% of the trials, the player wins. Otherwise, he loses.
Write a program that will ask user for number of trials. The program

4|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

should roll the two dice for that number of time and should display the
output of each dice along with the sum. Finally, it will display whether
the user won or lost according to the rule described above.

Note carefully in sample output that user is asked to enter some key for
next trial. Key entered by user will be used nowhere but it's important
to have it like that to keep user's interest.

Enter the number of Trials: 5

(Press any key for next trial)


Trial 1: Dice1=3 Dice2=4 Sum=7

(Press any key for next trial)


Trial 2: Dice1=2 Dice2=6 Sum=8

(Press any key for next trial)


Sample Output 1 Trial 3: Dice1=3 Dice2=4 Sum=7

(Press any key for next trial)


Trial 4: Dice1=5 Dice2=1 Sum=6

(Press any key for next trial)


Trial 5: Dice1=1 Dice2=5 Sum=6

The Sum>=7 occurred 3 times in 5 trials.


CONGRATULATIONS!!! You are WINNER
Enter the number of Trials: 4

(Press any key for next trial)


Trial 1: Dice1=1 Dice2=3 Sum=4

(Press any key for next trial)


Trial 2: Dice1=3 Dice2=6 Sum=9

Sample Output 2
(Press any key for next trial)
Trial 3: Dice1=2 Dice2=1 Sum=3

(Press any key for next trial)


Trial 4: Dice1=4 Dice2=1 Sum=5

The Sum>=7 occurred 1 times in 4 trials.


SORRY!!! You LOST

5|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

TASK 11.4: Simple Math Quiz


Make a simple Quiz application for kids to test their simple addition
skill. The program should ask sum of two number (both operands in range
1-15 both inclusive) generated randomly and should display whether the
entered answer is correct or not.

Sample Output 1 9+11=20


(9+11= was Correct!
displayed by the
program and 20 is
entered by user)
Sample Output 2 12+15=26
(12+15= was Incorrect!
displayed by the
program and 26 is
entered by user)
Now modify the code such that the question appears 10 times and at the
end number of correct answers is also displayed.

TASK 11.5: Simple Math Quiz


Modify above code in a way that now subtraction and multiplication
questions are also asked. So, now there can be three types of questions;
addition, subtraction or multiplication. The two operands are generated
randomly (1-15) as previously and moreover the operation (+ , - or *) is
also chosen randomly.

To choose the operation randomly, we can generate a random number 1-3


and use three if statements incorporating one operation each.

Again ask 10 questions and display the number of correct answers.

6|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

TASK 11.6: Probability on Two Dice Roll Simulation


What is the probability of getting same numbers on two dice rolls? Here
is the sample space of the experiment:

1,1 1,2 1,3 1,4 1,5 1,6

2,1 2,2 2,3 2,4 2,5 2,6

3,1 3,2 3,3 3,4 3,5 3,6

4,1 4,2 4,3 4,4 4,5 4,6

5,1 5,2 5,3 5,4 5,5 5,6

6,1 6,2 6,3 6,4 6,5 6,6

The highlighted part shows the occurrence of similar numbers on both


rolls. There are total 36 possibilities and out of those 6 have the same
numbers. From your elementary knowledge of probability, you must know
that the probability of above event is:

P(Same number on both dice)=6/36=1/6=0.1667

The above method of finding the probability is Theoretical method. The


other method to find probability is the Experimental method where we
actually repeat the experiment and count the number of occurrences of a
particular event. Hence, in above case two dice must be rolled and
occurrences of same number on both should be counted. But how many times
the experiment must be repeated? Should we obtain results with two or
three experiments?

Ideally, we should repeat the experiment infinite times to get the same
result as of the theoretical calculations. But of course, practically it
is not possible. In reality even repeating above experiment 200 times
will take reasonable time. But here a computer program can help us repeat
the experiment even a few hundreds of thousands times at the cost of few
seconds!

So, write a program that will simulate the rolling of two dice and will
check whether the two outputs are same or not. The program must ask user

7|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

to enter the number of times he wants to repeat the experiment and then
should count the number of times the event in question occurred. The
program then must display the probability of the event.

Execute the program by entering different number of experiments starting


from 10 to 100 and then 1000, 10,000, 100,000 etc. Observe carefully
that the final answer of Experimental probability will get closer and
closer to the Theoretical value i.e. 0.1667 as we increase the number of
experiments.

Screen Statements:

Sometimes we need to customize the output on the output screen like changing the color of the screen or displaying
the output on a particular location on the screen. For that we can use the system() function available in stdlib header
file.

Screen Colors:

The first thing we can do with system() function is that we can change the color of background and foreground. For
that we need to pass the hexadecimal code for the two colors. The codes and their colors are detailed below:

The first digit represents the background color, and the second digit represents the foreground (text) color. Here are
some common color options:

0 - Black

1 - Blue

2 - Green

3 - Aqua

4 - Red

5 - Purple

6 - Yellow

7 - White

8 - Gray

9 - Light Blue

A - Light Green

B - Light Aqua

8|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

C - Light Red

D - Light Purple

E - Light Yellow

F - Bright White

For example, if you want to set the console text to bright yellow (E) on a blue (1) background, you would use
system("COLOR F0");.

#include <stdio.h>
#include <stdlib.h>

int main() {
system("COLOR 1E");
printf("My colorful screen!");
return 0;
}

Clearing the whole Screen:

If we want to clear the whole screen, we can use system("cls");

#include <stdio.h>
#include <stdlib.h>

int main() {
system("COLOR 1E");
printf("Mechatronics");
system("cls");
printf("UET Lahore");
return 0;
}

You would only see “UET Lahore” when above code is executed because system("cls") cleared the previous
screen.

Adding Delay:

Sometimes we need to add delay before we execute the next statement. For example, in above code, we can add
some delay before clearing the screen. For that we can use the Sleep() function available in windows header file.
The input to this function is number of milliseconds. The code below adds 2 seconds delay before clearing the output
screen.

#include <stdio.h>
#include <stdlib.h>

9|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

#include <windows.h>

int main() {
printf("Mechatronics");
Sleep(2000);
system("cls");
printf("UET Lahore");
return 0;
}

Accessing any location at output screen:

So far, we have seen that whenever we display something at output screen, it starts from upper left corner of the
window. But actually we can move to any location on the screen. The whole screen is of size 120x30 i.e. 120 characters
can be displayed horizontally and 30 vertically. We can move to any location on the window using its horizontal and
vertical location.

#include <stdio.h>
#include <windows.h>

void gotoxy(int x, int y) {


COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

int main() {
gotoxy(50, 0);
printf("Mechatronics");
return 0;
}

Running .exe file:

When compiled a program, the compiler generates an executable file .exe of the program which we can execute on
any windows system. If you will execute the .exe of above code, it will display the output i.e. “Mechatronics” and the
window will get closed immediately. Essentially you will not be able to see any output so quickly. The solution can be
placing an input statement as the last statement in the program which will be waiting for the user to input and the
window will close only after the user enters some input. The main code is shown here:

int main() {
char c;
gotoxy(50, 20);
printf("Mechatronics");
scanf("%c",&c);
return 0;
}

10 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

To take input a single character, instead of scanf() we can also use getchar() function. This function takes in a
single character as input. For above case, we don’t need to save the input character in any variable.

int main() {
gotoxy(50, 20);
printf("Mechatronics");
getchar();
return 0;
}

A small Animation:

We have discovered three new instructions system("cls"), Sleep() and gotoxy(). These three instructions
can be used to create simple text animations. For example, a simple car can be displayed at output window as:

int main() {
printf("__/TAXI\\__\n");
printf("l_(@)_(@)_l");
return 0;
}

Now you can make this car move on the output screen. It can be done by displaying car at the start of the window.
Use Sleep() to display car there for some milliseconds. Then clear the screen using system("cls")and display
car on next location on the screen. Repeat this procedure till car reaches right most side of the screen and at that point
move it back to loft most position. Below is the code for it:

#include <stdio.h>
#include <windows.h>

void gotoxy(int x, int y) {


COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

int main() {
system("COLOR F0");
int x = 1, y = 1;

while (1) {
gotoxy(x, y);
printf("__/TAXI\\__");
gotoxy(x, y + 1);
printf("l_(@)_(@)_l");
x = x + 2;
if (x == 111) {//120 is total console window size

11 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

x = 1;
}
Sleep(150);
system("cls");
}

return 0;
}

Further let’s try to control car using keyboard keys A and S. A to move it to left and S to move it to right. Here we also
want that user just need to press the keys A or S but doesn’t need to press the enter key. For that we can use kbhit()
function (keyboard hit) which returns 1 if any key is pressed on keyboard. This is how we can use the kbhit()
function for this purpose:

if (kbhit()) {
char c = getch();
// Handle the keypress (e.g., move the taxi)
}

The function kbhit() is available in the header file conio.

Here is the code for controlling the car with keys A and S:

#include <stdio.h>
#include <conio.h>
#include <windows.h>

void gotoxy(int x, int y) {


COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

int main() {
system("COLOR F0");
int x = 0, y = 0;

printf("__/TAXI\\__\nl_(@)_(@)_l");

do {
if (kbhit()) {
char c = getch();

switch (c) {
case 's':
x = x + 2;
if (x > 111) {

12 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

x = 0;
}
system("cls");
gotoxy(x, y);
printf("__/TAXI\\__");
gotoxy(x, y + 1);
printf("l_(@)_(@)_l");
break;

case 'a':
x = x - 2;
if (x < -1) {
x = 111;
}
system("cls");
gotoxy(x, y);
printf("__/TAXI\\__");
gotoxy(x, y + 1);
printf("l_(@)_(@)_l");
break;
}
}
} while (1);

return 0;
}

Note: Instead of A and S, if you want to use the arrow keys, you can access them using their ASCII codes given as:

UP KEY: 72

DOWN KEY: 80

LEFT KEY: 75

RIGHT KEY: 77

Now below is the code where you will see the moving car which you can stop by pressing the spacebar key and restart
the movement by pressing the spacebar again. Moreover, you can accelerate or decelerate the movement by pressing
the right or left arrow keys respectively. You can press the ESC key to end the program.

#include <stdio.h>
#include <windows.h>
#include <conio.h>

void gotoxy(int x, int y) {


COORD coord;
coord.X = x;
coord.Y = y;

13 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

int main() {
system("COLOR F0");
int x = 1, y = 1;
char c;
int delay = 200;

while (1) {
gotoxy(x, y);
printf("__/TAXI\\__");
gotoxy(x, y + 1);
printf("l_(@)_(@)_l");
x = x + 2;
if (x == 111) {
x = 1;
}
Sleep(delay);

if (kbhit()) {
c = getch();
if (c == ' ') {
c = 'p'; // Any character other than spacebar
while (c != ' ') {
c = getch();
if (c == 27){ // Check for ESC key to end the program
return 0;
}
}
}
if (c == 77) { // Right arrow key
delay = delay - 10;
if (delay < 5) {
delay = 5;
}
}
if (c == 75) { // Left arrow key
delay = delay + 10;
if (delay > 200) {
delay = 200;
}
}
if (c == 27){ // Check for ESC key to end the program
return 0;
}

}
system("cls");

14 | P a g e Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

return 0;
}

15 | P a g e Computer Programming-I Lab

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy