Printing prime numbers

/* Task: create a function that determines prime number and use it to print out prime numbers from 0-50: */

EDIT
task:
Function prototype: Should return a `bool` (because it answers a yes/no question) and should take in a single int (to ask whether it's prime).
- An int greater than 2 is prime if it is not divisible by any number between 2 and itself, not including itself.
- Use this function to print out the primes less than 50. Check it against my list:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int prime(int&x)
{
	if(x%2==1) 
		return x;
}
int main()
{
	for(int i=0;i<50;i++)
		cout<<prime(i)<<" ";
	return 0;
}


it is printing out the correct prime numbers but also printing this between each number: 1629974960

Any ideas why?
Last edited on
something is a bit messed up here. When you compile you should probably be getting a warning "not all paths return a value". Listen to this because what happens when x%2==1 is false? The function returns an undefined value.

It'd be better to do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool prime(int&x)
{
    if (x%2==1)
        return true;
    else
        return false;
}

int main()
{
    for (int i = 0; i < 50; i++)
        if ( prime(i) )
            cout << i << " ";

    return 0;
}


However note that not being divisible by 2 does not mean that it is prime.
Last edited on
thanks :P i originally had it as a bool but a friend told me not to... idk what he was thinking about... Thank you!
wait i missed something in the task.. editing it now
Topic archived. No new replies allowed.