0

Hi I wrote this code to print out factors of an integer with a for looop

how do i write it with a while loop?

for(int i = 1; i <  integer+1; i++)
{
    if(integer % i == 0)
        cout<< i<<" ";
}
6
  • You culd just stop at integer / 2 since numbers that large will obviously not divide evenly into it. How about you try it first and see if you can figure it out? Commented Mar 20, 2012 at 22:22
  • cplusplus.com/doc/tutorial/control Commented Mar 20, 2012 at 22:22
  • Which part of the task are you having trouble with? Commented Mar 20, 2012 at 22:22
  • @Ed S.: you forgot about integer Commented Mar 20, 2012 at 22:25
  • @KarolyHorvath: ...ok, that's true, but you can always just assume that N is divisible by N. My point is that running the loop on values greater than (n / 2) + 1 is a waste of time. Commented Mar 20, 2012 at 22:31

3 Answers 3

3
int i = 1;
while (i < integer+1)
{
  if(integer % i == 0)
    cout<< i<<" ";
  i++;
}

Or even better:

int i = 0;
while (++i < integer+1)
{
  if(integer % i == 0)
    cout<< i<<" ";
}
Sign up to request clarification or add additional context in comments.

Comments

3
int i = 1;
while(i < integer + 1) {
    // your current loop body goes here
    i++;
}

See equivalent forms of for loop.

Comments

0

Following code will print the same result as your for loop in printing.

 int i = 1;
    while(i < integer + 1)
    {
        if(integer % i == 0)
         {   cout<< i<<" "; }
         i++;

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.