Search code examples
cpointersnumbers

Pass by reference method


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;  
} 

Solution

  • 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;  
    }