Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

This is a program that asks the user to enter a number greater than 2 to test its primality, that is, if the number is

This is a program that asks the user to enter a number greater than 2 to test its primality, that is, if the number is a prime or not. The program defines a function is_prime that accepts an integer and returns a bool value to indicate if the number is prime or not. The program keeps on testing various numbers until -1 is entered. Please read the comments and fix the bugs in the program as per required by the comments.

#include #include void get_valid_number(int *n); bool is_prime(int x)

//main() uses a sentinel controlled loop to test the primality of numbers //, without knowing how many numbers to be tested. // -1 is the sentinel value // the loop repeats the cycle of read->test->process->read ... int main() { int n; get_valid_number(&n); //read while (n!=-1) { //test //process if (is_prime(n)) { printf("%d is a prime number! ", n); } else { printf("%d is not a prime number! ", n); } int n; //read again then loop back to test get_valid_number(&n); } return 0; }

bool is_prime(int n) { //if n is divisible by any number greater or equal to 2 and less than n, then n is not prime. for (int i = 2; i < n; i++) { if (n%i == 0) { break; } } return !(n%i==0);

}

void get_valid_number(int * n) { //The valid number is either -1 (to exit the program) or an integer greater than 2. //A loop is used to implement input validation, that is, user will be asked to //enter a valid number over and over again until a valid number is received. printf("Please enter an integer greater than 2 to test its primality, enter -1 to exit "); scanf("%d", n); while (*n <= 2 || *n != -1) { printf("Please enter an integer greater than 2 to test its primality, enter -1 to exit "); scanf("%d", n); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

What are key elements of leading others effectively?

Answered: 1 week ago