-
prime numbers?
Code:
#include<iostream>
#include<conio.h>
using std::cout;
using std::cin;
using std::endl;
// function prototype
void prime(void);
int main()
{
// display prime numbers
prime();
getch();
}
// definition of prime()
void prime(void)
{
// declare alias
int num;
for( num=1; num<=1000; num+=2 )
{
cout<< num<<endl;
}
}
With the above code i meant to view all the prime numbers from 1 - 1000. It gives the right output , thats okeys. The only thing I don't understand is the parse error it gives when i do the following changes to the above code,
instead of prime();
i write the following
cout<< prime();
or
cout<<prime(void);
in both of the above cases it gives a parse error before token')'. I dont understand this. Last but not the least when i only change prime(); to prime(void); with no cout<< at the beginning it gives me all the prime numbers from 403 - 999 but not from 1-999 y is this so? Can anyone explain this logic.
-
cout<< prime();
I don't see why you want this. the function prime() is not returning anything, so this construction has no effect.
I tested your program, and I think I can explain your 403 - 999 range... Your dos-box in windows (I asume you program in Windows) has a limited buffer, so it will not show the first values. You can change this in the properties of the output window.
I think this algorithm does not only output prime numbers
-
Thank u. One more question, do we have to use only the following format for void functions in the function calls?
function_name(); or function_name(void);
and the following for the functions which return some value,
cout<< function_name(int/whatever);
-
Couple of points.
1. Your code does not display primes - it displays integer values incremented by 2 each time.
2. << is a binary operator that takes an ostream& as the first argument and your variable as the second. Your prime function does not return anything, and even if it did, it could only return one value and not the list of primes that you require.
To achieve what you want you need a loop in main to call prime and pass its return value to cout.
-
How can we return a prime function value in main() while looping in main()?
I mean would it not b right to loop in functions definition and then return value in main() ?
-
eg
Code:
bool isPrime(int num)
{
//psuedo code;
if(num is prime)
return true;
return false;
}
int main()
{
for(int y = 1; y < 1000; ++y)
{
if(isPrime(y))
cout << y << endl;
}
return 0
}
-
thanku F102. I was printing odd numbers not prime numbers u see. So I should do as u said but with some statement that returns prime numbers instead of odd integers? am i right F102?
-