
Introduction
Determining whether a number is even or odd is a fundamental concept in computer programming and mathematical computations. This simple test can influence the flow of logic in applications ranging from simple loops to complex conditional structures.
In this article, you will learn how to create a C program to check if a number is even or odd. Practical examples will help you understand the implementation and usage of conditional statements in C for this purpose.
Basic Even or Odd Check
Create a Function to Determine Evenness
Start by defining a function that takes an integer as its argument.
Inside the function, use the modulus operator
%
to test if the number is divisible by 2.If the number is divisible by 2, return
true
indicating even; otherwise, returnfalse
.c#include <stdio.h> #include <stdbool.h> bool isEven(int num) { return (num % 2 == 0); }
The function
isEven
returnstrue
ifnum
is divisible by 2, indicating the number is even. If not, it returnsfalse
, implying the number is odd.
Main Function to Test Even or Odd
Define the
main()
function where you prompt the user for a number.Use the
isEven
function to check the number and display the appropriate message based on whether the number is even or odd.cint main() { int number; printf("Enter an integer: "); scanf("%d", &number); if (isEven(number)) { printf("%d is even.\n", number); } else { printf("%d is odd.\n", number); } return 0; }
This
main
function reads an integer from the user and checks its evenness using theisEven
function. It then prints whether the given number is even or odd.
Conclusion
Creating a C program to check whether a number is even or odd showcases basic programming skills involving input/output operations and conditional statements. By following through with these examples, you improve your ability to handle fundamental data manipulation and improve clarity in programming through the creation of specialized functions. Continue experimenting with these foundations to enhance your ability in C programming for various applications.
No comments yet.