# Thread: Alternative way for void type help!

1. Alright have finally done it. And this is my code. See if there is anything that could be truncated or left off. I appreciate it. And thanks Cornedbee for clarifying the question.

Code:
```#include <iostream>
#include <math.h>
using namespace std;

// Function must be declared before being used.
int prime(int n);

int main(){
int i;

// Set up an infinite loop; break if user enters 0.
// Otherwise, evaluate n from prime-ness.
while(1){
cout << "Enter a number (0 to exit)";
cout << "and press ENTER: ";
cin >> i;
if(i == 0)
break;
for(i = 2; i <= 22; i++)                      // Test all numbers from 2 to 22
if(prime(i)){                                 // state for each mumber whether it is a prime
cout<< i << "is prime" << endl;       // and print out all numbers.
}else{
cout<< i << "is not a prime" << endl;
}
}
return 0;
}

// Prime number function. Test divisors from
// 2 to sqrt of n. Return false if a divisor
// found; otherwise, return true.
int prime(int n){
int i;
for(i = 2; i <= sqrt((double) n); i++)
if(n % i == 0)
return false;         // n is not prime.

return true;    // If no divisor found, n is prime.
}```

2. It appears that you do not need the controlled infinite loop, since all you are doing is printing the primes in the range [2,22]. In the prime function, you should compute the square root before the loop, not on every iteration.

It looks like you believe that variables may only be declared at the start of each block, as in C (C89, anyway). This is not the case in C++, where variables can really be declared near first use, in the middle of a block.

Also, the code could do with better indentation.

3. So would you give me some hints on how to optimize it? I am at a loss as it is a bit confusing to me when it comes to computing the square root before the loop and the iteration.

4. So make another variable, like
Code:
`double bob = sqrt(n);`
and then use bob in your for-loop test.

5. Tabstop you mean in the definition of the for-loop test? Is it possible to use boolean without any conditional statement such as while loop in the main function since we don't need user input and other screen displays, which means I could get rid of COUT and CIN and what remains are the for-loop in the main() as well as the boolean thing.

I mean it would be better to have you tweak or modify my exercise and tell me what each of them really does. What I don't understand is what laserlight said, compute the square root before the loop and not on every iteration.

6. I don't understand any of what you're asking. What I said was to do this:
Code:
```double bob = sqrt(n);
for (int i = 2; i <= bob; i++) {
//the rest of your prime testing
}```
Apart from that, yes you should get rid of the cout/cin at the beginning of your program, since as you say you are not accepting any input from the user.