Counting how many times a number appears in a random array - arrays

C function.
Heres my working code. It shows this output when given a random array size;
Enter the size of the array: 20
What's in the array:
3 6 17 15 13 15 6 12 9 1 2 7 10 19 3 6 0 6 12 16
3 occurs 2 times.
6 occurs 4 times.
15 occurs 2 times.
6 occurs 3 times.
12 occurs 2 times.
6 occurs 2 times.
However I was wondering how you would go about implementing once a certain number has been searched for how to not repeat the loop?
#include <stdio.h>
#include <stdlib.h>
/* shows duplicate numbers in randomly generated array*/
void display_repeats(int *a, int n){
int i, j;
int count = 0;
for(i = 0; i < n; i++){
for(j = i; j < n; j++){
if(a[i] == a[j]){
count++;
}
}
if(count > 1){
printf("%3d occurs %3d times.", a[i], count);
printf("\n");
}
count = 0;
}
}
int main(void){
int array_size = 0;
int *my_array;
int i = 0;
printf("Enter the size of the array: ");
scanf("%d", &array_size);
/*initialises the array to the appropriate size */
my_array = malloc(array_size * sizeof my_array[0]);
if(NULL == my_array){
fprintf(stderr, "memory allocation failed!\n");
return EXIT_FAILURE;
}
for(i = 0; i < array_size; i++){
my_array[i] = rand() % array_size;
}
printf("What's in the array:\n");
for(i = 0; i < array_size; i++){
printf("%d ", my_array[I]);
}
printf("\n");
display_repeats(my_array, array_size);
/* release the memory associated with the array */
free(my_array);
return EXIT_SUCCESS;
}

You can sort the array and count runs of each number. Time complexity is O(n log(n)) but without a clean hashing solution, it should be reasonable and is the easiest approach.
As an aside, it's a good idea to separate printing (a side effect) from logic. Return results as a data structure and let the caller decide what to do with it. Keeping logic and printing tightly coupled harms reusability and prevents you from programmatically operating on the data after applying a function.
Here's a quick proof of concept. Plenty of room for improvement based on the above tips--and consider making a copy of the int array before sorting to keep the function idempotent if you do move this out of main.
#include <stdio.h>
#include <stdlib.h>
int cmp_ints(const void *a, const void *b) {
return *((const int *)a) - *((const int *)b);
}
int main(void) {
int nums[] = {1, 1, 5, 6, 1, 6, 2, 4, 6, 8};
int len = sizeof nums / sizeof nums[0];
qsort(nums, len, sizeof *nums, cmp_ints);
for (int i = 0; i < len;) {
int count = 1;
int num = nums[i++];
for (; i < len && nums[i] == num; i++, count++);
printf("%d => %d\n", num, count);
}
return 0;
}
Output:
1 => 3
2 => 1
4 => 1
5 => 1
6 => 3
8 => 1

The following proposed code:
cleanly compiles
properly initializes the rand() function via a call to srand()
properly checks for success/failure of the call to scanf() and properly handles any failure by informing the user via stderr and exiting the code
makes use of the Variable Length Array feature of C, so no need for dynamic memory
limits the scope of local variables when ever possible
does not repeat the examination for a value more than once
makes use of appropriate horizontal and vertical spacing for readability
outputs the values in the array in ascending order
Performs the desired functionality
and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* shows duplicate numbers in randomly generated array*/
/* note: order of parameters in function
* so can clearly indicate the array sizing
*/
void display_repeats(int arraySize, int Array[ arraySize ] )
{
int minValue = 0;
int maxValue = 0;
for( int i = 0; i < arraySize; i++ )
{
if( Array[i] > maxValue )
{
maxValue = Array[i];
}
}
for( int j = minValue; j <= maxValue; j++ )
{
int count = 0;
for( int i = 0; i < arraySize; i++)
{
if( Array[i] == j )
{
count++;
}
}
if(count > 1 )
{
printf( "%d occurs %d times.\n", j, count );
}
}
}
int main( void )
{
int array_size = 0;
printf( "Enter the size of the array: " );
if( scanf( "%d", &array_size ) != 1 )
{
fprintf( stderr, "scanf for array size failed\n" );
exit( EXIT_FAILURE );
}
/* use VLA feature of C to declare array */
int my_array[ array_size ];
srand( (unsigned)time(NULL) );
for( int i = 0; i < array_size; i++ )
{
my_array[i] = rand() % array_size;
}
printf( "What's in the array:\n" );
for( int i = 0; i < array_size; i++ )
{
printf( "%d ", my_array[i] );
}
printf( "\n" );
display_repeats( array_size, my_array );
}
A typical run of the proposed code results in:
Enter the size of the array: 100
What's in the array:
19 69 68 90 25 8 44 64 33 3 28 4 4 43 22 6 19 93 70 63 34 96 42 31 74 9 72 49 34 12 12 53 33 80 95 10 40 39 74 26 94 55 82 98 98 56 56 69 49 78 33 35 75 75 19 1 36 91 50 70 55 63 76 40 95 71 51 88 63 25 14 9 80 48 8 30 4 16 0 5 95 33 93 22 60 12 23 96 3 74 19 58 89 95 50 84 18 1 24 33
1 occurs 2 times.
3 occurs 2 times.
4 occurs 3 times.
8 occurs 2 times.
9 occurs 2 times.
12 occurs 3 times.
19 occurs 4 times.
22 occurs 2 times.
25 occurs 2 times.
33 occurs 5 times.
34 occurs 2 times.
40 occurs 2 times.
49 occurs 2 times.
50 occurs 2 times.
55 occurs 2 times.
56 occurs 2 times.
63 occurs 3 times.
69 occurs 2 times.
70 occurs 2 times.
74 occurs 3 times.
75 occurs 2 times.
80 occurs 2 times.
93 occurs 2 times.
95 occurs 4 times.
96 occurs 2 times.
98 occurs 2 times.

