[Programming] Question 14: Write a Program to check whether a number is prime or not

Learn how to write a C program to determine whether a given number is prime. This guide provides a step-by-step explanation of how to implement a function that checks for primality by testing divisibility from 2 up to the square root of the number. The tutorial includes sample code, explanations of the logic used, and tips for optimizing the program.

#include <stdio.h>

int main() {
	int num, i, flag = 0;

	printf("Enter a positive integer: ");
	scanf("%d", &num);

	for (i = 2; i <= num / 2; ++i) {
		if (num % i == 0) {
			flag = 1;
			break;
		}
	}

	if (num == 1) {
		printf("1 is neither prime nor composite.\n");
	} 
	else {
		if (flag == 0)
			printf("%d is a prime number.\n", num);
		else
			printf("%d is not a prime number.\n", num);
	}

	return 0;
} 

Inside the main() function:

- An integer variable num is declared to store the input number.

- The user is prompted to enter a positive integer.

- A for loop is used to iterate from 2 to num/2.

- Within the loop, it checks if the number is divisible by any number other than 1 and itself.

- If the number is prime, it sets flag to 0, otherwise to 1.

- Finally, it prints whether the number is prime or not based on the value of flag.



Featured Posts

Leetcode 4. Median of Two Sorted Arrays

  4. Median of Two Sorted Arrays Hard Given two sorted arrays  nums1  and  nums2  of size  m  and  n  respectively, return  the median  of t...

Popular Posts