Hello everybody,
I was asked by an interviewer the following question. but I was not able to answer. Please get back to me if you know the answer. thank you in advance.


Que: What is the exact difference between the "for" loop and "while" loop in C language ?

Any first year C programming student should be able to answer that question. If you could not then you are not yet ready to work as a professional programmer.

commented: That's for sure. +17
commented: Intelligent and 100% correct. I am new to programming and I know the difference between While and For so... +0

That was a question for a job interview? If you couldn't answer it, I'm inclined to say that you're a perfect candidate. :icon_rolleyes:

Anyway, the expected answer is probably that the for loop is counted and the while loop is not. Though that's only a superficial difference because you can simulate the behavior of either loop with the other.

You're all off the mark. The answer is "Whatever you want the difference to be." ;)

Seriously, take some courses (or better yet, get a degree). For and while loops are used in so many common languages. You are not ready for any kind of software development career.

For me the only significant difference except for superficialities (put first statement of for as first inside while and third at end of while and keep the middle one) is that for parameters are optional, while parameter is not, so for( ; ; ) is correct infinite loop but while() is not.

I too am looking for a job:">. Is this the idea? (I don't know assembly too well)

For loop:

for (int x=0;(x*2)<100;x++)  {}
   
   mov   eax,   0  
@head:

   ;;loop body

   inc  eax
   imul 2
   cmp  eax,   100
   ja   @end  
   jmp  @head     
@end:

While loop:

int x=5;
while (x)  {
   x--;
   //loop
 }

@head:
   mov   ecx,   5  ;;number of loops

   ;;loop body

   loop  @head     ;;jumps at the beginning of the loop if ecx!=0

1. To : Ancient Dragon,Adak,namillet,WaltP
If you think the question is basic,Just do not respond to the post. I do not need your crap replies. because I do not want to reply you in the same way which is not professionalism.

2. To : Others who were able to give me information.

Thank you guys for your time.

3. To : DaniWeb blog administrator
Request you to delete my account from this blog as soon as possible because I see some worst people here who are making the blog environment dirty.


Thank you

OK, you're serious.

The for loop is the more complete loop. In fact the Go language from Google, doesn't have any loop other than the for loop. Anything you can do with a while loop, you can do with a for loop.

The while loop doesn't include an inital assignment to the format, so it's standard idiom to see one or more assignments before the while loop begins:

i=0;
while(i<10) {
  printf("%d\n", i);
  ++i;
}

The typical while loop includes just a test between it's parenthesis, but here's one with an assignment first:

while((ch=getchar()) != '\n') {
  countchar++;
}

The for loop syntax in C, requires more than just a single value in the while test:

i = 0;
while(1) {
  if(i++ == 9) break; //a break is required or it's an endless loop
}
for(1) { <<== illegal syntax

for(;;) { //legal, note the two semi-colons
  if(i++== 9) break;
}

So at a deep logic level, there is no difference between them. Anything you can do in a for loop, you can also do in a while loop, and vice versa.

In common usage, when you know the number of times the loop will need to iterate around, then a for loop is more intuitive. When you don't know how many times a loop will need to iterate, then a while loop is slightly clearer, and is usually used.

1. To : Ancient Dragon,Adak,namillet,WaltP
If you think the question is basic,Just do not respond to the post. I do not need your crap replies. because I do not want to reply you in the same way which is not professionalism.

2. To : Others who were able to give me information.

Thank you guys for your time.

3. To : DaniWeb blog administrator
Request you to delete my account from this blog as soon as possible because I see some worst people here who are making the blog environment dirty.


Thank you

In DaniWeb, posters are discouraged from completely giving away answers for the benefit of the student programmer. They are supposed to teach you the answer and let you carve out your own path to success.

Your post incorrectly emphasised the need for an answer alone. It implies that you want to take the quick answer and use it next time in an interview so you can prove how smart you are at C.

You should have instead told us what you already know and why you are confused by the two loops. It is hard to teach someone when we don't know what they are thinking first.

We are not here to give out answers, especially for someone who appears to be cheating.

Anything you can do with a while loop, you can do with a for loop.

Anything you can do with a for loop, you can do with a while loop.
To the OP: If you get ANY programming book about C or C++, you WILL find both kinds of loops in the first or second chapter. It is THE most basic part of programming. STOP BEING SO LAZY!

commented: exactly :) +17

