CrazyEngineers Archive
Old, but evergreen and popular discussions on CrazyEngineers, presented to you in read-only mode.
@Maelstrom • 03 Nov, 2009
There's an interesting story behind this!

I went to an interview where the interviewer (who looked pretty knowledgable) asked me, among other things, to write a program in C++ to display the first ten prime numbers... the "first ten", mind you, not "prime numbers less than 10."

Nervous as I was (first interview, please understand!!), I set about the task by inserting a couple of "for" loops here and there... Nothing came to mind, while the interviewer sat there clicking her tongue. After about five minutes, apparently she had had enough, and proceeded to scold me, "See, that's the exact mistake your predecessor made. You should use a while loop.. a for loop won't work for you in this situation.

"What is the difference between a for loop and a while loop?", she asked. This question came as a surprise to me. I tried to avoid the question, "I know the difference between a do...while loop and a while loop." But no, she wanted to know the difference between a "while" loop and a "for" loop...

...And that's where it all ended, I suppose. She scoffed at me and whispered in an undertone, "And you got 87% in aptitude!!" (*****). Anyway, back in the comfort of my home, I wrote a perfect program for the same using >>only<< "for" loops.

And that's why I'm totally bamboozled. I'd like to think that the interviewer was off her rocker, but... "innocent until proven guilty", I suppose. I've asked all my friends the same question, and they all answered the same way I did. I've looked into many books and there's no mention of a difference between the two (on the contrary, they preach ways to convert between them, to add to my frustration!)

Hoping someone would provide me with a satisfactory answer...

Yours frustratingly,
Maelstrom

