Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to read an array of 10 numbers and print the prime numbers?

Status
Not open for further replies.

greenieM

Technical User
Feb 20, 2009
1
this is what i wrote
could someone tell me where is my mistake?
can i use here flag at all?

#include <stdio.h>

void main ()
{
int arr[10], i, j, flag;

for (i=0;i<10;i++)

scanf ("%d", &arr);

for (i=0;i<10;i++)
{
flag=1;


for (j=2;j<=(arr/2); j++)
{
if (arr%j==0)
{
flag=0;
break;

}
}
}

for (i=0;i<10;i++)
{
if (flag=1)

printf ("%d", arr);
}
}
 
Hi

Use equality check instead of setting value :
Code:
if (flag=[red]=[/red]1)
Then is a conceptual mistake : you use a single variable to hold the status of all checked numbers. Of course, if the last checked one was prime, will say all were.

Either make the flag an array
Code:
#include <stdio.h>

int main ()
{
  int arr[10], i, j, flag[red][10][/red];

  for (i=0;i<10;i++) scanf("%d", &arr[i]);

  for (i=0;i<10;i++) {
    flag[red][i][/red]=1;

    for (j=2;j<=(arr[i]/2); j++) {
      if (arr[i]%j==0) {
        flag[red][i][/red]=0;
        break;
      }
    }
  }

  for (i=0;i<10;i++) {
    if (flag[red][i][/red]) printf("%d", arr[i]);
  }
}
or print the results before ending the second outer loop.
Code:
#include <stdio.h>

int main ()
{
  int arr[10], i, j, flag;

  for (i=0;i<10;i++) scanf("%d", &arr[i]);

  for (i=0;i<10;i++) {
    flag=1;

    for (j=2;j<=(arr[i]/2); j++) {
      if (arr[i]%j==0) {
        flag=0;
        break;
      }
    }
    [red]if (flag) printf("%d", arr[i]);[/red]
  }
}

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top