Search code examples
carraysfor-loopinputprimes

Display prime number


This programming I wrote below is used to display prime number from a list (20 numbers) which keyed in by user. But it only can detect 2 and 3 as prime number. I don't know why it doesn't work. Please tell me where is the errors and help me improve it. TQ.

#include <iostream>
#include <conio.h>
using namespace std;

void main ()
{
    int i,number,list[20];
    int t,p,prime=0;


    cout<<"please key 20 numbers from 0 to 99"<<endl;


    for(i=1;i<21;i++)
    {
        cin>>number;

        if((number<0)||(number>99))
        {
            cout<<"Please key in an integer from 0 to 99"<<endl;

        }

        list[i]=number;

    }


    for(p=1;p<21;p++)
    {
        for(t=2;t<list[p];t++)
        {
            if ( list[p]%t==0)
            {
                prime=prime+1;
            }
        }
            if (prime==0&&list[p]!=1)
            {
                cout<<"Prime numbers:"<<list[p]<<endl;
            }
    }

getch();
}

Solution

  • So there are a few issues with your code, but the one that will solve your issue is simply algorithmic.

    When you start at the next iteration of p, you don't reset the value of prime and therefore it's always > 0 after we detect the second prime number and you'll never print out any again.

    Change this:

    for(p=1;p<21;p++)
    {
        for(t=2;t<list[p];t++)
        {
            if ( list[p]%t==0)
            {
                prime=prime+1;
            }
        }
            if (prime==0&&list[p]!=1)
            {
                cout<<"Prime numbers:"<<list[p]<<endl;
            }
    }
    

    To this (I've added some brackets for clairty and so we're certain the condition evaluates as we expect it to):

    for(p=0;p<20;p++)
    {
        for(t=2;t<list[p];t++)
        {
            if ( list[p]%t==0)
            {
                prime=prime+1;
            }
        }
            if ( (prime==0) && (list[p]!=1) )
            {
                cout<<"Prime numbers:"<<list[p]<<endl;
            }
            prime = 0;
    }
    

    And your issue will be solved.

    HOWEVER: I would like to reiterate this does not solve all of your code issues. Make sure you think very carefully about the input part and what you are looping over (why is p 1 to 21? Why not 0 to 20 ;) arrays are zero indexed in C meaning that your list of 20 numbers goes from list[0] to list[19], you're currently looping from list[1] to list[20] which is actually out of range and I'm surprised you didn't get a segfault!)