Function Assignment 2 — Check Whether a Number Is Prime Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check Whether a Number Is Prime Using a Function

📑 On this page:
  • What is a prime number?
  • Designing the isPrime function
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to write a function that returns a boolean answer (1 = prime, 0 = not prime)
  • How to handle edge cases early in a function to simplify the main logic
  • Why checking divisors up to √n is enough (and why it matters)
  • How the math.h library's sqrt function fits into the loop bound
  • How to test a function by calling it on a range of inputs

What is a prime number?

A prime number is a whole number greater than 1 that has exactly two divisors: 1 and itself. So 2, 3, 5, 7, 11, 13, 17, 19, 23, and so on are prime. Numbers like 4, 6, 8, 9, 10, and 12 are not — they can be divided evenly by something other than 1 and themselves. And 0 and 1 are not prime, by definition.

The straightforward way to test primality is to check divisibility: try dividing n by every number from 2 up to n-1. If any of those divisions has no remainder, then n is composite. If none of them divide evenly, then n is prime. That works — but it's slow. For a number like 1,000,003, you'd do nearly a million divisions.

The standard optimization is to stop at √n. Why? Because if n has any factor greater than √n, it must also have a factor smaller than √n — the two factors multiply to give n. So if you don't find a divisor by the time you reach √n, you never will. For 1,000,003, you'd only need to check up to about 1,000 — a thousand times faster. That's the version most people write, and the one we'll use here.

We'll wrap the logic in a function called isPrime that takes one int and returns an int: 1 if prime, 0 if not. Using an int instead of a dedicated boolean type is the traditional C convention — C didn't have a built-in bool until C99, and even now, returning int is common in code that needs to interop with older compilers. It works the same way: 0 is false, anything else is true.

💡 In one line: write a function int isPrime(int n) that handles 0, 1, and small numbers specially, then loops from 2 to √n checking for divisors. Return 1 if none are found, 0 otherwise. Call it from main.

A number flows through the isPrime function, which returns 1 if prime and 0 if not.

Designing the isPrime function

There are three "situations" the function has to handle, and it helps to think of them in order:

Input What it is Return
n ≤ 10 and 1 aren't prime; negatives aren't either0
n = 2 or n = 3The two smallest primes; the loop bound would be tricky1
n = 4, 6, 8, ...Even numbers greater than 2 — composite0 (the loop catches this quickly)
n = 5, 7, 11, ...Odd numbers that might be prime1 or 0 depending on divisors

The first check is easy: if n <= 1, return 0 immediately. That eliminates 0, 1, and any negative input in one line. If n is 2 or 3, return 1 immediately — we know they're prime, and we save a loop iteration. After those two guards, n is at least 4, and we can check divisors from 2 to √n without worrying about edge cases.

That gives us the prototype:

int isPrime(int n);
                                

And the core logic:

if (n <= 1) return 0;
if (n == 2 || n == 3) return 1;

for (int i = 2; i * i <= n; i++) {
    if (n % i == 0) return 0;
}

return 1;
                                

A note on the loop condition: i * i <= n is equivalent to i <= sqrt(n) but faster — no floating-point math, no <math.h> include, no rounding errors. For small numbers, the difference is negligible, but for large numbers it's meaningful. It's also more robust: floating-point sqrt can be slightly off for perfect squares, whereas integer multiplication is exact.

🎯 Key idea: check for divisibility up to √n only. If n has a divisor greater than √n, the corresponding co-factor is less than √n — so the smaller factor would have already been caught.

Complete C Program

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

#include <stdio.h>

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

int main(void) {
    int n;

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

    if (isPrime(n)) {
        printf("%d is a prime number.\n", n);
    } else {
        printf("%d is not a prime number.\n", n);
    }

    return 0;
}

/* Function definition */
int isPrime(int n) {
    if (n <= 1) return 0;
    if (n == 2 || n == 3) return 1;

    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return 0;
    }

    return 1;
}
                                    

