Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to fill an array with the first N prime numbers in C

1 Answer

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

#define N 10

bool isPrime(int num) {
    for (int i = 2; i <= num / 2; i++) {
        if (num % i == 0) {
            return false;
        }
    }

    return true;
}

void fill_array_with_N_prime_numbers(int arr[], int size) {
    int num = 1;

    for (int i = 0; i < size; i++) {
        while (!isPrime(++num)) {}

        arr[i] = num;
    }
}

int main() {
    int arr[N];

    fill_array_with_N_prime_numbers(arr, N);

    for (int i = 0; i < N; i++) {
        printf("%3d", arr[i]);
    }

    return 0;
}



/*
run:

  2  3  5  7 11 13 17 19 23 29

*/

 



answered Feb 17, 2024 by avibootz
edited Feb 17, 2024 by avibootz

Related questions

1 answer 96 views
1 answer 158 views
158 views asked Feb 17, 2024 by avibootz
1 answer 257 views
1 answer 139 views
1 answer 114 views
1 answer 95 views
1 answer 132 views
...