I hope you are doing well everyone. I was given this homework by my teacher.
Which is the problem below:
Write a program that will ask for n positive whole numbers. Your program will only stop asking for a number if the input number is 0 or < 0. From these inputs, determine all the prime numbers. After determining the prime numbers, write a menu option shown below:
[A] Display One’s
[B] Display Ten’s
[C] Display Hundred’s
[D] Display Thousand’s
If the user presses on of these options, then it will display what is being asked. To further understand and shorten the instructions, an illustration is provided below.
Input numbers: 123, 112, 1377, 2, 13, 0
Prime numbers: 123 1377 2 13
If the user presses ‘A’, then the output is
123 = 3
1377 = 7
2 = 2
13 = 3
If the user presses ‘B’, then the output is
123 = 23
1377 = 77
2 = 0
13 = 13
If the user presses ‘C’, then the output is
123 = 123
1377 = 377
2 = 0
13 = 0
If the user presses ‘D’, then the output is
123 = 0
1377 = 1377
2 = 0
13 = 0
I've written a program that I thought would solve the problem, but somehow after I input a character (A,B,C,D) the program immediately terminates? If someone could point any other mistakes or have any suggestions in mind. I'll be open to them and I'll be grateful. Thanks so much in advance. :))
#include<stdio.h>
int isPrime(int num);
void Sort(char sort, int psize, int* prime);
int main ()
{
int psize=0;
int i, num=1;
int arr[1000], prime[1000];
char sort;
do
{
printf("Enter array element:");
scanf("%d", &num);
if(num<=0) break;
if(isPrime(num))
{
prime[psize]= num; //assign to prime array if it is a prime
psize++;
}
} while(num>0);
printf("\nEnter [A] to Display One's\nEnter[B] Display Ten's\nEnter[C]Display Hundred's\nEnter[D]Display Thousand's");
scanf("%c", &sort);
Sort(sort, psize, prime);
}
int isPrime (int num)
{
int i, flag=1;
for(i=2;i<num;i++)
{
if(num%i==0)
{
flag=0;
break;
}
}
return flag;
}
void Sort(char sort, int psize, int* prime)
{
int i, ans;
if(sort == 'A'){
printf("Ones\n");
for(i=0;i<psize;i++)
{
ans = prime[i] % 10;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'B'){
printf("Tens\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 10)
ans = prime[i] % 100;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'C'){
printf("Hundreds\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 100)
ans = prime[i] % 1000;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'D'){
printf("Thousands\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 1000)
ans = prime[i] % 10000;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
}