Anything you can do with a for loop, you can do with a while loop.

The way I see it, this topic concerns the functionality of the loop syntax itself. In C you can do anything with anything (literally), but the loop operators themselves have a defined function and inherent limitations.

With the for loop you can initialise variables, check for a series of conditions, and do work that affects the conditions. All this without adding any extra code (which would defeat the purpose of displaying the power of the loop operator.)

for (i=0;check(i);do_work(i));

The while loop simply cant do the same number of things without adding code outside the while loop.

i=0; while (check(i)) do_work(i);
#include<stdio.h>
int main()
{
    int i=1;
    while()
    {
        printf("%d\n", i++);
        if(i>10)
           break;
    }
    return 0;
}

will report an error because there isnocondition in while brackets while

#include<stdio.h>
int main()
{
    int i=1;
    for(;;)
    {
        printf("%d\n", i++);
        if(i>10)
           break;
    }
    return 0;
}

will give you the answer..THIS IS ONE OF THE DIFFERENCE. :)

    #include<stdio.h>
    int main()
    {
        int i=1;
        while()
        {
            printf("%d\n", i++);
            if(i>10)
               break;
        }
        return 0;
    }

will report an error because there isnocondition in while brackets while

#include<stdio.h>
int main()
{
    int i=1;
    for(;;)
    {
        printf("%d\n", i++);
        if(i>10)
           break;
    }
    return 0;
}

will give you the answer..THIS IS ONE OF THE DIFFERENCE.
What about while(true), or while(1). Doesn't seems that hard to me :D

@sergent
Whenever we mention condition in the bracket,they are evaluated to either true or false.In the above program,nothing is mentioned in the braces and thats why an error will be generated.Mr you have mentioned the condition in while loop.:D

commented: alright :) +6

wow

"for" is a complete loop control statement. for(assignment component; test component; indexing component)
i.e. for(int i = 0; i < 10; ++i)

"while" is a limited "for" while(test component) i.e. while (i < 10)

You could code while (i++ <10) but that would be rather convoluted.

The main difference between while and for loop is "for" can execute without condition but when we execute while function the condition is mandotary........


Ex:

void main()
{
int i;
for(;;) //Means an infinate loop
{
if(i<10)
break;
i++;
}
printf(" %d ",i);
}

-----No error executes succesfully----

Ex:

void main()
{
int i;
while()
{
if(i<10)
break;
i++;
}
printf(" %d ",i);
}

-----Gives an error message-----

commented: void main(); no formatting; bad spelling; FAIL -4

Interesting. There have been more answers to this question since the OP announced that he was deleting his account than before he did. Given that the OP is almost certainly not reading this, it seems rather quixotic to be answering this now.

for loop: for loop is most popular lopping construct.It is very different from while and do-while loop.the advantage of for loop is that it contains all the steps in single step.The initialize phase,condition & increment & decrement phase are contain in single step.

 SYNTAX:-for(initialize phase;condition;increment & decrement phase)
         {
          loop body
         }

while loop: The while loop is a pretested loop,in which the condition is firstly checked,if condition is true,then loop body executed.the execution of loop body is repeated till the condition hold TRUE and when the condition FALSE,the control become after the end of loop body.

  SYNTAX:-while(test condition)\\condition phase 
          {
           loop body\\increment & decrement phase
          }

do while loop: do while is a post tested loop,in which the loop body is first & then is condition is tested.If statement is TRUE then the loop is executed,when the condition is FALSE then loop is terminated.This loop is terminated by semicolon(;).

SYNTAX:-do 
        {
         loop body
        }while(condition);

OK OK Enough already!! I think we've got it!!!!

try this ....
we can do anything with "while" ... which we do with "For"...
for(assignment;testing;indexing)...
try this ....
while((i++=getchar()) !='\n')..... okay

try this ....
we can do anything with "while" ... which we do with "For"...
for(assignment;testing;indexing)...
try this ....
while((i++=getchar()) !='\n')..... okay

This thread is a year old. I don't think anything more needs to be said about it.

Generally the for loop is for a specific number of iterations and the while is as long as a condition is true.

commented: Bumping an ancient thread. -1

AS all others aid for loop can be made while.

//syntax for
for(initialisation;condition;increment/decrement)
{

}

//syntax while
//initialisation
while(condition)
{
 inc/decrement;
 }

hope you understand
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.