Function Assignment 4 — Check Whether a Number Is Even or Odd Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check Whether a Number Is Even or Odd Using a Function

📑 On this page:
  • What makes a number even or odd?
  • Designing the isEven function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How the modulo operator (%) determines even/odd
  • How to write a function that returns a true/false answer
  • How the modulo result for negative numbers behaves in C
  • How to name and structure a check function for reusability
  • How to test the function on positive, negative, and zero inputs

What makes a number even or odd?

A number is even if it can be divided by 2 with no remainder. It's odd if dividing by 2 leaves a remainder of 1 (or -1, for negatives). So 4, 10, 100, 0, and -6 are even. 3, 7, 99, and -5 are odd. The test is the same in C as it is in elementary arithmetic: n % 2 — the remainder after dividing by 2.

The simplest possible function is just return n % 2 == 0;. That expression evaluates to 1 if n is even, 0 if it's odd. It's a one-line function with no conditionals, no loops, no edge cases — practically a perfect example of "do one thing and do it well." You could write the test directly in main, but wrapping it in a named function makes the call site read better (if (isEven(x)) is clearer than if (x % 2 == 0) once you've seen it a few times), and it gives you a single place to fix if the definition ever needs to change.

There's one wrinkle worth knowing: negative numbers. In C, the modulo operator preserves the sign of the dividend. So -5 % 2 is -1, not 1. That's why the test must be n % 2 == 0, not n % 2 == 1. The == 0 form works for both positive and negative evens, because both 4 % 2 and -4 % 2 are 0. The == 1 form would incorrectly classify -5 as "not odd" because -5 % 2 == -1, not 1.

💡 In one line: write a function int isEven(int n) that returns n % 2 == 0. It's the simplest possible check — one modulo, one comparison, one return. Works for negatives, zero, and positives.

Numbers flowing into a function that returns 1 for even and 0 for odd.

Designing the isEven function

The function signature is the same pattern you've seen in the previous assignments:

Part Choice Why
Function nameisEvenReads naturally at the call site: if (isEven(n)). The "is" prefix is a common convention for predicate functions.
Parameterint nThe number to check. Using int covers the typical range.
Return typeint1 for even, 0 for odd. The traditional C "boolean" convention. Could also be bool with <stdbool.h>.

That gives us the prototype:

int isEven(int n);
                                

And the entire definition:

int isEven(int n) {
    return n % 2 == 0;
}
                                

That's it. No if statement, no early return, no edge cases. The function is a one-liner because the logic is a one-liner. There's no need to complicate it with structure that doesn't add clarity — sometimes the simplest function is the best function.

A note on the return value: n % 2 == 0 is a comparison, which in C produces an int of 1 (if true) or 0 (if false). So return n % 2 == 0; returns an int — the same type as the function's declared return type. This works perfectly in C, and it's a common idiom. Some style guides prefer return (n % 2 == 0) ? 1 : 0; for explicit clarity, but for a function returning int used as a boolean, the comparison expression is idiomatic.

🎯 Key idea: use n % 2 == 0, not n % 2 == 1. The == 0 form works for negatives; the == 1 form breaks for them because C's modulo preserves the sign of the dividend.

Complete C Program

Program: read an integer, call isEven, print the result

#include <stdio.h>

/* Function prototype */
int isEven(int n);

int main(void) {
    int n;

    printf("Enter an integer: ");
    scanf("%d", &n);

    if (isEven(n)) {
        printf("%d is even.\n", n);
    } else {
        printf("%d is odd.\n", n);
    }

    return 0;
}

/* Function definition */
int isEven(int n) {
    return n % 2 == 0;
}
                                    

And a version that tests a range of numbers — useful for verifying the function on negatives, zero, and positives all at once:

Variant: classify integers from -5 to 5

#include <stdio.h>

int isEven(int n) {
    return n % 2 == 0;
}

int main(void) {
    printf("n     | n %% 2 | parity\n");
    printf("------+-------+--------\n");
    for (int n = -5; n <= 5; n++) {
        printf("%-5d | %-5d | %s\n",
               n, n % 2, isEven(n) ? "even" : "odd");
    }
    return 0;
}
                                    

This second version prints the modulo result alongside the classification, so you can see exactly how negative modulos behave. It's worth running once — the pattern (0, -1, 0, -1, ... for negatives, then 0, 1, 0, 1, ... for positives) makes the "use == 0" rule obvious.

Here's a variant that returns the answer as a string directly — sometimes useful for logging or display:

Variant: function returns const char *

#include <stdio.h>

const char *evenOdd(int n) {
    return (n % 2 == 0) ? "even" : "odd";
}

int main(void) {
    int n;
    printf("Enter an integer: ");
    scanf("%d", &n);
    printf("%d is %s.\n", n, evenOdd(n));
    return 0;
}
                                    

This variant pushes the ternary into the function and returns a string literal. It's less flexible (you can't do anything with the result except print it), but it's tidy for one-off display code. The isEven version is more reusable — you can combine it with other logic later.

