Let’s write a C program to print list of Prime numbers. This program will be useful for you to understand the basic concepts in C programming such as,
- How to get a user input value in C
- How to write for loop in C
- How to get the remainder value using modules in C
See the script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include <stdio.h> int main() { int limit, i=0, j=0; //print a string about the program printf("Let's print Prime Numbers\n"); printf("Enter the Limit: "); //get the limit scanf("%d", &limit); //loop till i equals to limit for (i = 1; i <= limit; i++) { int c = 0; for (j = 1; j <= i; j++) { // % modules will give the reminder value, so if the reminder is 0 then it is divisible if (i % j == 0) { //increment the value of c c++; } } //if the value of c is 2 then it is a prime number //because a prime number should be exactly divisible by 2 times only (itself and 1) if (c == 2) { printf("%d\n", i); } } return 0; } |
The output of the program will be:
Just go through the comments in the above program to understand each line. Bye!