Delay() function in C++

Hello everyone, In this post, we will learn about the delay() function in C++. There can be many instances when we need to create a delay in our programs. C++ provides us with an easy way to do so. We can use a delay() function for this purpose in our code. This function is imported from the “dos.h” header file in C++. We can run the code after a specific time in C++ using delay() function.
delay() function in C++
Now let us understand the syntax for delay() function. It is as follows:
void delay(unsigned int milliseconds);
Explanation:
- Here, void suggests that this function returns nothing.
- ‘delay’ is the function name.
- The function takes one parameter which is unsigned integer.
Create a delay in time in a C++ program
The key point to note here is that this delay() function accepts parameter in milliseconds. That is if we want to create a 1-second delay in our program we have to pass 1000 as a parameter to the function.
Example of delay() in C++
#include<iostream.h> #include<dos.h> //for delay() #include<conio.h> //for getch() int main() { clrscr(); int n; cout<<"Enter the delay (in seconds) you want to make after giving input."<<endl; cin>>n; delay(n*1000); cout<<"This has been printed after "<< n <<" seconds delay"; getch(); return 0; }
OUTPUT:
Enter the delay (in seconds) you want to make after giving input. 5 This has been printed after 5 seconds delay.
How it worked:
As you can see in the program, we are taking input from the user ( To know: Taking only integer input in C++ ) and passing it to the delay function after multiplying it with 1000 to convert the seconds into milliseconds.
“dos.h” header file has been included so that a call to delay() function can be made.
NOTE: Your compiler must have dos.h header file in it.
Leave a Reply