Of course! Here is a C program to count from 0 to 1,000,000.
I'll provide two versions:
- A simple version that prints every single number.
- An improved version that is much faster and cleaner, as printing one million lines to the screen can be very slow.
Version 1: Simple and Direct
This program uses a for loop to iterate from 0 to 1,000,000 and prints each number on a new line.
Note: This will be very slow because writing to the console is a time-consuming operation. Your screen will be flooded with numbers for a while.
// File: count_simple.c
#include <stdio.h>
int main() {
// We use a 'for' loop for counting.
// 1. Initialization: 'int i = 0' starts our counter 'i' at 0.
// 2. Condition: 'i <= 1000000' continues the loop as long as 'i' is less than or equal to 1,000,000.
// 3. Increment: 'i++' adds 1 to 'i' after each loop cycle.
for (int i = 0; i <= 1000000; i++) {
// printf is used to print formatted output to the screen.
// %d is a placeholder for an integer.
// \n creates a new line after each number.
printf("%d\n", i);
}
// A good practice is to return 0 from main to indicate the program ran successfully.
return 0;
}
How to Compile and Run:
- Save the code as
count_simple.c.
- Open a terminal or command prompt.
- Compile it using a C compiler like GCC:
gcc count_simple.c -o count_simple
- Run the executable:
./count_simple
Version 2: Improved and Faster
This version still counts to 1,000,000, but instead of printing every number on a new line, it updates a single line. This is much faster and provides a cleaner user experience.
// File: count_fast.c
#include <stdio.h>
// On Windows, you might need this for unistd.h equivalent for sleep
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h> // for usleep
#endif
int main() {
printf("Starting count...\n");
for (int i = 0; i <= 1000000; i++) {
// '\r' is a carriage return. It moves the cursor to the beginning of the line
// without going down. This allows us to overwrite the previous number.
printf("\rCounting: %d", i);
// stdout is the standard output stream (your terminal). It is often buffered,
// meaning it waits to print until a newline is found or the buffer is full.
// fflush() forces the buffer to print immediately.
fflush(stdout);
// Optional: slow down the count slightly to make it visible
// usleep(1); // sleep for 1 microsecond (requires <unistd.h>)
}
// Print a final newline to move to the next line after the count is done.
printf("\nDone!\n");
return 0;
}
How to Compile and Run:
- Save the code as
count_fast.c.
- Open a terminal or command prompt.
- Compile it:
gcc count_fast.c -o count_fast
- Run the executable:
./count_fast
You will see a single line in your terminal with the number rapidly updating until it reaches 1,000,000.