An implementation of the first suggestion by ggorlen, creating an array that stores whether the number at each index has already been seen.
void display_repeats(int *a, int n){
int i, j;
int count = 0;
int seen[n]; //stores 1 if the number at this index has already been seen, 0 if not
for (int i = 0; i<n; i++) seen[i] = 0; //initializes values to 0
for(i = 0; i < n; i++){
if (seen[i]) continue; //skips this iteration of the for loop if this number has already been seen
for(j = i; j < n; j++){
if(a[i] == a[j]){
count++;
seen[j] = 1; //notes that we already seen the number at this index
}
}
if(count > 1){
printf("%3d occurs %3d times.", a[i], count);
printf("\n");
}
count = 0;
}
}

Related

Sum of primes: what is the problem in result?

The code works fine but why are my answers wrong in the int result?
in output:
3
10
2 3 5 7: 17 //correct
30
2 3 5 7 11 13 17 19 23 29: 146 //incorrect
50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47: 474 //incorrect
Here is the code:
#include <stdio.h>
int main() {
int y, n, i, fact, j, result = 0;
scanf("%d", &y);
for (int x = 1; x <= y; x++) {
scanf("%d", &n);
for (i = 1; i <= n; i++) {
fact = 0;
for (j = 1; j <= n; j++) {
if (i % j == 0)
fact++;
}
if (fact == 2) {
result += i;
printf("%d ", i);
}
}
printf(": %d\n", result); //Not Getting correct answer please HELP!
}
return 0;
}
You forgot to initialize result before each calculation.
for(int x=1;x<=y;x++){
scanf("%d", &n);
result = 0; // add this for initialization
for (i = 1; i <= n; i++) {
/* ... */
}
/* ... */
}
The variable result is initialized only once
int y, n, i, fact, j, result = 0;
So it will accumulate values calculated in the loop
for(int x=1;x<=y;x++){
//...
}
Move the declaration of the variable result in the body of the loop
for(int x=1;x<=y;x++){
int result = 0;
//...
}
To avoid such an error you should declare variables in the minimum scope where they are used.
Also this loop
for (j = 1; j <= n; j++)
{
if (i % j == 0)
fact++;
}
does not make a great sense. Change the condition in the loop the following way
for (j = 1; j <= i; j++)
{
if (i % j == 0)
fact++;
}
substituting the variable n for the variable i.
Also you should use an unsigned integer type instead of the signed integer type int because prime numbers are defined for natural numbers.
The program can look for example the following way
#include <stdio.h>
int main(void)
{
unsigned int n = 0;
scanf( "%u", &n );
while ( n-- )
{
unsigned int max_value = 0;
scanf( "%u", &max_value );
unsigned long long int sum = 0;
for ( unsigned int i = 1; i <= max_value; i++ )
{
size_t count = 0;
for ( unsigned int j = 1; j <= i; j++ )
{
if ( i % j == 0 ) ++count;
}
if ( count == 2 )
{
printf( "%u ", i );
sum += i;
}
}
printf( ": %llu\n", sum );
}
return 0;
}
If to enter
3
10
20
100
then the output will be
2 3 5 7 : 17
2 3 5 7 11 13 17 19 : 77
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 : 1060

