Here's a program to print prime numbers in C:
#include #include int main() { int i, num, isPrime; printf("Enter an integer: "); scanf("%d", &num); for(i=2; i<=num; i++) { isPrime = 1; int j; for(j=2; j<=sqrt(i); j++) { if(i%j==0) { isPrime = 0; break; } } if(isPrime == 1) { printf("%d\n", i); } } return 0; }
Explanation:
The program takes an integer input from the user and stores it in the variable num
.
A for loop is used to iterate from 2 to the input number num
.
Another for loop is used inside the first loop to check if the current number is divisible by any number between 2 and its square root. If it is divisible, the isPrime
flag is set to 0, and the inner loop breaks.
If the isPrime
flag is still 1 after the inner loop, it means the number is prime, and it is printed to the console.
Note: This program uses the sqrt
function from the math.h
library to calculate the square root of a number.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.