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 */
#include<stdio.h>

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

     printf("Enter any number \n");
     scanf("%d",&n);

     printf(" All prime numbers are -\n");
     for(i=2;i<=n;i++)
     {
             ct=0;

             for(j=2;j<i;j++)
             {
                     if(i%j==0)
                     {
                               ct=1;
                               break;
                     }
             }
             if(ct==0)
             {
                 printf("%d \t",i);
             }
     }
     getch();
}

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

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

    1. Mitchell says:

      Manolo:Duvido que a medicina consiga curar realmente todas as doenças – mesmo nos países mais ricos e delvenosvidos. Mas com o passar dos anos provavelmente conseguirá curar muitas mais e desenvolverá também melhores tratamentos paliativos. Isso diminuirá o número de casos de doença incurável e sofrimento intenso. Mas não resolverá o problema ético da eutanásia.

  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 = [];
    for(i=2;i<n;i++){
    limit = i/2;
    len = result.length;
    isPrime = true;
    for(j=0;len && result[j]<=limit;j++){
    if(i%result[j] == 0){
    isPrime = false;
    break;
    }
    }
    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>