Program Output

A typical run of the first program:

Enter an integer: 42
42 is even.
                                

And with an odd number:

Enter an integer: 17
17 is odd.
                                

With zero:

Enter an integer: 0
0 is even.
                                

With a negative even number:

Enter an integer: -8
-8 is even.
                                

With a negative odd number:

Enter an integer: -7
-7 is odd.
                                

And the range-testing variant:

n     | n % 2 | parity
------+-------+--------
-5    | -1    | odd
-4    | 0     | even
-3    | -1    | odd
-2    | 0     | even
-1    | -1    | odd
0     | 0     | even
1     | 1     | odd
2     | 0     | even
3     | 1     | odd
4     | 0     | even
5     | 1     | odd
                                

Notice how the modulo result is -1 for negative odds and 1 for positive odds. That's the C convention — the sign of a % b matches the sign of a. The == 0 test works for both because evenness is symmetric — the sign doesn't matter for even numbers.

Step-by-Step Explanation

Let's walk through the pieces and then trace a few calls.

1. The prototype

int isEven(int n); — same shape as isPrime from assignment 2. One integer in, one integer out. The compiler sees this and knows what to expect when it reaches isEven(n) inside main.

2. The definition

return n % 2 == 0; is a single expression. Let's break it into pieces:

  1. n % 2 computes the remainder after dividing n by 2.
  2. == 0 compares that remainder to 0. The comparison produces an int: 1 if the remainder is 0, 0 otherwise.
  3. return hands that int back to the caller.

No if, no branching, no temporary variable. This is what people mean when they say "the function does exactly one thing."

3. Tracing isEven(42)

  1. 42 % 2 = 0.
  2. 0 == 0 evaluates to 1.
  3. Return 1. The caller's if condition is true. Prints "even." ✓

4. Tracing isEven(17)

  1. 17 % 2 = 1.
  2. 1 == 0 evaluates to 0.
  3. Return 0. The if condition is false, so the else branch runs. Prints "odd." ✓

5. Tracing isEven(-7)

  1. -7 % 2 = -1 (C preserves the sign of the dividend).
  2. -1 == 0 evaluates to 0.
  3. Return 0. Correctly classified as odd. ✓

This trace is why the test must be == 0. If we'd written n % 2 == 1, then -7 % 2 is -1, and -1 == 1 is false — so -7 would be classified as "not odd," which is wrong.

6. Why zero is even

By the standard definition, an integer n is even if there exists an integer k such that n = 2k. For n = 0, that's k = 0, so 0 is even. This matches intuition in many contexts (0 is divisible by 2, 0 is the "start" of the even numbers), and it matches the modulo test: 0 % 2 == 0. If you ever need to handle 0 specially (e.g., reject it as input), do that in main before calling isEven — don't complicate the function itself.

7. Why use a function at all?

