Introduction:
In this program, we will determine whether a given number is odd or even using the C programming language. An even number is any integer that is divisible by 2 (i.e., the remainder is 0 when divided by 2), whereas an odd number is any integer that is not divisible by 2 (i.e., the remainder is 1 when divided by 2).
Objective:
The objective of this program is to take a number as input from the user, check whether the number is even or odd, and print the result accordingly.
C Program Code
#include int main() { int number; // Ask the user for input printf("Enter an integer: "); scanf("%d", &number); // Check if the number is even or odd if (number % 2 == 0) { printf("%d is an even number.\n", number); } else { printf("%d is an odd number.\n", number); } return 0; }
Explanation of the Program
Here is a breakdown of the program structure:
- #include <stdio.h>: This line includes the standard input/output header file, which is necessary for using functions like
printf
andscanf
. - int main(): This defines the main function where the program execution begins.
- int number;: This declares a variable
number
of typeint
to store the user’s input. - printf(“Enter an integer: “);: This line displays a prompt asking the user to input an integer.
- scanf(“%d”, &number);: This function reads the user’s input and stores it in the variable
number
. - if (number % 2 == 0): This conditional statement checks if the remainder of the number when divided by 2 is zero, which would indicate that the number is even.
- printf(“%d is an even number.\n”, number);: If the condition is true (the number is even), this line prints the message indicating that the number is even.
- else: If the number is not even, this block executes and prints that the number is odd.
- return 0;: This statement ends the program and returns a status code of 0, indicating that the program has run successfully.
How to Run the Program
To run this program, follow these steps:
- Open a text editor (like Notepad++ or Visual Studio Code) and paste the provided code into a new file.
- Save the file with a .c extension (e.g.,
odd_even.c
). - Open a terminal (command prompt) and navigate to the folder where the .c file is saved.
- Compile the program using a C compiler (e.g., GCC) with the following command:
gcc odd_even.c -o odd_even
- Run the compiled program with this command:
./odd_even
- Enter an integer when prompted, and the program will tell you whether the number is odd or even.