You are here:

C++/finding prime numbers between 1 and an input value


what does that mean?i thought if statments should be boolean(can either be true or false).
i'll just adjust it so that it contains an is also a requirement.and by doing so, is it right that i use variable "i" as the index of the array elements?

The text above is a follow-up to ...

this was based on the sieve of eratosthenes.I have tried doing it but we are required to use 2 for loops and i have no idea why is there a need to do so.what will you use as the limit/termination condition in the loop?i tried the input value N as the limit to the first loop but it did not work.sorry i am a nemwbie to C++ and thanks for helping.!
Dear farrah !

The problem is of course simple  , because finding all the prime numbers in a certain range of course expect 2 for loops!
one ( the outer for loop) selects the value under discussion  , and the inner for loop determines its actually a prime number or not!
Here i present you a simple my simple code to find all prime numbers in a given range!


void main()
  int n , isprime;
  cout<<"Enter range :";
  for( int i = 2 ; i <= n ; i++)
     isprime  = 1;
     for( int j = 2 ; j <= i ; j++)
        if( i == j)
        else if( i % j == 0)
        isprime = 0;
     cout<<i<<" ";

Thanks and regards !
Prince M. Premnath

Dear farrah !
 Actually its not a problem  , purpose of the variable "isprime " here i used to save only two values ( say 1 true 0 false )  , You may ask why i declared it as a 'int ' instead of 'boolean '  , here is the answer ! I actually programmed that solution in Turbo C++  3.0 ( Of course a old compiler ) that does not support the data type 'boolean' ,But im sure you won't get any problem if you declare it as a boolean data type ,
What you have to do is just to alter the 3 statements !

in Declaration : boolean isprime;
and the statement : isprime = 1; sholue be replaced with isprime = true;  similar change in case of isprime = 0; replacing 0 by false.

Statement: if(isprime)..

if statement expect only two conditions ie 0 and non zero ,
if(0)/* condition fails */
if(1)/* condition true */

if the variable 'isprime' holds 0 then the statement if(isprime) .. is equvalent to if(0).

Use of i as index?

  Of course i is just a variable! there is no special meaning of using i as an index  , except its the starting letter of the word "Index" - the term likely used in arrays!
You are free to use any variables replacing 'i' , ( say 'a' , 'b' ....) .

Thanks and regards !
Prince M. Premnath  


All Answers

Answers by Expert:

Ask Experts


Prince M. Premnath


Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)


More than 5 years


©2016 All rights reserved.