Question

How can i remove the goto from the following code?

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

bool is_prime(unsigned num)
{

   if(num==0 || num==1)
     return false;
   if(num==2)
     return true;
   for(unsigned i=2;i<=num-1;i++)
    if(num%i==0)
        goto step;

             return true;
      step:  return false;
}


int main(void)
{
  unsigned n;
  printf("enter the number: ");
  scanf("%u",&n);
  printf("%u\n",is_prime(n));
  return 0;
}
Was it helpful?

Solution

Replace it with return false;. return exits a function. The code even relies on that behaviour already.

bool is_prime(unsigned num)
{
    if(num == 0 || num == 1)
        return false;
    for(int i = 2; i < num - 1; i++)
        if(num % i == 0)
            return false;

    return true;
}

OTHER TIPS

if(num%i==0)    //if true return false and if fail return true.
    goto step;   

         return true;
  step:  return false; 

above block is equal to

    if(num%i==0)    //if true return false and if fail return true.
       return false;   
     return true;

um three ways

if(num%i!=0)
       return false;
return true;

Or you could use an else.

Or you could just do

return (num%i == 0);

Remove goto statement and use return false instead.

   if(num%i==0)
       // goto step;
       return false;

   return true;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top