this program calculates all the prime numbers between two input numbers num1 and num2.
first an array is created and num1,num1+1,......num2 are stored in that array
and then all elenemts of array are scanned and if they are divisible by any odd number except itself or by 2 then 0 is stored in tht array element.......
later all non zero elements are printed.......
is my algorithm wrong or program wrong?

#include<iostream>
#include<conio.h>
using namespace std;
class prime
{
      int num1,num2,length;
    public:
        void nextprime();
        prime(int nm, int mn){num1=nm; num2=mn;}
};

int main()
{
    
    int m,n; int choice;
    cout<<"how many times loop executed?"; cin>>choice;
    while(choice>0)
    { 
    cout<<"Enter two numbers: ";
    cin>>m>>n;
    prime a(m,n);
    a.nextprime();
    choice--;
    }
    getch();
}
void prime::nextprime()
{
    length=num2-num1;
      int i=0,a[length],j=0;
    //setting the array
    for(i=0;i<=length+1;i++)
    {        
     
        switch(num1+i)
        {     
           case 1: a[i]=0; break;
           case 2:
                a[i]=2;
                 break;
           default:
                if((num1+i)%2==0)
                {
                     a[i]=0;
                }
               else if((num1+i)%2!=0)
                     for(j=3;j<=num2;j+=2)
                   if((num1+i)%j==0) a[i]=0;
                else
                a[i]=num1+i;
                break;
        }
    }

        for(i=0;i<=length;i++) cout<<a[i]<<"\t"; 
}

Recommended Answers

All 3 Replies

int i=0,a[length],j=0; // *** error: ISO C++ forbids variable length array 'a'

no sir i declared length = num2-num1, that makes that valid according to iso c++,
actually the program executes but gives different output..

somewhere something is wrong, i made certain changes to the code, then suddenly output changed,

by the way i am using windows 7 64 bit OS, Dev C++ compiler.
which compiler should i use?

> i am using windows 7 64 bit OS, Dev C++ compiler.
> which compiler should i use?

Dev C++ is the IDE; you are probably using an archaic version of the Mingw port of GNU compiler (g++ 3.4 or so).

This would be a more reasonable choice of IDE and compiler:
http://prdownload.berlios.de/codeblocks/codeblocks-10.05mingw-setup.exe

This is another:
http://sourceforge.net/projects/codelite/files/Releases/codelite-3.0/codelite-3.0.0.5041-mingw4.4.1.exe/download

Or this:
http://go.microsoft.com/?linkid=9709949

If you are using the GNU compiler (g++), set the options which would make g++ become a C++ compiler: --std=c++0x --pedantic-errors

preferably along with: -Wall -Wextra -Werror

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.