[BTW: If you don't know how to write the program yourself... DO NOT press the Reply button]
@Manish Goyal • 03 Nov, 2009 Nice question This Question was asked by my Teacher at my 6 weeks training
According to my knowledge
a for loop repeats for a predefined number of times

a while loop repeats as long as a certain condition is true
......
@yadavundertaker mohit • 03 Nov, 2009 typical question dude.......
@yadavundertaker mohit • 03 Nov, 2009 ...

The difference between the two is where the test for the condition is. For example, suppose a variable is equal to 10. This is followed by a while loop which runs so long as the variable is equal to 11.
@Maelstrom • 04 Nov, 2009 Sorry guys, I still don't get the point. Maybe reframing the question would be a bit of a help...

Let's start out with the assumption that there's no difference. Just humour me for a minute... Directly derived from this assumption is the inference that Dennis Ritchie made a stupid mistake to include both the loops in the language, since we can always use them interchangeably...

[Sidenote: Maybe the while loop is there simply for convenience, in cases where we don't need a counter - like "while(!feof(fp))" - and the for loop is there in cases where we need a counter?? ...Maybe not. It seems a waste to me.. I mean, it's not a humongously large task to initialize a counter just before the start of the while loop and provide an increment at the end.... Why make a separate programming construct just to avoid this small thing?]

... Anyway, getting back to the point, what I'd like to hear is evidence on why including both the for and while loops is not just plain stupidity.

Atleast, having the for loop makes a lot more sense in Visual Basic [especially the For Each... Next variation] in which case it provides a much bigger convenience advantage over its corresponding While... End While equivalent.

yadavundertaker
...

The difference between the two is where the test for the condition is. For example, suppose a variable is equal to 10. This is followed by a while loop which runs so long as the variable is equal to 11.
I disagree [or maybe I just didn't understand]. Would you care to elaborate [maybe with an example?]

Thank You.
@Gurjeet Singh • 04 Nov, 2009 • 1 like a FOR loop is used when you know in advance that how many times you want to execute the particular block of code.
a WHILE loop is used when in advance you do not know how many times your block of code will be executed.. eg-WHILE read records until END OF FILE
@Manish Goyal • 04 Nov, 2009 For loop can only be used for uniform iterations where as while loop can be used for non uniform iterations
@tashirosgt • 06 Nov, 2009 The interviewer must have had some stereotyped answer for the program already in mind that happened to use while-loops. You don't want to work for a company that hires interviewers like that.
@Manish Goyal • 06 Nov, 2009 I thought a lot for this Question and concluded that..basically there is no difference between for loop and while loop after all both are used for carrying out iterations..
think when bjarne stroustrup created c++..what occurs in his mind...??
while looks better with some condition and for looks better with upto some point
so we can say for loop is used for uniform iterations and while loop is used for non uniform iterations...
or we can say for loop works better when we have already predefined no of iterations whereas while loop when we have given certain condition
so here both are used for carrying out iterations only
I hope you are satisfied with my answer
@vik001ind • 06 Nov, 2009 These things we don't learn, we come up with answers of such questions as per our programming skills. Some interviewers have written answers or predefined answer of such questions & they just wanna hear that only which is depressing.
There is just structural difference between the two, where you iterate, where the condition is checked. Both of them do the same thing.
I think while loop is more flexible in terms where we do iteration & initialization, whereas for loop give as a defined structure to do that..
I think Students like for loop as it is easier to implement due to its structure.
@Maelstrom • 06 Nov, 2009 GUYS!! I GOT IT!!!!

If you use "continue" in a "for" loop, it will still increment the variable. But if you use continue inside a "while" loop with counter, then it will turn into an infinite loop.

Jesus! I can't believe it was such a hidden answer like this.

Amazing! All those books, and I thought atleast one of them would have mentioned it...
@vik001ind • 06 Nov, 2009 I don't think you got it right.
That depends where you put continue statement, if you put increment variable after continue in while loop then it will loop forever, if you put increment before, it will behave normally..
continue is just used to jump directly to the condition of loop, ignoring other statements below it..

check it again!
@Manish Goyal • 06 Nov, 2009
Maelstrom
GUYS!! I GOT IT!!!!

If you use "continue" in a "for" loop, it will still increment the variable. But if you use continue inside a "while" loop with counter, then it will turn into an infinite loop.

Jesus! I can't believe it was such a hidden answer like this.

Amazing! All those books, and I thought atleast one of them would have mentioned it...
can you give any code..that will illustrate it...😕?
@safwan • 06 Nov, 2009 As far as I know is for loop will automatically increment the value and will execute the block of code .but while loop requires the increment value for going next time.😀

If you use "continue" in a "for" loop, it will still increment the variable. But if you use continue inside a "while" loop with counter, then it will turn into an infinite loop.
your saying is right.
@Saandeep Sreerambatla • 06 Nov, 2009
vik001ind
I don't think you got it right.
That depends where you put continue statement, if you put increment variable after continue in while loop then it will loop forever, if you put increment before, it will behave normally..
continue is just used to jump directly to the condition of loop, ignoring other statements below it..

check it again!

This is correct!!

Generally continue is used to skip one execution.

Any loop can turn into infinite loop !!
@Saandeep Sreerambatla • 06 Nov, 2009 To say one difference is For loop is a loop which executes for some predefined number of times.

Where as the while loop executes until the given condition is true.
@Manish Goyal • 06 Nov, 2009 hey genrally i think continue usually comes with if condition..
if i use say
while(i!=10)
{
if(i==5)
{
continue;
}
else
{
i++;
}
}
then there will be infinite loop or not
@tashirosgt • 06 Nov, 2009 The code in the for-loop is executed before a test is made to see if the stopping condition is reached.

So

n = 6;
j = 3;

for(i = 0; i < 4 && n < 6; i++)
{
n++;
j = 4;
}

Will set j equal to 4

[ No, it won't. Malestrom corrects me later in this thread. I'm thinking of the old fashioned FORTRAN DO-loops which were executed at least once.]

But if the code is:

n = 6;
j = 3;
i = 0;
while( i < 4 && n < 6)
{
i++;
j = 4;
}

Then j will remain at 3
@Maelstrom • 07 Nov, 2009
goyal420
can you give any code..that will illustrate it...?
~ Using a for loop ~

for(i = 0; i < 10; i++)
{
if(i == 5) continue;
printf("%d ", i);
}

OUTPUT: 0 1 2 3 4 6 7 8 9 [notice that '5' is missing]

~ Using a while loop ~

i = 0;
while(i < 10)
{
if(i == 5) continue;
printf("%d ", i);
i++;
}

OUTPUT: 0 1 2 3 4 ....... [the cursor will remain there, stuck in an infinite loop]
tashirosgt
j = 3;
n = 6;
for(i = 0; i < 4 && n < 6; i++)
{
n++;
j = 4;
}

Will set j equal to 4
I don't think you got this right! The condition inside the for loop is "i < 4 && (LOGICAL AND) n < 6", so irrespective of the value of i, this condition will return FALSE, because n is NOT LESS THAN 6. Hence, the for loop will not execute even once, resulting in the value of j remaining at 3.
@Manish Goyal • 07 Nov, 2009
Maelstrom
~ Using a for loop ~

for(i = 0; i < 10; i++)
{
if(i == 5) continue;
printf("%d ", i);
}
OK bASIC you can say this since in for loop all the three requirements to carry out iterations comes together
but what about this
for(i=0;i<10; )
{
if(i==5)continue;
printf("%d",i);
i++;
}
I have not try this..but what do you think what will be the output?
@Maelstrom • 08 Nov, 2009
goyal420
I have not try this..but what do you think what will be the output?
Yes, you are right, in this case it will be just like the infinite while loop.

This leads me to believe that a for loop was made specifically for cases where the programmer wanted to ensure that the counter would be incremented after each iteration of the loop no matter what happens. [Of course, for that to happen, the programmer would have to provide the increment inside the for() statement itself.]

Only now do I fully understand what all the others were trying to say.

I always thought that the for loop is the looping structure used by default. However, now I come to realize that the while loop is the most general looping statement available, whereas the for loop and the do...while loop are provided for specific purposes. Of course, the 'specific' purpose of iterating for a known number of times is so common that it is not hard to see why a for loop is encountered so many more times than a while loop.

After careful thought, I have come up with (arguably) a few "rule-of-thumb"s for programmers (it's like social rules in the world, nobody tells you this, you just know):
1.If you want the body of the loop to execute atleast once irrespective of the condition, then use a do...while loop.
2.If you want to use a counter to keep track of the number of iterations of the loop, use a for loop [it goes without saying that you put the increment inside the for() statement...]
3.For all other cases, use a while loop.
4.By default, use a while loop [Ignore this at your own peril (see the first post)]
I cannot stress this enough. USE A WHILE LOOP. For me and programmers like me, the word "loop" is synonymous with a for loop. All I can say is, think before using the for loop from now on. If you don't need a counter, use a while loop. Especially when you are using an infinite loop like for(..) [just replace the periods with semicolon, it's showing a smiley where I don't want it to] instead use while(1).

(Programmers with any ammount of credibility may wish to argue with me on, especially, the last point. However, I have paid my price - I merely wish no one else the same trauma.)
@maggi.sharma • 01 Dec, 2010 The main difference comes into picture when you use continue with them i.e. for and while.
In a while loop if continue is used before the increment of a variable is done it converts into a infinite loop.
i=1;
while(i<10)
{
/* do stuff */
if(i==6);
continue;
i++;
}
The above piece of code will turn into an infinite loop.
for(i=1;i<10;i++)
{
/* do stuff */
if(i==6);
continue;
}

In the above for loop the value of will be incremented once it attains the value 6.
Therefore it will not turn into a infinite loop.

'for' statement takes the start condition, stop condition, and the increment. 'while' statement just takes the stop condition.


Another main difference between the two: a 'for' loop is called a determinate loop, meaning that we usually use it when we know ahead of time how many iterations we want. The 'while' loop is an 'indeterminate' loop, because we usually use it in situations where we do not know the number of times the loop may iterate.

HOPE IT WILL HELP.😛
@sanjana17 • 24 Feb, 2011 The lady who took ur interview is right. look....u can use for loop to pront prime nos. LESS THAN 10!but NOT for first 10 prime nos. !!for that u have to use while loop.
@Mayank 07 • 04 Mar, 2011 One first basic rule is that you should use the for loop when the number of iterations is known. For instance:

  • The loop iterates over the elements of a collection.
  • The loop iterates over a range of values which is known in advance at execution time.
  • The object provides a way to iterate over its elements with a for statements (e.g files).


The while loop is the more general one because its loop condition is more flexible and can be more complicated than that of a for loop. The condition of a for loop is always the same and implicit in the construction. A for loop stops if there are no more elements in the collection to treat. For simple traversals or iterations over index ranges it is a good advice to use the for statement because it handles the iteration variable for you, so it is more secure than while where you have to handle the end of the iteration and the change of the iteration variable by yourself.
The while loop can take every boolean expression as condition and permits therefore more complex end conditions. It is also the better choice if the iteration variable does not change evently by the same step or if there are more than one iteration variable. Even if you can handle more than one iteration variable in a for statement, the collections from which to choose the values must have the same number of elements.Hope it's handy for u.

@PraveenKumar Purushothaman • 04 Mar, 2011 Simple Definition
For Loop is a counter loop.
While Loop is a conditional loop.
@Deepika Bansal • 05 Mar, 2011
sanjana17
The lady who took ur interview is right. look....u can use for loop to pront prime nos. LESS THAN 10!but NOT for first 10 prime nos. !!for that u have to use while loop.
Or similarly, in place of whle loop, we can use an additional for loop that'll count the number of prime number found till time.
@PraveenKumar Purushothaman • 05 Mar, 2011
Deepika Bansal
Or similarly, in place of whle loop, we can use an additional for loop that'll count the number of prime number found till time.
Why do you need to complicate the program when you just use a single for loop or while loop to do it?
@Deepika Bansal • 06 Mar, 2011 Nothing like that Praveen. It is just that earlier outer 'while' loop was counting the number of prime numbers and the inner 'for' loop was finding them. I'm comfortable with 'for' loop so I proposed using outer loop as 'for' instead of 'while'. Simple.
@PraveenKumar Purushothaman • 06 Mar, 2011
Deepika Bansal
Nothing like that Praveen. It is just that earlier outer 'while' loop was counting the number of prime numbers and the inner 'for' loop was finding them. I'm comfortable with 'for' loop so I proposed using outer loop as 'for' instead of 'while'. Simple.
Yeah, I agree, but your combination will use both the loops na?
@Deepika Bansal • 06 Mar, 2011 Yeah. It all depends on your ease of using a loop. With some little modifications, they can be used interchangeably.
@PraveenKumar Purushothaman • 06 Mar, 2011 That's what am saying... Understand, for a simple stuff, why do you need two loops... This is my question...
@Aman Goyal • 07 Jul, 2011 can anyone plz post the program to display the first 10 prime nos,i know how to check for prime and also to print prime nos in a given range but not getting this specific problem
@PraveenKumar Purushothaman • 07 Jul, 2011 Say the logic to check the prime numbers... 😀 I will try to give you a solution... 😀
@Aman Goyal • 07 Jul, 2011
cout<<"Enter the number\n";
cin>>n;
for(i=2;i<n/2;i++)
{
if(n%i==0)
{
f=1;
break;
}
}
if(f==1)
cout<<"No. is not prime\n";
else
cout<<"No. is prime\n";
@PraveenKumar Purushothaman • 07 Jul, 2011 First 10 prime numbers...

int isPrime(int n)
{
    for (i = 2; i < n / 2; i++)
    {
        if (n % i == 0)
        {
            f = 1;
            break;
        }
    }
    return f == 1;
}

// In the main function

int cnt = 0, i = 0;
while (cnt < 10)
{
    if(isPrime(i))
    {
        cout<<i;
        cnt++;
    }
    i++;
}
Hope this helps... 😀
@Aman Goyal • 07 Jul, 2011 thnx a lot,but can it be done w/o function?
@PraveenKumar Purushothaman • 07 Jul, 2011 Yes, it can be done... But if so, the whole function would be executing about a 100 times!!! Is that fine and is it not a performance issue??? 😐
@ayusha patnaik • 16 Aug, 2011 for loop is easier than while loop cz of its structure that we write the update expression in the same line..whr as in the while loop dr is a chance of the update expression getting missd and hence creation of an infinite loop...both being loops..both can be used in programs...bt asfar as i knw..while loop makes a complicated problem get an easier program than for loop cz smtyms for loops r lengthier..apart frm that while loop nt havin any initial is more flxible and can be used in any program nd yeah it is told by teachers that sm programs cant be done by all the loops..bt i blv at a hghr level things can b done by any means jst the complicacy level matters...i think since u used for loops in an interview it wd have bn long and the interviwer lackd patience and wanted u to get finishd as soon as possible...so she flew her rage at u!
@proveitboy • 23 Sep, 2011
Maelstrom
There's an interesting story behind this!

I went to an interview where the interviewer (who looked pretty knowledgable) asked me, among other things, to write a program in C++ to display the first ten prime numbers... the "first ten", mind you, not "prime numbers less than 10."

Nervous as I was (first interview, please understand!!), I set about the task by inserting a couple of "for" loops here and there... Nothing came to mind, while the interviewer sat there clicking her tongue. After about five minutes, apparently she had had enough, and proceeded to scold me, "See, that's the exact mistake your predecessor made. You should use a while loop.. a for loop won't work for you in this situation.

"What is the difference between a for loop and a while loop?", she asked. This question came as a surprise to me. I tried to avoid the question, "I know the difference between a do...while loop and a while loop." But no, she wanted to know the difference between a "while" loop and a "for" loop...

...And that's where it all ended, I suppose. She scoffed at me and whispered in an undertone, "And you got 87% in aptitude!!" (*****). Anyway, back in the comfort of my home, I wrote a perfect program for the same using >>only<< "for" loops.

And that's why I'm totally bamboozled. I'd like to think that the interviewer was off her rocker, but... "innocent until proven guilty", I suppose. I've asked all my friends the same question, and they all answered the same way I did. I've looked into many books and there's no mention of a difference between the two (on the contrary, they preach ways to convert between them, to add to my frustration!)

Hoping someone would provide me with a satisfactory answer...

Yours frustratingly,
Maelstrom

[BTW: If you don't know how to write the program yourself... DO NOT press the Reply button]
The answer I would like to give is..

In a 'for' you know what is the intial value of the iterator (say 'i')..
Therefore, a 'for' loop is used where you know the initial value of the iterator and 'while' loop when you do not know what the initial value of the iterator is...
This is just my way of answering your question...
Ready to recieve comments....
@vinci • 26 Sep, 2011 hello
First of all syntactically for loop and while loops are different.Syntax of both are different
Second ,a for loop initiates ,check for error,and increment at the same time at once....a while doesnt do that.While loop just mark upper bound and starts looping till that higher bound
@vinci • 26 Sep, 2011 hello
First of all syntactically for loop and while loops are different.Syntax of both are different<br>Second ,a for loop initiates ,check for error,and increment at the same time at once....a while doesnt do that.While loop &nbsp;just mark upper bound and starts looping till that higher bound

also an empty while loop is not valid but empty for loop is valid
@cilvan • 01 Oct, 2011 In the for loop,we can initialize counter,test the condition and also increment/decrement the counter variable whereas in while only the condition is written and the increment/decrement is given at the bottom.

In for loop assignment,increment/decrement and condition checking are done in the same line which no other loop offer.Hence we can reduce the number of lines in coding.We can initialize,increment/decrement more than one variable and test condition can also have a compound relation.

Though both loops can be used,the following strategy is usually followed:
Choose for loop,if the programmer exactly knows how much times the loop is needed to be executed.(while can also be used)
Choose while loop,if programmer is not sure how much times the loop need to be executed since the condition is tested for repetition.(for can also be used)
@Smriti Jha • 03 Oct, 2011 I think what she meant was a for loop would require a predefined number of iterations. Considering you don't know where the tenth prime number occurs, a while loop would be the preferred option. I am thinking a while loop and if statement would do the trick.
@ayusha patnaik • 06 Oct, 2011 while loop may deal with infinity on the other hand for loop never deals with infinity
@b_sothiya • 17 Oct, 2011 There is no difference between while and for loop.
you can handle any problem with any loop, there is no program wich can be
handle by for and not by while and vice-versa.
the only difference in the application, i.e. if no. of iteration are known then using for is better
otherwise while is better.
give me any problem i can do with "while" and "for" with both...?
challenge..?
@crazy_sam • 02 Jan, 2012 Hi guys ,
I am Sam and I am new to this forum and would like to be a part of this team. Please accept me as a team member so that i can share my views and get an opportunity to chat with the tech gurus here..

I understand that there is little difference in the structure of while and for loops, but for a programmer it is a negligible issue. The while statement is generally used as a simple conditional loop. However, a for statement can also be used in place of while statements like for(;condition😉. There is nothing like a "A for loop is a counter loop " or a " while loop is a conditional loop" as per my knowledge. It depends on the way u use it . Generally because of the ease in use people use ,for loop as it initializes itself in the structure so they use it as counter loops. and because there is no inbuilt initialization, in while loop people commonly use it for checking conditions only as those situations don't need a loop counter. Either way all loops are almost similar and there is nothing that is impossible with any of the loop structures. (Correct me if I am wrong!)

The simple and modified program for first 10 prime numbers using only "for loop" is posted here. Please have a look and comment.

#include<stdio.h>
#include<conio.h>
void main(){
clrscr();
int c, i, j, n, count = 0;
for(i =2;i>0;i++){
c = 0;
for(j=2;j<i;j++){
if(i%j==0){
c = 1;
}
}
if(c == 0 && count<=10){
printf("%d\t", i);
count++;
}
if(count == 10){
break;
}
}
getch();
}
@PraveenKumar Purushothaman • 02 Jan, 2012 Yeah, I agree with Sam! 😀 Right dude, it depends on how you use it and yeah, sometimes for can be made a conditional loop and while can be made a counter loop... 😀
@crazy_sam • 02 Jan, 2012
Nice question This Question was asked by my Teacher at my 6 weeks training​
According to my knowledge​
a for loop repeats for a predefined number of times​

a while loop repeats as long as a certain condition is true​
......​


This is bull shit. Both loops repeats as long as a certain condition is true, and both loops repeats for a predefined number of times.​
@PraveenKumar Purushothaman • 02 Jan, 2012
crazy_sam
Nice question This Question was asked by my Teacher at my 6 weeks training​
According to my knowledge​
a for loop repeats for a predefined number of times​

a while loop repeats as long as a certain condition is true​
......​



This is bull shit. Both loops repeats as long as a certain condition is true, and both loops repeats for a predefined number of times.​
Rightly said.. for ( ; ; ); is an infinite loop!
11.1k views

Related Posts

@Kaustubh Katdare · Oct 22, 2013

Yesterday's Apple iPad event was amazing! Apple made a lot of announcements and one of the most exciting among them was the launch of new iPad, called iPad Air. It's...
8.4k views

@Gjnitp · May 17, 2008

hello to everybody, This is G J Nithya Shankari.I just want some tips regarding presentations and projects😒😒😒. What are the basic things to be learned before starting paper presentations? what...
8.3k views

@Nithin C S · Jan 4, 2013

i am in final year engineering under Visvesvaraya Technological University ...... In 7th sem I had failed in elective subject and I heard that it will badly affect in getting...
8.1k views

@alokthakur · Sep 15, 2011

i m 7th sem student i have an idea of minor project as "medical database " for a medical shop what things should i put stress on in my project...
5.3k views

@Ravindra1988 · Nov 21, 2013

Hi friends, i am finding a topic for my final year project(mech.) in FEA & stress analysis so if u have any topic please suggest me.
4.7k views