EQuestionAnswers.com Computer/Electronics Questions and Answers
C, C++, VC++, COM/DCOM, DLL and more
#Login #Sign up  Facebook Twitter TGoogle+
 

Write a program to print the prime numbers between 1 and 100

Abstract

C Source code program to print all numbers between 1 and 100. This program can be altered to print all prime numbers between a range given by user. A prime number is one which is only dividable by 1 or by the the number itself. It should not be dividable by any other numbers. is_prime() is the core routine to check if number is prime or not. It starts from 2 till (number - 1) to check if the number is dividable. If divisible then remainder will be zero and prime check should fail else it will continue till (number - 1). We have a main loop to take care the entire range. This loop start from 1 till 100. This upper range can be changed by taking input from user. Main loop calls is_prime() function and passes the number as the argument and checks the return value. If it returns true the it prints the number can continue to the next number. Main loop should list all prime number as it completes its entire range.

Source Code

#include<stdio.h>
#include<conio.h>
#define TRUE 1
#define FALSE 0
/* Check if given number is prime or not */
bool is_prime(unsigned int number)
{
10    unsigned int i;
11    for (= 2; i < number; i++)
12    {
13      /* remainder zero means not prime */
14      if((number % i) == 0) {
15        return FALSE;
16      }
17    }
18    return TRUE;
19  }
20 
21  /* Print all prime numbers in a given range */
22  /* Define USER_RANGE if you want range from user */
23  int main(int argc, char* argv[])
24  {
25    unsigned int index;
26    unsigned int lrange = 1;
27    unsigned int hrange = 100;
28  #ifdef USER_RANGE
29    printf("Print Prime numbers from #");
30    scanf("%u", &lrange);
31    printf("Print Prime numbers till #");
32    scanf("%u", &hrange);
33  #endif
34    for(index = lrange; index <= hrange; index++)
35    {
36      if(is_prime(index) != FALSE){
37        printf("%u,", index);
38      }
39    }
40    printf("\b.");
41    return 0;
42  }
43 

Output

1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97.

Find More from our code collection
Armstrong number, binary number to a decimal number, bubble sort, decimal number to binary number, factorial of the given number factors, fibonacci numbers, HCF and LCM, matrix, mergesort, salary of the employee. palindrome, quadratic equation, star patterns, series etc. and much more...
#Return to Example Source Code