English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

is it possible to write the same program wit same commands without flag and also please describe flag

#include


int main(void){
int j,n,i,flag;
printf("Please enter a number : ");
scanf("%d",&n);
if(n<2) {
printf("\nNo prime numbers available");
return 1;}
printf("Thank you : 2");
for(i=2;i<=n;i++){
for(j=2;j<=i-1;j++){
if(i%j==0){
flag=0;
break;}
flag=1;
}
if(flag==1)
printf("%5d",i);
}

return 0;
}

2006-10-27 21:42:03 · 4 answers · asked by Anonymous in Computers & Internet Programming & Design

4 answers

u need atleast one flag variable. I have reduced ur code. wat i have given is very simple code.

please correct the syntax. but the logic is correct.

flag=1;

for(i=2;i if(n%i==0){
flag=0;
break;
}
}
if(flag==1){
printf("prime");
}
else
printf("not a prime");


//Note:-
/*
n is the number for which it has to be checked for prime.
flag=1 (initially assuming that the given number is prime and reinitializing to 0 after checking the condition in if loop.
*/

2006-10-28 06:43:50 · answer #1 · answered by Sudha P 2 · 0 0

Yes. Instead of for loops you should be using while loops. The flafg here is only used for breaking the loop. You will not need it if you use while loop.

i =2;
while(i<=n)
{
j=2;
while (j<=i-1)
{
if (I%j++ == 0)
{
break; // this will break the loop for j
}
}// end of while for j

if (j == i) printf("%d ",i);
i++;
} //end of while for i
}

2006-10-27 23:00:27 · answer #2 · answered by manoj Ransing 3 · 0 0

//try this
#include
void main()
{
int n,i,flag;
flag=0;
printf("Enter the Number:\t\t");
scanf("%d",&n);
if(n<2)
printf("\n%d is not prime",n);
else
{
for(i=0;i {
if(n%i)
flag=1;
}

if(flag)
printf("%d is not prime",n);
else
printf("%d is prime",n);
}
getch();
}

2006-10-27 21:55:11 · answer #3 · answered by noushad ali 1 · 0 0

fedest.com, questions and answers