Search code examples
cloopsfor-loopwhile-loopfunction-definition

Transform while to for in C


I'm beginning with C

I want to change while to for

int test(int nb){
    int rv = 0;

 if(nb=1)
     return (1)
 while(rv < nb) {   // change this line 
     if(rv * rv == nb)
         return (rv)
     rv++;
 }
 return (0);
}

Can I do :

for (int rv=0; rv<nb.length; rv++)

Thanks for your help


Solution

  • You probably want this:

    int test(int nb)
    {
      if (nb == 1)    // << changed = to ==
        return (1);   // << added missing ;
    
      for (int rv = 0; rv < nb; rv++;)   // << modified
      {
        if(rv * rv == nb)
          return (rv);                     // << added missing ;
      }
    
      return (0);
    }
    

    But I'm not sure if your original codes is correct in the first place.