C Tutorial

C Project: Prime Finder

List every prime up to a limit with trial division, then count how many you found.

What you will build

A prime number is an integer greater than 1 whose only positive divisors are 1 and itself. Trial division tests those divisors. This project prints every prime less than or equal to 50 and then prints how many there were.

Use stdbool.h for bool, true, and false. C has no built-in boolean type unless you include that header. Compile with Try it in C at/c/try — gcc.

Trial division

For a candidate n, try divisors from 2 upward. If any divisor splits n evenly,n is composite. You can stop when d * d > n: a larger factor would already have a matching smaller partner you would have seen.

Example

#include <stdio.h>
#include <stdbool.h>

bool is_prime(int n) {
  if (n < 2) {
    return false;
  }
  for (int d = 2; d * d <= n; d++) {
    if (n % d == 0) {
      return false;
    }
  }
  return true;
}

int main(void) {
  printf("2: %s\n", is_prime(2) ? "prime" : "not");
  printf("9: %s\n", is_prime(9) ? "prime" : "not");
  printf("13: %s\n", is_prime(13) ? "prime" : "not");
  printf("1: %s\n", is_prime(1) ? "prime" : "not");
  return 0;
}

2 is prime. 9 fails because 3 divides it. 13 has no divisor with d * d <= 13 except trials that leave a remainder. 1 is not prime by definition.

List primes through 50

Loop n from 2 through 50. If is_prime(n) is true, print n and add one to a counter. After the loop, print the count. That pair of outputs is the project: the list and the total.

Example

#include <stdio.h>
#include <stdbool.h>

bool is_prime(int n) {
  if (n < 2) {
    return false;
  }
  for (int d = 2; d * d <= n; d++) {
    if (n % d == 0) {
      return false;
    }
  }
  return true;
}

int main(void) {
  int count = 0;
  int limit = 50;

  printf("primes <= %d:\n", limit);
  for (int n = 2; n <= limit; n++) {
    if (is_prime(n)) {
      printf("%d ", n);
      count++;
    }
  }
  printf("\ncount: %d\n", count);
  return 0;
}

You should see 15 primes and a last value of 47. Compile at /c/try. Stay on the C track; this is not the Python, HTML, or C++ editor.

Check the list by hand

The primes at most 50 are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, and 47. Fifteen numbers. If your program prints 16, you likely treated 1 as prime. If it stops at 49, the loop used n < limitinstead of n <= limit — 47 would still appear, but a later limit that is itself prime would be dropped.

Example

#include <stdio.h>
#include <stdbool.h>

bool is_prime(int n) {
  if (n < 2) {
    return false;
  }
  for (int d = 2; d * d <= n; d++) {
    if (n % d == 0) {
      return false;
    }
  }
  return true;
}

int main(void) {
  int expected[] = {2,  3,  5,  7,  11, 13, 17, 19,
                    23, 29, 31, 37, 41, 43, 47};
  int want = (int)(sizeof expected / sizeof expected[0]);
  int k = 0;

  for (int n = 2; n <= 50; n++) {
    if (is_prime(n)) {
      if (k >= want || n != expected[k]) {
        printf("mismatch at slot %d\n", k);
        return 1;
      }
      k++;
    }
  }
  printf("matched %d primes <= 50\n", k);
  return 0;
}

Why 2 is special

2 is the only even prime. After you know n is odd, you could trial only odd divisors. The simple loop from 2 is enough for a limit of 50 and stays easy to read. Do not start the divisor loop at 1:n % 1 is always 0, so every number would look composite.

Example

#include <stdio.h>
#include <stdbool.h>

bool is_prime(int n) {
  if (n < 2) {
    return false;
  }
  if (n == 2) {
    return true;
  }
  if (n % 2 == 0) {
    return false;
  }
  for (int d = 3; d * d <= n; d += 2) {
    if (n % d == 0) {
      return false;
    }
  }
  return true;
}

int main(void) {
  int count = 0;
  for (int n = 2; n <= 50; n++) {
    if (is_prime(n)) {
      printf("%d ", n);
      count++;
    }
  }
  printf("\ncount: %d\n", count);
  return 0;
}

The printed list and the count must match the first full program. The even-skip is only a faster form of the same trial division.

Common mistakes

  • Using bool without #include <stdbool.h>. That is not C++. Include the header or use int with 0 and 1.
  • Testing divisors with d <= n. Then n % n == 0 marks every number composite. Stop at d * d <= n.
  • Starting candidates at 0 or 1. Both are not prime.
  • Using math.h and sqrt when d * d <= n already bounds the loop and needs no extra library.

Practice

  1. Change the limit to 20, then to 100, and print both counts. For 20 the count is 8.
  2. Print only the primes that are also one less than a multiple of 4 (5, 13, 17, …) within 50.
  3. Write a second function that returns how many primes are at most limit, and call it from main instead of counting in the print loop.

FAQ: C Project: Prime Finder

Common questions about this page.

What is the StudyGrid C tutorial?

The StudyGrid C tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, pointers, structs, files, and the standard library. Each chapter has copy-and-run examples.

Should I run c primes project examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c primes project in this C C lesson (C Project: Prime Finder).

Is the C editor the same as Try Python, Try HTML, or Try C++?

No. Try C compiles with gcc at /c/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. Try C++ stays at /cpp/try. C lessons never open those editors.

Do I need to install a compiler to learn C?

No. Open a chapter, click Try it in C, and compile in the browser. You can also download a .c file and compile locally with gcc.

Where should I start the C tutorial?

Start at C Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After pointers, open C Examples, then files and bitwise. Use Next at the bottom of each chapter.

Is the C tutorial free?

Yes. The C workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.