Home > database >  Not Able To Add To Array In "C"
Not Able To Add To Array In "C"

Time:10-16

I have a program meant to calculate prime numbers of a specific number then I have to put it into an array in order to do some math to those numbers; however, I'm running into an issue where I am not able to put the prime numbers collected into an array.

Current Code

#include <stdio.h>
#include "pairs.h"
#define SIZE 1000

int main(){
    int n, m, count, i=0, res = 0;
    char prime[SIZE];

    scanf("%d %d", &n, &m);


    // while(count >= 1){
    //     // count = getchar();
    //     // prime[i  ] = count;
    for(count = n; count >= 2; count--){
        if(primed(count) == 0){
            prime[i  ] = count;
        }

    }
    printf("%s",prime);
    return 0;

}

int primed(int num){
    int primes;
    for(primes = 2; primes<=num/2; primes  ){
        if (num % primes != 0){
            continue;
        }
        else{
            return 1;
        }
    }
    return 0;
}

I am hoping to add the numbers collected in the for-loop to an array

CodePudding user response:

Well, your code works, the problem is that you are not printing the array well, try this code for printing the array which has to the same type of the elements you want to put in, so int prime[SIZE]:

int j;
for(j = 0; j < i; j  )
    printf("%d ", prime[j]);
printf("\n");

Note that the numbers will be in reverse order as you are starting the calculation from the last element, so if you input 10 you will have:

7 5 3 2 

The %s you are using in order to print the array is used to print strings (char arrays terminated with the character '\0'). If you want to print every other type of array you must use a cycle and print every element.

  • Related