Check Primeness of an Array

Beginner

Introduction

In this lab, we will learn how to find the count of prime numbers in an array in C++. We will write a program to check if a number is prime or not and traverse through each element of an array, checking if it is prime. If an element is prime, we will increment a counter.

Setting up the file

Create a file named main.cpp in the ~/project directory using the following command:

touch ~/project/main.cpp

Open the file using a command-line text editor and enter the following code:

#include <iostream>
using namespace std;

int main() {
    return 0;
}

Defining the checkPrime function

We define a function called checkPrime which takes an integer as input and returns 0 or 1 based on if it is prime or not. We will use this function to check if each element of the array is prime. Add the following code to the main.cpp file:

// Function to check if number is prime
int checkPrime(int num){
    if (num <= 1){
        return 0;
    }
    // Check from 2 to half of num
    for (int j = 2; j <= num/2; j++){
        if (num % j == 0){
            return 0;
        }
    }
    return 1;
}

Counting the number of primes in the array

We create an array of integers and count the number of primes using the checkPrime function for each element of the array. If an element is prime, we increment a counter. Add the following code to the main.cpp file:

int main(){
    int arr[] = { 1, 3, 5, 4, 8, 13, 11 };
    int n = 7;
    int count = 0;
    int isprime = 0;
    // Traverse through each element of array and check if it is a prime
    for(int i = 0; i < n; i++){
        isprime = checkPrime(arr[i]);
        if(isprime == 1){
            count++;
        }
    }
    cout << "Count of number of primes in array: " << count << endl;
    return 0;
}

Compiling and running the program

Compile the program using the following command:

g++ main.cpp -o main

Run the program using the following command:

./main

Viewing the output

The output should be as follows:

Count of number of primes in array: 4

Summary

In this lab, we learned how to count the number of primes in an array in C++. We wrote a function to check if a number is prime and traversed through each element of the array, incrementing a counter for each prime element.

Other Tutorials you may like