Home > Mobile >  Passing an array to function a looping through it in C
Passing an array to function a looping through it in C

Time:04-01

I know I'm asking pretty basic question here, but could anyone give me a hint how to properly loop through an array which is initialized in another function ? I tried googling, found tons of videos but I didn't manage to get it right just yet. Would anyone please help me find out, what I'm missing in my code ? I'm a struggling beginner. Thanks in advance for your time.

My code (not functioning):

#include <stdio.h>

#define ARR_RANGE 1000000
#define GREATEST_NUMBER 1000000

void sieve(int eratosthenes[]);

int main() 
{
    int eratosthenes[ARR_RANGE];

    int n = 999;
    int c;
    for(i = 2; i <= arrLen;   i)
    {
        if(eratosthenes[i]!= -1)
        {
            int c = 0;
            while(n % i == 0)
            {
                n /= i;
                  c;
            }

            if(c >= 2)
            {
                printf("%d^%d x ", i, c);
            }
            else if(c == 1)
            {
                printf("%d x ", i);
            }
        }
        else
        continue;
    }
    return 0;
}

void sieve(int eratosthenes[])
{
    for(int i = 1; i < GREATEST_NUMBER;   i)
    {
        eratosthenes[i] = i;
    }
    
    for(int i = 2; i*i < GREATEST_NUMBER;   i)
    {
        if(eratosthenes[i] != -1)
        {
            for(int j = 2*i; j < GREATEST_NUMBER ; j  = i)
                eratosthenes[j] = -1;
        }
    }
    
    int arrLen = sizeof eratosthenes / sizeof eratosthenes[0];
}

CodePudding user response:

In the main is not visible the call of function sieve,so the array is not passed into function, to do this you have to write in the main sieve(eratosthenes); (Passage by reference)

  • Related