Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int main(void) {//declare a method called main. This method returns an int. This method takes no parameters (void).
- int i;
- for (i = 0; i < 100; i++) {//these last 2 lines effectively combine as for (int i = 0; i < 100; i++) however some compilers reject that and prefer i to be declared seperately
- if (isPrime(i) > 0) { //isPrime returns 1 if the number is a prime number, 0 if it is not a prime number. 1 is greater than 0 so this statement will be executed if i is prime
- printf("%d\n",i);//print the number to the console
- }
- }
- return 0;//this method was declared as returning an int. Here we return that integer, in this case 0.
- }
- int isPrime(int x) {//declare a method called isPrime. This method returns an int. This method takes an int as a parameter and within the method the parameter will be known as x
- int flag = 0;//create a flag
- int i;
- for (i = 2; i <= (x / 2); i++) {//loop from 2 to half of the input number
- if ((x%i) == 0) {//if the input number can be divisible by i, the flag will be changed to 1. Importantly we never ever set the flag back to 0.
- flag = 1;
- }
- }
- if (flag == 0) {//if the flag was never changed to 1, then it is still 0 indicating that our number cannot be divisible by any value smaller than itself
- return 1;//we therefore return 1 to show that this number is a prime number
- }
- else {
- return 0;//or we return 0 if it isnt a prime number
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment