C Program to print prime numbers up to the inputted number

Write a program in the C programming language to print all the prime numbers up to the inputted number. This program is being made by using the nested for loop statements and if statements. Below is the code of this C program –

/* C program to print prime numbers */

void main()
     int n,i,j,ct=0;

     printf("Enter any number \n");

     printf(" All prime numbers are -\n");

                 printf("%d \t",i);

Description – The outer for loop is used to create the numbers up to the limit and the nested loop is used to check if the numbers are prime or not and if any of the number is prime then it prints the number.
Input –  15
Output – All prime numbers are – 2   3   5   7   11   13

yashan has written 69 articles

10 thoughts on “C Program to print prime numbers up to the inputted number

  1. Jonathan says:

    Ct variable acts as a flag variable. When ct=1 of that particular value of i, then that value is not a prime number which will not be printed. Hope you got it. :)

  2. Rohit Sengar says:

    You can optimize you code to the following,

    function getPrimesTill(n){
    var i, j, len, limit, result = [];
    limit = i/2;
    len = result.length;
    isPrime = true;
    for(j=0;len && result[j]<=limit;j++){
    if(i%result[j] == 0){
    isPrime = false;
    if(isPrime) result.push(i);
    return result;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>