Program to print all prime numbers btw 1 to 100

C Program to print all prime numbers btw 1 to 100..
pls explain the program: What is if(p)??

Code
  1. #include

  2. #include

  3. int main()

  4. {

  5.  int num,n,div,p;

  6.  printf("Enter any number: ");

  7.  scanf("%d", &num);

  8.  for(n=2; n<=num; n++)

  9.  {

  10.   for(div=2; div  {

  11.    if(n%div==0)

  12.    {

  13.      p=0;

  14.      break;

  15.    }

  16.    p=1;

  17.   }

  18.   if(p)

  19.     printf("    %d",n);

  20.  }

  21.  getch();

  22.  

  23. }
Copyright GeekInterview.com

Questions by Pavani Shiny

Showing Answers 1 - 9 of 9 Answers

Code
  1. #include<iostream>

  2. using namespace std;

  3. int main(){

  4. for(int i=1;i<=100;i++){

  5.         int flag=0;

  6.         if(i/2==0||i/2==1)

  7.         {

  8.                 cout<<"prime"<<i<<endl;

  9.                 continue;

  10.         }

  11.         for(int j=2;j<=i/2;j++){

  12.                 if(i%j==0){flag=0; break;}

  13.                 else flag=1;

  14.         }

  15.         if(flag){

  16.                 cout<<"prime "<<i<<endl;

  17.         }

  18. }

  19.  

  20. return 0;

  21. }


Code
  1. #include<iostream>

  2. using namespace std;

  3. int main(){

  4. for(int i=1;i<=100;i++){

  5.         int flag=0;

  6.         if(i/2==0||i/2==1)

  7.         {

  8.                 cout<<"prime"<<i<<endl;

  9.                 continue;

  10.         }

  11.         for(int j=2;j<=i/2;j++){

  12.                 if(i%j==0){flag=0; break;}

  13.                 else flag=1;

  14.         }

  15.         if(flag){

  16.                 cout<<"prime "<<i<<endl;

  17.         }

  18. }

  19.  

  20. return 0;

  21. }

  Was this answer useful?  Yes

Rajkumar Yonzan

  • Feb 24th, 2017
 

// Wap to display all prime number from 1 to 100. //

#include
#include
void main()
{
int i,j,n;
for(n=1;n<=100;n++)
{
i=0;
for(j=1;j<=n;j++)
{
if(n%j==0)
i++;
}
if(i==2)
printf("
%d",n);
getch();
}
}

  Was this answer useful?  Yes

To answer the specific question, "if(p)" is the same thing as "if (p == 1)" or "if (p != 0)". The variable "p" is being used as a flag to indicate whether the current candidate number ("n") is prime or not. Thats being determined by using the modulo operator %. If "a % b == 0", then "a" is evenly divisible by "b". So the program performs "n % div" for all values of "div" from 2 to ... something (that part of the code appears to be missing). If "n % div != 0" for all values of "div", then the number is prime and "p" is set to 1 (true). If "n % div == 0" for any value of "div", then the number is "not" prime and "p" is set to 0 (false).

Code
  1.  

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions