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 named num to store the current number.
    • num = 1: Initializes num 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 as num is less than 10.
    • printf("%d\n", num): Prints the current value of num followed by a newline.
    • num++: Increments num 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

  1. Save the code as a .c file (e.g., print_numbers.c).
  2. Open a terminal or command prompt.
  3. Navigate to the directory where you saved the file.
  4. Compile the code using a C compiler (e.g., gcc print_numbers.c -o print_numbers).
  5. Run the compiled executable (e.g., ./print_numbers).

Expected Output:

1
2
3
4
5
6
7
8
9

CodeForHunger

Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button