Bubble Sort Algorithm in C – Is this it?

I'm currently a CS50x student.
I've been toying around with the search and sorting algorithms. Trying to understand them in code. Now, on the topic of bubble sort: I created what I think is a bubble sort algorithm. But I couldn't quite fit in the idea of the swap count that needs to be set to non-zero value. My algorithm (below) does sort all numbers. Where would I fit in the swap idea though? If anyone could be so kind to explain I'd really appreciate it.
#import <stdio.h>
#import <cs50.h>
int main(void)
{
// Creating an unsorted array
int count = 10;
int array[count];
for (int z = 0; z < count; z++)
scanf("%i", &array[z]);
// Bubble Sort
int buffer;
for (int b = 0; b < count; b++)
{
int a = 0;
while (a < count)
{
if (array[a] > array[a+1])
{
buffer = array[a];
array[a] = array[a+1];
array[a+1] = buffer;
}
a++;
}
}
printf("Sorted: ");
for (int b = 0; b < count; b++)
printf("%i ", array[b]);
printf("\n");
}
The directive is #include, not #import. The idea of counting swaps is to break the outer loop if nothing is out of sequence (because there were no swaps needed in the inner loop). This code implements that:
#include <stdio.h>
int main(void)
{
// Creating an unsorted array
int count = 10;
int array[count];
for (int z = 0; z < count; z++)
scanf("%i", &array[z]);
putchar('\n');
printf("%8s:", "Unsorted");
for (int b = 0; b < count; b++)
printf(" %i", array[b]);
printf("\n");
// Bubble Sort
for (int b = 0; b < count; b++)
{
int a = 0;
int num_swaps = 0;
while (a < count - 1)
{
if (array[a] > array[a+1])
{
int buffer = array[a];
array[a] = array[a+1];
array[a+1] = buffer;
num_swaps++;
}
a++;
}
if (num_swaps == 0)
break;
}
printf("%8s:", "Sorted");
for (int b = 0; b < count; b++)
printf(" %i", array[b]);
printf("\n");
return 0;
}
Sample runs (source bs97.c compiled to bs97; home-brew random number generator random — the options used generate 10 numbers between 10 and 99 inclusive):
$ random -n 10 10 99 | bs97
Unsorted: 68 47 85 39 52 54 31 81 19 59
Sorted: 19 31 39 47 52 54 59 68 81 85
$ random -n 10 10 99 | bs97
Unsorted: 75 85 36 11 35 87 59 63 26 36
Sorted: 11 26 35 36 36 59 63 75 85 87
$ random -n 10 10 99 | bs97
Unsorted: 90 27 64 90 76 79 52 46 98 99
Sorted: 27 46 52 64 76 79 90 90 98 99
$ random -n 10 10 99 | bs97
Unsorted: 53 60 87 89 38 68 73 10 69 84
Sorted: 10 38 53 60 68 69 73 84 87 89
$
Note that the code avoids trailing blanks in the output.
You could also define int num_swaps = 1; outside the sorting for loop and test it in the main loop condition:
for (int b = 0; b < count - 1 && num_swaps > 0; b++)
{
num_swaps = 0;
and remove the if (num_swaps == 0) break; from the end of the loop. The inner loop could be a for loop too. And the first cycle of the outer loop moves the largest value to the end of the array, so you can shorten the inner cycle so it has less work to do. The printing code should be factored into a function, too.
#include <stdio.h>
static void dump_array(const char *tag, int size, int data[size])
{
printf("%8s (%d):", tag, size);
for (int i = 0; i < size; i++)
printf(" %i", data[i]);
printf("\n");
}
int main(void)
{
// Creating an unsorted array
int count = 10;
int array[count];
for (int z = 0; z < count; z++)
{
if (scanf("%i", &array[z]) != 1)
{
fprintf(stderr, "Failed to read number %d\n", z + 1);
return 1;
}
}
putchar('\n');
dump_array("Unsorted", count, array);
// Bubble Sort
int num_swaps = 1;
for (int b = 0; b < count - 1 && num_swaps > 0; b++)
{
num_swaps = 0;
for (int a = 0; a < count - b - 1; a++)
{
if (array[a] > array[a + 1])
{
int buffer = array[a];
array[a] = array[a + 1];
array[a + 1] = buffer;
num_swaps++;
}
}
}
dump_array("Sorted", count, array);
return 0;
}
Sample output:
$ random -n 10 10 99 | bs97
Unsorted (10): 31 82 81 40 12 17 70 44 90 12
Sorted (10): 12 12 17 31 40 44 70 81 82 90
$

Printing first 50 numbers with 5 rows and 10 cols

I want to print the first 49 numbers with 5 rows and 10 columns.
I've tried using certain width implications and trying to make it aligned but I couldn't figure out how.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j;
int count = 50;
int r = 5;
int c = 10;
for (i = 0; i <= r; i++)
{
for(int j = 1; j <=count; j++)
{
printf("%9d", i);
i++;
}
}
return (0);
}
I was able to print from 0-49 but it wasn't aligned correctly, can someone help? Thank you.
No need to use two loops, one will do fine.
Use "%2d" to reserve two digits for each number.
Don't increase for loop variable inside loop. It isn't of much use here.
Code
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i, j;
int count = 50;
int c = 10;
for (i = 0; i < count; i++)
{
printf("%2d ", i);
if (i%c == 9) printf("\n");
}
return (0);
}
You only need one loop and can use the remainder operator to detect when a new line is needed.
#include <stdio.h>
int main()
{
int count = 50;
int columns = 10;
for (int i = 0; i < count; i++)
{
printf("%9d", i);
if ((i % columns) == 9)
{
printf("\n");
}
}
return 0;
}
Output is:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
You will need to know if the column has printed 10 values,you will need a offset to remind you that, where the last element occured which was the last 10th value, so we assign the offset variable to that element value based on 10 columns per row, so we take modulus if its the completely divisible by 10, then we will move to next row
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count = 0;
int row = 5;
int column = 9;
int offset = 0;
for (int outer = 0; outer <= row; outer++)
{
for(int inner = offset; inner <= column; inner++)
{
if(count>=50){
break;
}
printf("%9d", count); // tab spaces between colums
count++;
}
printf("\n"); // new lines
}
return (0);
}
Adding space or any character before "%9d" fixes the problem.
printf(" %9d", i);

