Home > database >  Pass by reference method
Pass by reference method

Time:04-10

The question is to find twin prime numbers using pass by reference. I tried to code it out but it doesn't work the way normal pointers would? (Cannot use malloc function)

#include <stdio.h>  
int twinp(int *n)  
{  
  int i=2;  
  for (i=2; i<= *n/2; i  )  
  {  
    if (*n%i == 0)  
    return 0;  
    }  
  if (i > *n/2)  
  return 1;  
}  
int main ()  
{  
  int i, c= 0; 
  printf("Twin prime numbers before 100 are: ");
  for (i = 2; i <= 100; i  )  
  {  
    if (twinp(&i) && twinp(&i 2))  
    {  
      printf ("(%d, %d) ", i, i 2);  
      c  ;
    }  
  }  
  printf (" \nTotal number of twin prime pairs: %d", c);       return 0;  
} 

CodePudding user response:

If you want to pass the reference to a function in c, you have to use pointers. Use the '&' keyword to reference the address of the value. Remember to have a memory location at moment to pass the reference, so you have to store the 'i 2' in local function and pass the reference to your function. Then use '*' to access the value.

#include <stdio.h>  

int twinp(int * n)  
{  
  int i=2;  
  for (i=2; i<= *n/2; i  )  
  {  
    if (*n%i == 0)  
    return 0;  
    }  
  if (i > *n / 2)  
  return 1;  
}  

int main ()  
{  
  int i, c= 0; 
  printf("Twin prime numbers before 100 are: ");
  for (i = 2; i <= 100; i  )  
  {  
    int i_plus_2 = i 2;
    if (twinp(&i) && twinp(&i_plus_2))  
    {  
      printf ("(%d, %d) ", i, i 2);  
      c  ;
    }  
  }  
  printf (" \nTotal number of twin prime pairs: %d\n", c);       return 0;  
}  

CodePudding user response:

You are on the right track. When you pass by reference, you pass a memory location & of a variable in the calling function (twinp(..)) and in the actual function implementation, you'd catch that memory location via * pointer. When you actually try to use the value, you have to make sure you deference with the *.

Another approach you can take would be the below:

In the function itself, we do our checks for that current number AND the 2 number.

Your loop in your main function will take care of all the iterations up to 100.

If we find the number is prime, we print in the function. If not, we return and continue to the next iteration in our main loop.

#include <stdio.h>  
void twinp(int *n)  
{   
  for(int i= 2; i < *n; i  ) {
    if((*(n) % i) == 0 || (*(n)   2) % i == 0)
      return;
  }
  
  printf("(%d, %d),", *n,*n  2);
} 

int main ()  
{  
  int i, c = 0; 
  printf("Twin prime numbers before 100 are: ");
  for (i = 3; i < 100; i  )  
  {  
      twinp(&i);
  }  
  printf (" \nTotal number of twin prime pairs: %d", c);       
  return 0;  
} 
  • Related