LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   array of integer in C (https://www.linuxquestions.org/questions/programming-9/array-of-integer-in-c-4175659173/)

sibelius 08-15-2019 07:26 AM

array of integer in C
 
Hi everyone
I have some problems with an array of integer numbers.
let's suppose we have an array v[]= {2,3,0,5,0,7,0,0,0,11,0,13,0,0,0,17,0,19}

from this array I'd like to get a second array
q[]={1,1,3,1,3,1} where the number in this array are the total number of zeros between two prime numbers.

any idea would be great.
thank you very much in advance.

PS: my coding skills are a bit rusty

hazel 08-15-2019 08:28 AM

I suppose you could have a loop that ran through the big array sequentially, testing each value against zero and storing the result in a counter that is zeroed after every non-zero value in the array. Like in this pseudocode
Code:

while items in array
{
  If (array[n]==0)
  {
    counter++
  }
  else    // Possible end of zero sequence
  {
    if (counter==0)    // Previous item was not zero
    {
        continue
    }
    else
    {
        add counter value to array q
        counter=0    //reset counter
      }
  }
  n++
}

That's probably buggy but it's a start.

rtmistler 08-15-2019 08:43 AM

Quote:

Originally Posted by sibelius (Post 6025334)
Hi everyone
I have some problems with an array of integer numbers.
let's suppose we have an array v[]= {2,3,0,5,0,7,0,0,0,11,0,13,0,0,0,17,0,19}

from this array I'd like to get a second array
q[]={1,1,3,1,3,1} where the number in this array are the total number of zeros between two prime numbers.

any idea would be great.
thank you very much in advance.

PS: my coding skills are a bit rusty

My idea is that since your coding skills are rusty, to instead use your design skills and write pseudocode as a means to solve the mathematical or procedural problem here.

I call the most lengthy process, brute force.

Since your requirement is something stated, and you've demonstrated an example. Apply logic leading to an algorithm towards that example. Then create examples where there should be different outcomes as well as non-conditions which should not be detected.

Go from the first element of that primary array, one element at a time, and evaluate it.
What will you need to remember?
  • Whether or not you've already found a first prime. So that is a true/false condition, starting at false
  • The count of zero terms you have passed, therefore this starts at zero once you encounter a first prime number.
  • Once you encounter a new prime number, you save your zero count to a new array and reset the first prime flag back to false.
Some design considerations you may evaluate:
  • Whether or not a non-prime number cancels a whole run of counting zeros. I.e. 3, 0, 0, 4, 0, 0, 2 - does that example mean no zeros were encountered, or instead four zeros were encountered between two primes and there just happened to be a non-prime tucked in there, but it is not a zero?
  • The sizes of arrays you can process. If you say open a file, or accept input, thus allowing some very lengthy array of numbers as input, you may need to find a way to create a very large array, or list of numbers representing your zero count. Or if you're hard-coding the input array, then you can likely hard-code a static array of the same size or slightly smaller in size to store your output count array. It is also possible, if you choose to do so, to overwrite your input array from the starting point, with your count values, because you know that this insert point should always be trailing your reading point.

pan64 08-15-2019 08:54 AM

as usual, we would like to see your code and where did you stuck
we can definitely help you to continue, but I think it is your homework (and not mine).

dugan 08-15-2019 07:50 PM

Every number in the question you posted is prime.

Do you need to determine if each number is prime, or can you just assume they all are?

Skaperen 08-16-2019 12:57 AM

i typically prototype more complicated programs, using simpler test cases, in higher level languages such as Pike or Python (use whatever works best for you) before i code up a C version to really kick some ... cores. in some cases i have found the higher level version good enough for my needs. but if you are trying to build your experience in C, then you need to stick with that. but prototyping is still a useful methodology.

sibelius 08-16-2019 01:10 AM

thank you very much to all of you for the reply, most of the time thanks to members of this community, make my life easy.

please believe me that was not my intention to get someone to write the code for me.
often reply like "try to do this or that" or even "get out of that wardrobe and get some air" solve my mathematical problems.
i have to admit my skills in that area is not that good either.
i d like also to say that i like to share codes, maybe someone somewhere work on the same problem.
so here the code (please only if you are interested).



Code:

#include <stdio.h>
#define N 1000




int insert(int *v) {    //let's check if n is odd or even
          int i, n;
         
         
          printf("let's check if n is >= 2 and in this case\n");
          printf("check if n is odd or even\n");
          printf("let's find prime number <= to n with Eratostene sieve\n");       
          printf("be carefull if you put a number with comma or dot the code goes\n");
          printf("in loop and to stop it you need to press ctrl+c and start recompile again\n\n\n\n");
         
         
          while (n<2) {
         
          printf("the number have to be >=2, please insert here:");
          scanf("%d", &n);
                 
                      }
                 
         
         
                  if (n%2 == 0)
                  printf("\nthe number is positive and even\n");
                  else
                  printf("\nthe number is positive and odd\n");



 /*let' generate an array of zeros with index from 2 to n*/
          for(i=2; i<=n; i++)
                  v[i]=0;
 
          return n;
                  }







void eratostene(int *v, int n) {
          int i,j;
         
        for(i=2; i<=n; i++)
                if(v[i]==0)
                            for(j=2*i; j<=n; j+=i)
                                           
                                    v[j]=1;                        //let's set v[j]=1, to mark all the multiple number ; that's the sieve
                                                    }
                                                   
                                                   
                                                   
                                           
                                           
                                                   
void print(int *v, int n) {
        int i,k;
       
        k=0;
  for(i=2; i<=n; i++)
  if(v[i]==0) //if the number is prime
  k=k+1;  //count the number of prime numbers
  printf("\nthe prime numbers between 2 and %d are %d:\n\n",n,k); 
 
 
        for(i=2; i<=n; i++)
            if(v[i]==0) //if the number is prime
                    printf("%d\n",i);  //let's print the list of prime numbers
                   
                    printf ("\nquotient of the division of %d for all the prime numbers <= of %d\n",n,n);
                for(i=2; i<=n; i++)
            if(v[i]==0) //if the number is prime
                             
                    printf ("\n%d",n / i );//print the quotient of the division
                    printf ("\n");



                printf ("\nremainder of the division of %d for all the prime numbers <= of %d\n",n,n);
                for(i=2; i<=n; i++)
            if(v[i]==0) //if the number is prime
                             
                    printf ("\n%d",n % i );//print the remainder of the division
                    printf ("\n");

                            }
                         
                         
                         
                         
                         
                         
 int primo (int *v, int *q, int n)                {
 
                        int i,j,k,m;
                       
                  for(i=2; i<=n; i++)
                if(v[i]==0)
                                                           
                q[i]=i;  //i use an array q to put the prime numbers in
               
                printf ("\nthe positions in the array where zeros are present give to me an indication of the gap (in the set of natural numbers)  between two consecutive prime numbers\n");
                 
                                        for(i=2; i<=n; i++)
                                        printf ("\n components of q array %d\n",q[i]);//print the componets of q array
               
               
               
               
                    //  PART OF CODE I HAVE PROBLEM WITH
               
                // the idea of this part of the code is to get rid of the zeros and leave an array with all the prime numbers
                //and at that point the next step is to create a new array where the components are the various gaps between the prime numbers
                // actually before do this step i should write another function to check if n is prime number or not
                //i have not get that far, i know what have to be done in teory but i did not think to the code yet
               
               
               
               
               
                //compatto il vettore eliminando gli 0
                              k=0;
                for(i=2; i<=n; i++){
               
                if(q[i]==0)
               
               
                      q[i]=q[i+k]; 
                     
                        k=k+1;
               
               
                  }
               
                m=n-k;
               
               
                for(i=2; i<=m; i++)
                printf ("\n\n\n\n componenti nuovo  vettore q[i] %d\n",q[i]);               
               
                                                                // END  PART OF CODE I HAVE PROBLEM WITH
               
               
                                } 



int main() {
        int a[N],b[N],n;
       
        n=insert(a);
        eratostene(a,n);
        print(a,n);
        primo(a,b,n);
       
  return 0; }


rtmistler 08-16-2019 08:27 AM

Quote:

Originally Posted by sibelius (Post 6025644)
the idea of this part of the code is to get rid of the zeros and leave an array with all the prime numbers

As you progress through your array, maintain the position of one beyond your last known prime as long as you are seeing zeros, therefore two pointers, a parse pointer and an insert pointer. Once you encounter another prime, move it to your insert point, as well as all prime+non-zero terms. Once you're done with the array, truncate away beyond your insert point.
Quote:

Originally Posted by sibelius (Post 6025644)
and at that point the next step is to create a new array where the components are the various gaps between the prime numbers

My original logic answer described how to create a new array which contains these numbers.
Quote:

Originally Posted by sibelius (Post 6025644)
actually before do this step i should write another function to check if n is prime number or not

I really didn't check it, or even look it up, but when you said you were going to use the Eratostene sieve to determine if a number was prime, AND you have code in a function to do that, I assumed you knew what you were talking about. So, WHY do you need another function to do the same thing?
Quote:

Originally Posted by sibelius (Post 6025644)
i have not get that far, i know what have to be done in teory but i did not think to the code yet

I know your comment here is a general comment, myself as well as others have already pointed out to you that you are not yet thinking about how to handle non-prime number situations. Or at least you haven't discussed what the requirements are for this.

sibelius 08-17-2019 01:25 AM

thank you very much again.
i just finish working on a separate code to solve my problem, i'll post this new code.
this code generate an array without zeros and without repetitions of numbers (each elements appear only once), at the moment i m out of the wardrobe to get same fresh air but as soon as i can I will get inside again to try to implement this second code in my original one.
thanks again to all of you.
sorry no time to translate my writing in English inside the code, but is quite simple.

here is the code

Code:

#include <stdio.h>
#include <stdlib.h>

int main (void)  {

const int MAXN=30;

int vet[MAXN];
int compatto[MAXN];
int N;
int N_compatto;
int i,j;
int trovato;

do{

                    printf("inserire n ");
                    scanf("%d",&N);


                    if(N>MAXN||N<=0)
                    printf("errore il numero deve essere compreso tra 0 e MAXN\n");
    }                                while(N>MAXN||N<=0);


for(i=0;i<N;i++) 
vet[i]=0;

for(i=0;i<N;i++)  {

printf("elemento %d di %d\t",i,N);
scanf("%d", &vet[i]);

                  }

printf("\n");
           
   
N_compatto=0;



for(i=0;i<N;i++) {
if(vet[i]!=0) {
trovato=0;

for(j=0;j<N_compatto && trovato==0;j++)  {
if(compatto[j]==vet[i])
trovato=1;
                                          }

if(trovato==0)    {
compatto[N_compatto]=vet[i];
N_compatto=N_compatto+1;
                  }

              }

}


if(N_compatto==0)
printf("il vettore risultante non contiene nessun elemento\n");
else    {
printf("il vettore risultante contiene %d elementi \n",N_compatto);

for(i=0;i<N_compatto;i++)
printf("elemento %d %d\n",i+1,compatto[i]);
printf("\n");
        }
                 
exit(0);

}


pan64 08-17-2019 01:35 AM

is this the original formatting of your file? Would be nice to have a better one.
Code:

#include <stdio.h>
#include <stdlib.h>

int main(void) {

    const int MAXN = 30;

    int vet[MAXN];
    int compatto[MAXN];
    int N;
    int N_compatto;
    int i, j;
    int trovato;

    do {

        printf("inserire n ");
        scanf("%d", & N);

        if (N > MAXN || N <= 0)
            printf("errore il numero deve essere compreso tra 0 e MAXN\n");
    } while (N > MAXN || N <= 0);

    for (i = 0; i < N; i++)
        vet[i] = 0;

    for (i = 0; i < N; i++) {
        printf("elemento %d di %d\t", i, N);
        scanf("%d", & vet[i]);
    }

    printf("\n");

    N_compatto = 0;

    for (i = 0; i < N; i++) {
        if (vet[i] != 0) {
            trovato = 0;

            for (j = 0; j < N_compatto && trovato == 0; j++) {
                if (compatto[j] == vet[i])
                    trovato = 1;
            }

            if (trovato == 0) {
                compatto[N_compatto] = vet[i];
                N_compatto = N_compatto + 1;
            }
        }
    }

    if (N_compatto == 0)
        printf("il vettore risultante non contiene nessun elemento\n");
    else {
        printf("il vettore risultante contiene %d elementi \n", N_compatto);

        for (i = 0; i < N_compatto; i++)
            printf("elemento %d %d\n", i + 1, compatto[i]);
        printf("\n");
    }

    exit(0);

}

https://codebeautify.org/c-formatter-beautifier

rtmistler 08-17-2019 01:43 AM

Are there further questions?

sibelius 08-17-2019 05:41 AM

Thank you for the web site for better format coding, and no at the moment I don't have anything else to ask, but is a work in progress and I m sure something else will come along the way.
Thanks again.

dugan 08-19-2019 12:06 PM

There's a program called clang-format, which you can use to automatically format C code. It's fairly standard these days.

GazL 08-19-2019 02:00 PM

There's also an old-school one called 'indent'

I wasn't aware of the clang one. Might have to see if I can find a Allman style config file for it.

sibelius 08-19-2019 03:40 PM

thanks for the additional information.


All times are GMT -5. The time now is 01:33 AM.