how to generate an array of diffrent integers

i have been trying to make an array of complitely diffrent random integers, 25 of them between 1-75. have been getting stuck in an infinite loop. help greatly appreciated!
ive tried to look up solutions but i either didnt understand them or just didnt find anything that suits my level.
btw i have made sure that i used srand(time(NULL));
for (i = 0; i < 25; i++)
{
while (k != 1)
{
arr[i] = rand() % 75 + 1;
for (j = 0; j < 25; j++)
{
if (arr[i] == arr[j])
{
k++;
}
}
}
k = 0;
}
whole code:
/*********************************
* Class: MAGSHIMIM C2 *
* Week: *
* Name: *
* Credits: *
**********************************/
#include <stdio.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void)
{
srand(time(NULL));
int i = 0;
int j = 0;
int k = 0;
int arr[25] = { 0 };
for (i = 0; i < 25; i++)
{
while (k != 1)
{
arr[i] = rand() % 75 + 1;
for (j = 0; j < 25; j++)
{
if (arr[i] == arr[j])
{
k++;
}
}
}
k = 0;
}
for (i = 0; i < 25; i++)
{
printf("%d", arr[i]);
}
getchar();
return 0;
}
expecetd: a nice diffrent array but i got an infinite loop.
One way to do it is to make a pool or bag of numbers in the required range and pick from them. It is not much harder than repeated checking to see if the number has already been picked, and more efficient. Your modified program is now:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define ARRLEN 25 // how many to pick
#define NUMBERS 75 // range of available numbers
#if NUMBERS < ARRLEN // precaution
#error Impossible job!
#endif
int cmp(const void *a, const void *b)
// optional, for qsort
{
return *(int *)a - *(int *)b;
}
int main(void)
{
int arr[ARRLEN]; // final array
int bag[NUMBERS]; // bag of available numbers
int avail = NUMBERS; // size of bag available
srand((unsigned)time(NULL));
// prepare the bag of available numbers
for(int i = 0; i < NUMBERS; i++) {
bag[i] = i + 1;
}
// fill the array with values from the bag
for(int i = 0; i < ARRLEN; i++) {
int index = rand() % avail; // random index into array
arr[i] = bag[index]; // take that number
avail--;
bag[index] = bag[avail]; // replace with the one from the top
}
// just to check, sort the array, can be deleted
qsort(arr, ARRLEN, sizeof arr[0], cmp);
// output the result
for (int i = 0; i < ARRLEN; i++) {
printf("%d ", arr[i]);
}
printf("\n");
getchar();
return 0;
}
I sorted the array to make it easy to see if there are duplicates. That qsort line and the cmp function can be deleted.
Program output from three runs
6 7 8 9 12 16 17 19 21 27 31 35 43 46 47 50 51 53 59 64 65 66 70 71 72
2 6 7 14 17 23 24 25 30 31 32 34 36 37 45 58 59 61 65 68 69 71 73 74 75
5 10 13 18 20 21 25 30 34 36 39 40 41 43 49 50 54 58 60 63 64 66 67 72 75
... but i got an infinite loop.
just replace
while (k != 1)
{
arr[i] = rand() % 75 + 1;
for (j = 0; j < 25; j++) {
...
}
}
k = 0;
by
do
{
k = 0;
arr[i] = rand() % 75 + 1;
for (j = 0; j < 25; j++) {
...
}
} while (k != 1);
Note it is also useless to check looking at all the array including the entries not set by a random value, so can be :
do
{
k = 0;
arr[i] = rand() % 75 + 1;
for (j = 0; j < i; j++)
{
if (arr[i] == arr[j])
{
k++;
}
}
} while (k != 0);
because now j cannot values i the test is (k != 0) rather than (k != 1)
or better because when an identical value is found there is no reason to continue
do
{
arr[i] = rand() % 75 + 1;
for (j = 0; j < i; j++)
{
if (arr[i] == arr[j])
break;
}
} while (j != i);
To see well the values also add a space between them and add a final newline:
for (i = 0; i < 25; i++)
{
printf("%d ", arr[i]);
}
putchar('\n');
AFter these changes, compilation and executions :
pi#raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall r.c
pi#raspberrypi:/tmp $ ./a.out
74 60 16 65 54 19 55 45 41 24 39 59 66 36 27 22 68 49 29 14 28 5 71 56 72
pi#raspberrypi:/tmp $ ./a.out
16 34 62 29 74 41 3 43 69 17 61 22 28 59 7 65 5 46 60 20 66 14 49 54 45
pi#raspberrypi:/tmp $
edit
The implementation is simple but it can take time to find a not yet used value in that way, and the more the range of allowed values is closer to the number of values to return the higher the needed time is. So that solution is good when there are few values to return compared to the range of allowed values.
It is the reverse concerning the interesting proposal of Weather Vane, the number of call to rand is only equals to number of values to return, but the more the range of allowed values is large the more the array bag is large up to may be overflow the memory size.
Probably for 25 values from 1 to 75 the solution of Weather Vane is better ... even my proposal seems to need just 0.001 sec on my raspberry pi so almost nothing
int *fillint(int *arr, size_t size)
{
int added = 0;
int pos = 0
while(pos != size)
{
int rv;
do
{
added = 1;
rv = rand();
for(size_t index = 0; index < pos; index++)
{
if(arr[index] == rv)
{
added = 0;
break;
}
}
}while(!added)
arr[pos++] = rv;
}
return arr;
}
Another slight variation on Weather Vane's bag approach, is rather than preparing a bag of all available numbers, simply declare an array with the max number of elements equal to the range of numbers accepted initialized to all zero (e.g. int arr[75] = {0}; in this case). There is no need to populate the array, you will simply increment the element by 1 each time that number is used in filling your array.
To ensure you use only unique number you check whether the corresponding element of the array is zero, if it is, use that number and increment the element. If it is non-zero, you know that number has been used - generate another and try again.
For example with the number of integers for the array being 25 and the maximum value of any one integer being 75, you could do;:
#define NINT 25
#define MAXI 75
...
int arr[NINT],
seen[MAXI] = {0};
...
for (int i = 0; i < NINT; i++) { /* for each needed element */
int tmp = rand() % MAXI + 1; /* generate a random in range */
while (seen[tmp-1]) /* has been seen/used yet? */
tmp = rand() % MAXI + 1; /* if so, generate another */
seen[tmp-1]++; /* incement element */
arr[i] = tmp; /* assign unique value to arr */
}
(note: the seen indexes are mapped as tmp-1 to map to valid indexes 0-74 while the numbers generated for tmp will be 1-75 using rand() % MAXI + 1. You can accommodate any range needed by this type of mapping. Using a range of numbers from 1000001 - 1000075 would still only require a 75-element seen array.)
To output the numbers used in order, you simply need to output the index corresponding to each of the non-zero elements of the seen array (+1 to map back into the 1-75 values range), e.g.
for (int i = 0; i < MAXI; i++)
if (seen[i])
printf (" %d", i + 1);
putchar ('\n');
Putting it altogether in a short example you could do:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NINT 25
#define MAXI 75
int main (void) {
int arr[NINT],
seen[MAXI] = {0};
srand (time(NULL));
for (int i = 0; i < NINT; i++) { /* for each needed element */
int tmp = rand() % MAXI + 1; /* generate a random in range */
while (seen[tmp-1]) /* has been seen/used yet? */
tmp = rand() % MAXI + 1; /* if so, generate another */
seen[tmp-1]++; /* incement element */
arr[i] = tmp; /* assign unique value to arr */
}
puts ("array:");
for (int i = 0; i < NINT; i++) {
if (i && i % 5 == 0)
putchar ('\n');
printf (" %2d", arr[i]);
}
puts ("\n\nused:");
for (int i = 0; i < MAXI; i++)
if (seen[i])
printf (" %d", i + 1);
putchar ('\n');
}
(note: obviously the size of the seen array will be limited to the available stack size, so if your range of needed numbers exceeds the memory available for seen declared with automatic storage type, you will need to make seen an array with allocated storage type).
Example Use/Output
$ ./bin/randarr25-75
array:
1 18 70 26 75
29 31 58 22 9
5 13 3 25 35
40 48 44 57 56
60 50 71 67 43
used:
1 3 5 9 13 18 22 25 26 29 31 35 40 43 44 48 50 56 57 58 60 67 70 71 75
Whether you use a bag, or an array to track the numbers seen, the results are the same. No one better than the other. Add them both to your C-toolbox.
In the inner for loop, the one for j, iterate until j < i, to check if the value generated at step i has been already generated at a earlier step.
Also, initialize the value of k to be zero every time you check for previous occurrences, this makes the code more easy to read.
If one occurrence was found, just break, it make the algorithm to run faster, even if it only make a difference for big values.
Something like this:
for (i = 0; i < 25; i++)
{
k = 1;
while (k != 0)
{
arr[i] = rand() % 75 + 1;
k = 0;
for (j = 0; j < i; j++)
{
if (arr[i] == arr[j])
{
k++;
break;
}
}
}
}

