C Exercises: Check whether a given number is prime or not
C For Loop: Exercise-32 with Solution
Write a C program to determine whether a given number is prime or not.
Visual Presentation:

Sample Solution:
C Code:
#include <stdio.h> // Include the standard input/output header file.
int main() {
int num, i, ctr = 0; // Declare variables for user input, loop control, and a counter.
// Prompt the user to input a number.
printf("Input a number: ");
scanf("%d", &num); // Read the input number from the user.
// Start a loop to check for factors of the input number.
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) { // If the input number is divisible by 'i'.
ctr++; // Increment the counter.
break; // Exit the loop since a factor has been found.
}
}
// If no factors were found and the number is not 1.
if (ctr == 0 && num != 1)
printf("%d is a prime number.\n", num); // Print that the number is prime.
else
printf("%d is not a prime number.\n", num); // Print that the number is not prime.
return 0; // Return 0 to indicate successful execution.
}
Sample Output:
Input a number: 13 13 is a prime number.
Flowchart:

C Programming Code Editor:
Previous: Write a program in C to display the pattern like a diamond.
Next: Write a C program to display Pascal's triangle
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join