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)
{
  unsigned int i;
  for (= 2; i < number; i++)
  {
    /* remainder zero means not prime */
    if((number % i) == 0) {
      return FALSE;
    }
  }
  return TRUE;
}

/* Print all prime numbers in a given range */
/* Define USER_RANGE if you want range from user */
int main(int argc, char* argv[])
{
  unsigned int index;
  unsigned int lrange = 1;
  unsigned int hrange = 100;
#ifdef USER_RANGE
  printf("Print Prime numbers from #");
  scanf("%u", &lrange);
  printf("Print Prime numbers till #");
  scanf("%u", &hrange);
#endif
  for(index = lrange; index <= hrange; index++)
  {
    if(is_prime(index) != FALSE){
      printf("%u,", index);
    }
  }
  printf("\b.");
  return 0;
}

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