C (programming language)
C program to print number while is less than 10
Understanding the Problem
- Goal: To write a C program that repeatedly prints numbers starting from 1, continuing as long as each number is less than 10.
- Key Concepts:
- Variables: Containers for storing data.
- While loops: Structures for repeating code blocks until a condition becomes false.
- Increment operators: Used to increase a variable’s value by 1.
- Input/Output (I/O): Communicating with the user through the console.
Step-by-Step Guide
1. Header Inclusion
C
#include <stdio.h>
- Explanation: This line includes the standard input/output library, providing functions for printing to the console (e.g.,
printf
) and reading user input (e.g.,scanf
).
2. Main Function
C
int main() {
// Code statements here
return 0;
}
- Explanation:
int main()
: The entry point of the C program. Execution begins here.// Code statements here
: Placeholder for the code we’ll add.return 0;
: Indicates successful program termination.
3. Variable Declaration
C
int num = 1; // Initial number
- Explanation:
int num
: Declares an integer variable namednum
to store the current number.num = 1
: Initializesnum
to 1, starting the sequence from 1.
4. While Loop
C
while (num < 10) {
// Print the current number
printf("%d\n", num);
// Increment the number
num++;
}
- Explanation:
while (num < 10)
: The loop continues as long asnum
is less than 10.printf("%d\n", num)
: Prints the current value ofnum
followed by a newline.num++
: Incrementsnum
by 1, moving to the next number in the sequence.
5. Complete Code
C
#include <stdio.h>
int main() {
int num = 1;
while (num < 10) {
printf("%d\n", num);
num++;
}
return 0;
}
6. Executing the Program
- Save the code as a
.c
file (e.g.,print_numbers.c
). - Open a terminal or command prompt.
- Navigate to the directory where you saved the file.
- Compile the code using a C compiler (e.g.,
gcc print_numbers.c -o print_numbers
). - Run the compiled executable (e.g.,
./print_numbers
).
Expected Output:
1
2
3
4
5
6
7
8
9