Monday, April 28, 2025

C Program - Check if Numbers are Even in Range from 1 to n

This C program prints all even numbers in the range from 1 to n.  

#include <stdio.h>

int main ()
{

    int x, number;

    printf("Range from 1 to n: \n");
    scanf("%d", &number);

    for (x = 1; x <= number; x++)
    {
        if (x % 2 == 0)
        {
            printf("%d \n", x);
        }
    }

    return 0;
}

Result:

Range from 1 to n:
10
2
4
6
8
10

Process returned 0 (0x0)   execution time : 1.031 s
Press any key to continue.

Here's a line-by-line explanation: 

#include <stdio.h>

This line includes the standard input/output library header file. 

int main ()
{

This line defines the main function of the program. 

    int x, number;

This line declares two integer variables x and number

    printf("Range from 1 to n: \n");
    scanf("%d", &number);

These lines prompt the user to enter the value of number and read its value from the standard input using the scanf() function. 

    for (x = 1; x <= number; x++)
    {
        if (x % 2 == 0)
        {
            printf("%d \n", x);
        }
    }

This for loop iterates over all integers from 1 to number (inclusive) and prints the even numbers using the printf() function. The if statement checks whether x is even or not by checking whether x % 2 is equal to 0. If x is even, it is printed to the standard output. 

    return 0;
}

This line indicates the end of the main() function and returns 0, indicating that the program has executed successfully.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...