In this post, I am going to write a very simple C program to increment the number by a given value every second. This program also helps you to understand how to use the sleep() function in the C language.
#include<stdio.h>
#include <unistd.h>
int main(void) {
//declare variables
int num = 0;
int increment;
//get the increment number from user
printf("Enter increment value:");
scanf("%d", &increment);
//loop till the 'num' value equals to 100, we'll add the 'increment' number every 1 second and print it.
while(num <= 100) {
sleep(1); // Wait for a second
num += increment; // add the 'num' value with the 'increment'
printf("%d\n", num); // Print the current value of num
}
return 0;
}Example Output of the above program is here,
Enter increment value:5 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 -------------------------------- Process exited after 23.76 seconds with return value 0 Press any key to continue . . .
I believe this post would have helped you to understand how to use the sleep() function in C programming.