• Write the function prime that checks if a number is prime or not. The function returns 1 if the number is prime and 0 otherwise.
  • Write a function ReadArray that allows to read the value of an array of size M. All the elements of the array should be between 10 and 100.
  • Write a main program that declares two arrays of maximum size 20. The program should prompts the user for the effective arrays size (should be positive), read their values using the function and then it checks if the two arrays contain the same number of prime numbers.

Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <math.h>
#define NMAX 20

int READARRAY(int TAB[])
{
	int I, M;
	do
	{
		printf("Size of the array (max.%d) : ", NMAX);
		scanf("%d", &M); 
	} while (M<0 || M>NMAX);

	for (I = 0; I<M; I++)
	{
	    do{
		    printf("Element[%d] : ", I);
		    scanf("%d", &TAB[I]);
	    }while(TAB[I]<10 ||TAB[I]>100 );
	}
	return M;
}


int isPrime(int nb)
{
	int i;

	for (i = 2; i <= sqrt(nb); i++)
		if (nb%i == 0)
			return 0;
	
	return 1;
}

int snpn(int T1[], int S1, int T2[], int S2)
{
    int i;
    int c1=0, c2=0;
    for(i=0;i<S1;i++)
        if(isPrime(T1[i]))
            c1++;
    for(i=0;i<S2;i++)
        if(isPrime(T2[i]))
            c2++;  
    return c1==c2;
}

int main()
{
 
    int S1, S2, T1[NMAX], T2[NMAX];
    
	S1 = READARRAY(T1);
	S2 = READARRAY(T2);
	printf("Contains same nb of prime nbs? %d\n",snpn(T1,S1,T2,S2));
 
	return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Add into a table based on coalesced hash without separated zones