To find and assign primes to an array

Hi I have made a simple program to print primes between 1 and 100 but I cannot figure a way to assign these values to an array of size 25 as we all know there are 25 primes between 1 and 100:
#include <stdio.h>
int main() {
int i, k;
for (i = 3; i < 100; i = i + 2) {
for (k = 2; k < i; k++) {
if (i % k == 0)
break;
}
if (i == k)
printf("%d\n", i);
}
}
Just create an array at the top, write to it, and then read out of it after you've found all your primes. Note that this could definitely be done more efficiently, but given the number of calculations you're doing, that's beside the point.
Code
#include<stdio.h>
int main() {
int primes[25];
int i, k;
int j = 0;
// find primes
for(i = 2; i < 100; i++) {
for (k = 2; k < i; k++) {
if (i % k == 0) {
break;
}
}
if (i == k) {
primes[j] = i;
j++;
}
}
// print primes
for (j = 0; j < 25; j++) {
printf("%d\n", primes[j]);
}
return 0;
}
Also note that 2 is prime, so you'll want to make sure that that's included in your output.
Output
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Make an array before you begin, then create a variable that increments while each prime is found. It might look something like this:
#include <stdio.h>
int main() {
int primes[25];
primes[0] = 2;
int count = 1;
for (int i = 3; i < 100; i += 2) {
int k;
for (k = 2; k < i; k++) {
if (i % k == 0) break;
}
if(i == k) {
primes[count] = i;
count++;
}
}
}
Warning: this is a humorous answer, not to be taken seriously.
Just like we all know there are 25 primes between 1 and 100, we might as well know the magic value to avoid using an array at all:
#include <stdio.h>
int main() {
long long magic = 150964650272183;
printf("2");
for (int i = 3; magic; magic >>= 1, i += 2)
magic & 1 && printf(" %d", i);
printf("\n");
return 0;
}
Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Resources