cp lab 11
cp lab 11
OBJECTIVE:
This lab will introduce loops available in C Language Program. At the end of this lab, you should be able to:
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.
In C, the rand() function is part of the standard library (stdlib.h). It generates a pseudorandom integer within a
specific range.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
// Seed the random number generator with the current time
srand(time(NULL));
return 0;
}
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.
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:
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.
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.
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>
int main() {
// Seed the random number generator with the current time
srand(time(NULL));
return 0;
}
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;
return 0;
}
Modify the above code so that it generates random numbers in the range 11-30.
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.
Sample Output 2
(Press any key for next trial)
Trial 3: Dice1=2 Dice2=1 Sum=3
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
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.
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
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;
}
#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>
#include <windows.h>
int main() {
printf("Mechatronics");
Sleep(2000);
system("cls");
printf("UET Lahore");
return 0;
}
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>
int main() {
gotoxy(50, 0);
printf("Mechatronics");
return 0;
}
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;
}
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>
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
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)
}
Here is the code for controlling the car with keys A and S:
#include <stdio.h>
#include <conio.h>
#include <windows.h>
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) {
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>
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");
return 0;
}