Lab 2: Prime Numbers

You will learn about preprocessor directives in C.

Read These Pages:


You will need to install a GCC compiler on your computer.

  • See Windows 10: Setup C Environment on how to set up Windows 10 to compile and execute C.

  • Don’t know if you have GCC installed? Open a prompt and run command:

    gcc --version
    # Ubuntu shell Output
    user@DESKTOP-Z4T37ER:~$ gcc --version
    gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
    Copyright (C) 2017 Free Software Foundation, Inc.
    # Windows CMD Output
    C:\Users\user>gcc --version
    gcc ( GCC-8.2.0-3) 8.2.0
    Copyright (C) 2018 Free Software Foundation, Inc.


You will create a C program that determines if a given number is a prime number.

A prime number is a a whole number that cannot be made by multiplying other whole numbers. less than or equal to n:

Task 1: Create a bool.h file

C does not have a native bool type, there is a library called stdbool.h that offers that functionality. Instead of using it, let’s build our own!


After this exercise, the safest option is to use stdbool.h :) This activity provides an example of how to create a simple .h file that contains a custom data type.

Traditional programing treats a 0 as FALSE and 1 as TRUE. However, any non-zero value in C is TRUE, and only 0 is FALSE. That means that expressions like int a = -8 and int = 2350 are evaluated as TRUE.

  1. Read the discussion on on Using boolean values in C on Stack Overflow.

  2. Choose option of creating your bool type.

  3. Create file called mybool.h

  4. Create a new data type, such as my_bool

Task 2: Create your Prime Function

  1. Start with the command line template from C Templates.

  2. Include your mybool.h file:

    #include "mybool.h"
    1. Verify that your file compiles without any errors or warnings.

    2. See How to write your own header file in C for additional information.

  3. Pass the value in using the command line

  4. Create a function with this prototype (or using your own type):

    my_bool number_is_prime(int);
  5. Develop the function. You can use Google to help you.

  6. Print the result in main() if the number is prime or not

Task 3: Test Random Generated Numbers

  1. Implement a random number algorithm using

  2. Use the #define macro to set the maximum number of random numbers to find.

    #define MAX   25
    int main() {
    . . .
    for (i = 0; i < MAX; ++i)
        // get random number
    . . .
  3. Generate 25 numbers in a loop, test each number for prime.

  4. Were any numbers prime?

  5. If not, increase the value till you find one!