And here's a version that tests isPrime across a range — useful for verifying the function's correctness:

Variant: print all primes up to 50

#include <stdio.h>

int isPrime(int n) {
    if (n <= 1) return 0;
    if (n == 2 || n == 3) return 1;

    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) return 0;
    }
    return 1;
}

int main(void) {
    printf("Prime numbers from 1 to 50:\n");
    for (int i = 1; i <= 50; i++) {
        if (isPrime(i)) {
            printf("%d ", i);
        }
    }
    printf("\n");
    return 0;
}
                                    

This second version is worth running first — you can eyeball the output against a known list of primes and confirm the function is behaving. If something's wrong, it'll show up immediately. Once the range test looks right, testing individual inputs is just icing.

Program Output

A typical run of the first program:

Enter a positive integer: 17
17 is a prime number.
                                

And with a composite number:

Enter a positive integer: 91
91 is not a prime number.
                                

Edge cases — 1, 2, and 0:

Enter a positive integer: 1
1 is not a prime number.

Enter a positive integer: 2
2 is a prime number.

Enter a positive integer: 0
0 is not a prime number.
                                

And the range-testing version:

Prime numbers from 1 to 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
                                

That list is correct — every number in it has exactly two divisors, and no prime less than 50 is missing. The function works.

Step-by-Step Explanation

Let's walk through the function and then trace a call.

1. The first guard: if (n <= 1) return 0;

This handles 0, 1, and every negative number in one line. Those are not prime by definition. Returning 0 early means the rest of the function can assume n ≥ 2 — a cleaner contract that simplifies everything that follows.

2. The second guard: if (n == 2 || n == 3) return 1;

2 and 3 are prime. We could let the loop handle them, but the loop condition i * i <= n gives us a subtlety: for n = 2, we'd start with i = 2, and 2 * 2 = 4 > 2, so the loop wouldn't run — and we'd fall through to return 1. That's correct, but it's a bit sneaky. Returning early for 2 and 3 makes the function easier to reason about: after these guards, n ≥ 4, and the loop is guaranteed to do at least one meaningful comparison.

3. The loop: for (int i = 2; i * i <= n; i++)

Start at 2, go up to √n. The condition i * i <= n means the loop continues while i² ≤ n, i.e., while i ≤ √n. Both bounds are exact integers, so there's no floating-point comparison — which is why this is preferred over i <= sqrt(n).

4. The divisor check: if (n % i == 0) return 0;

If n is divisible by i, then n has a divisor other than 1 and itself — so it's not prime. Returning 0 immediately is fine: we don't need to find all divisors, just one. The moment we see one, the answer is settled.

5. Falling through: return 1;

If the loop finishes without ever returning 0, then no divisor was found in the range [2, √n], so there's no divisor anywhere. The number is prime. Return 1.

6. Tracing a call: isPrime(17)

  1. 17 <= 1? No. Continue.
  2. 17 == 2 || 17 == 3? No. Continue.
  3. i = 2: 2 * 2 = 4 ≤ 17? Yes. 17 % 2 = 1. Not zero, continue.
  4. i = 3: 3 * 3 = 9 ≤ 17? Yes. 17 % 3 = 2. Continue.
  5. i = 4: 4 * 4 = 16 ≤ 17? Yes. 17 % 4 = 1. Continue.
  6. i = 5: 5 * 5 = 25 ≤ 17? No. Loop ends.
  7. Return 1. 17 is prime. ✓

7. Tracing a call: isPrime(91)

  1. 91 <= 1? No. Continue.
  2. 91 == 2 || 91 == 3? No. Continue.
  3. i = 2: 91 % 2 = 1. Continue.
  4. i = 3: 91 % 3 = 1. Continue.
  5. i = 4: 91 % 4 = 3. Continue.
  6. i = 5: 91 % 5 = 1. Continue.
  7. i = 6: 91 % 6 = 1. Continue.
  8. i = 7: 91 % 7 = 0. Return 0. ✓

