Ad

Chapter - 9: Arrays

Implement the following procedure to generate prime numbers from 1 to 100 into a program. This procedure is called sieve of Eratosthenes.


Ad
D
Sections
3
Exercises

Step 1 Fill an array num[100] with numbers from 1 to 100
Step 2 Starting with the second entry in the array, set all its multiples to zero.
Step 3 Proceed to the next non-zero element and set all its multiples to zero.
Step 4 Repeat step 3 till you have set up the multiples of all the non-zero elements to zero
Step 5 At the conclusion of step 4, all the non-zero entries left in the array would be prime numbers, so print out these numbers.


#include<stdio.h>
#include<conio.h>

int main()
{
	int a[100], i, j, curr;

	for (i = 0; i < 100; i++)
		a[i] = i + 1;

	for (i = 1; i < 100; i++)
	{
		if (a[i] == 0)
			continue;
		curr = a[i];
		for (j = i + 1; j < 100; j++)
		{
			if (a[j]%curr == 0)
				a[j] = 0;
		}
	}

	printf("\n");
	for (i = 0; i < 100; i++)
	{
		if (a[i] == 0)
			continue;
		printf("%d\t", a[i]);
	}
	printf("\n");
	_getch();
	return 0;
}
Ad

© 2024 Garbage Valuegarbage value logo