Transform while to for in C

88 views Asked by At

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

4

There are 4 answers

0
Jabberwocky On BEST ANSWER

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.

0
0___________ On
for(int rv = 0;rv < nb;rv++) {

and remove rv++;

0
ameyCU On

So basic syntax of for loop is this :-

for(initialization; condition; increment){
    // your code
}

So you can rewrite your while loop as for as follows :-

for (int rv=0; rv<nb; rv++){
    //rest of code
}

The problem with your code is :-

for (int rv=0; rv<nb.length; nb++)
//                  ^^ nb is integer type so nb.length doesn't make sense

Also incrementing nb in your loop will make your loop to iterate forever.

Note :- if(nb=1) here, in C, = an is assignment operator. To compare you need to use ==.

0
Vlad from Moscow On

For starters the condition in your while loop is redundant in terms of using redundant values of rv.

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

You could rewrite your loop like

while ( rv < nb / rv ) ++rv;

and after that

return rv * rv == nb ? rv : 0;

Also it is more logically consistent when the function parameter has an unsigned integer type.

Changing the shown above while loop to a for loop can be done the following way

int test( unsigned int n )
{
    unsigned int i = 1;
    
    for ( ; i < n / i; i++ );
    
    return i * i == n ? i : 0;
}