The loop stopped early — it found 7 as a divisor before reaching √91 ≈ 9.5. That's the efficiency of the early-return approach: as soon as a divisor appears, we stop. No need to check 8, 9, or anything else.

8. Why not check all the way to n-1?

For isPrime(17), checking up to 16 would do 15 modulo operations instead of 3. For larger numbers, the difference grows: isPrime(1,000,003) would do ~500,000 extra operations if we started from 2 and went to 1,000,002 instead of stopping at 1,000. The √n bound is the single most important optimization in primality testing. Everything else — skipping even numbers after 2, using the 6k ± 1 pattern — is a further refinement, but √n is the big win.

9. Why return int instead of bool?

C99 added <stdbool.h> with true and false, and modern C code often uses bool. But returning int is still the convention in older C code, and it's what you'll see in textbooks, legacy codebases, and many interview questions. The semantics are identical: 0 is false, non-zero is true. If you want to use bool, include <stdbool.h> and change the return type — the body stays the same, just with true/false instead of 1/0.

🔍 Try this: modify the loop to check only odd divisors after 2: skip even numbers with i += 2 starting from i = 3. For large numbers, this roughly halves the number of iterations. It's a common micro-optimization in competitive programming.

Frequently Asked Questions

1. Is 1 a prime number?

No. By definition, a prime number has exactly two distinct positive divisors: 1 and itself. For the number 1, those two divisors would be 1 and 1 — the same number, counted once. Mathematically, 1 has only one divisor. The first guard if (n <= 1) return 0; correctly rejects it.

2. Is 2 a prime number?

Yes. 2 is divisible only by 1 and 2. It's the only even prime number — every other even number is divisible by 2. Our function handles it in the if (n == 2 || n == 3) guard, returning 1 immediately.

3. Why do we only check up to √n?

If n has a divisor d > √n, then n = d × k for some integer k. Since d > √n, we must have k < √n — otherwise d × k > √n × √n = n, which contradicts n = d × k. So every divisor greater than √n has a partner smaller than √n. Checking up to √n catches them all.

4. Is i * i <= n safer than i <= sqrt(n)?

Yes, in two ways. First, sqrt on a floating-point value can have rounding issues — for perfect squares, sqrt(9) might return 2.999999999 on some platforms, causing the loop to exit early. Second, i * i stays in integer arithmetic, which is faster and exact. The only caveat is that for very large n (near INT_MAX), i * i could overflow — but at that point you'd need a different primality algorithm anyway.

5. Can I test isPrime on a range of numbers?

Yes — see the second variant above, which prints all primes from 1 to 50. Testing a range is a great way to verify correctness. If the function passes a range test (all known primes show up, no composites sneak in), you can be confident it's correct for any input.

6. What's the fastest way to check if a number is prime?

For small numbers (up to ~10⁶), the trial division method with the √n bound is fast enough. For medium numbers (up to ~10¹²), the Miller–Rabin probabilistic test is much faster. For very large numbers (cryptographic sizes, 2048+ bits), you'd use probabilistic tests in practice. Our implementation is fine for learning and for typical interview problems. For production code with adversarial input, you'd use a library.

💡 Tip: After this works, try the odd-only optimization: after handling 2, loop i = 3; i * i <= n; i += 2. For 1,000,003, this halves the number of iterations. Then try the 6k ± 1 optimization — checking i and i+2 for i = 6, 12, 18, ... — which skips all multiples of 2 and 3. Each refinement is a small win, and the progression is worth understanding.

📖 Related Tutorials

  • Introduction to Functions in C
  • Need for User-Defined Functions
  • Function Definition
  • Function Declaration
  • Types of Functions
  • Loop FAQ
  • All 33 Function Assignments

Previous Topic: -->> 1. Find the Sum of Two Integers Using a Function   ||   Next Topic: -->> 3. Find the nth Term of the Fibonacci Series 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.