You could write if (n % 2 == 0) directly in main. For a single check, that's fine. But once you're checking evenness in multiple places — filtering an array, validating input, formatting output — a named function is worth the tiny overhead. It documents intent, it can be replaced with a faster implementation later without touching call sites, and it's easier to test in isolation. It's also the standard pattern that every predicate function follows.

8. Comparison to isOdd

You could write isOdd(n) { return n % 2 != 0; } — return 1 when the remainder isn't 0. That works too, and it's actually a nice pairing with isEven. But there's a small subtlety: if you write isOdd(n) { return n % 2 == 1; }, it breaks for negative numbers (-7 % 2 == -1, not 1). The != 0 form is the correct one. Most style guides prefer one canonical test — pick isEven or isOdd as the primary, and derive the other as !isEven(n) or !isOdd(n).

🔍 Try this: write isOdd(n) as return n % 2 != 0; and run the range test again. Then try writing it as return n % 2 == 1; and see how the negative odd numbers come out wrong. The comparison between the two versions is a good exercise in understanding how modulo behaves with signs.

Frequently Asked Questions

1. What's the difference between n % 2 == 0 and n & 1 == 0?

The first uses modulo; the second uses bitwise AND. Both test evenness — the low bit of an even number is 0, and n & 1 extracts that bit. The bitwise version is slightly faster on some hardware, but modulo is more readable and what most people expect. Compilers often optimize n % 2 into n & 1 anyway, so the performance difference is negligible. Use n % 2 == 0 for clarity.

2. Does isEven work for long or long long inputs?

Only up to INT_MAX — the int parameter truncates larger values before they enter the function. If you need to support larger integers, change the parameter type to long or long long, and update the prototype accordingly. If you also want to use the same function for multiple types, C doesn't have generics (well, C11 has _Generic, but it's clunky) — you'd write separate functions or use macros.

3. Why not use bool instead of int?

You can — include <stdbool.h> and change the return type to bool. It's clearer intent, and modern code often uses it. The choice between int and bool is largely stylistic. Traditional C code and older textbooks use int; newer code prefers bool. Both work. If you're writing code that will be read by people using different generations of C, int is the safer default because it works on pre-C99 compilers without any extra headers.

4. Is 0 even or odd?

Even. By the standard mathematical definition, an integer is even if it's divisible by 2 with no remainder. 0 % 2 == 0, so 0 is even. This also matches intuition — the evens are ..., -4, -2, 0, 2, 4, ..., and 0 is right in the middle of the sequence. Some people are surprised by this, but it's the standard convention in mathematics and in most programming contexts.

5. Can I write this as a macro instead of a function?

Yes: #define IS_EVEN(n) ((n) % 2 == 0). The parentheses around n and the whole expression are essential — without them, macro expansion can break in surprising ways. For example, IS_EVEN(1 + 1) would expand to 1 + 1 % 2 == 0 if you forgot the parentheses around n, and 1 + 1 % 2 evaluates to 1 + 1 = 2, not 0. Functions are generally safer and easier to debug than macros; use macros only when you have a specific reason (e.g., needing the argument type to be generic).

6. What if the user enters a non-integer like 3.14?

scanf("%d", &n) will stop reading at the decimal point, so 3.14 gives n = 3 and leaves .14 in the input buffer. For most uses this is fine — the function only works with integers. If you need to validate input, read into a char buffer and parse manually, or use scanf's return value to detect format errors. That's a topic for a separate program; for this one, assume the user enters a valid integer.

💡 Tip: Once isEven works, try building a small program that counts even and odd numbers from a list of integers. Or filter an array into two separate arrays — evens and odds. The isEven function becomes a reusable building block for all of these. That's the real value of a well-named predicate function: it just plugs into whatever loop or filter you're writing next.

📖 Related Tutorials

  • Introduction to Functions in C
  • Need for User-Defined Functions
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Relational Operators
  • Arithmetic Operators
  • All 33 Function Assignments

Previous Topic: -->> 3. Find the nth Term of the Fibonacci Series Using a Function   ||   Next Topic: -->> 5. Calculate the Area of a Rectangle Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.