C Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - Point Out Correct Statements (Q.No. 7)
7.
Which of the following sentences are correct about a for loop in a C program?
1: for loop works faster than a while loop.
2: All things that can be done using a for loop can also be done using a while loop.
3: for(;;); implements an infinite loop.
4: for loop can be used if we want statements in a loop get executed at least once.
1
1, 2
2, 3
2, 3, 4
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
48 comments Page 1 of 5.

Basanta said:   2 decades ago
To execute a group of statement repeatedly we use Loops(may be any kinds of loop).C provides three types of Loop(for, while, do..while) for use in difference places according to situation, that means all things that can be done using a for loop can also be done using a while loop. If you failed give the Question in my mail (basanta.mca[at]gmail.com) I will solve it.

Naive_coder said:   2 decades ago
For loop is ultimately broken down to same machine code as a while loop doing same function. So their speed might be same.

Deepa said:   1 decade ago
Why statement 4 is true ?

Sundar said:   1 decade ago
@Deepa

The following is the valid for loop.

int i=0;

for(;;)
{
printf("%d ", i++);

if(i == 10) break; // condition checking is done here.
}

Thiyagarajan said:   1 decade ago
"for loop can be used if we want statements in a loop get executed at least once. ".

How? Can you tell that the above statement is write please explain.

Sundar said:   1 decade ago
@Thiyagarajan

Yes. The 'for-loop' can be used if we want statements in a loop get executed at least once.


/* The following is the code that you have requested. */

/* ----- Usually we write code with do-while loop ----- */

int num = 0;

do
{
printf("Enter a number : ");
scanf("%d", &num);

}while(num != 0);


/* ----- Same logic with for loop ----- */

int num = 0;

for(;;)
{
printf("Enter a number : ");
scanf("%d", &num);

if(num == 0) break;
}

I hope this will help you. Have a nice day!

Srinivas16 said:   1 decade ago
for loop is not end with semicolon (;)

for(i=0;i<n;i++)
{

}

Then why statement 3 is correct ?

Sarita said:   1 decade ago
@Srinivas

See its not compulsary that for loop should have body for execution...so we can write for(i=0;i<n;i++); i.e for without body... but as here our for is 'for(;;)' it go infinite
so statement three is correct..

I hope you understood what i mean to say...

Ranganath M said:   1 decade ago
Here I can say that 4th statement is wrong, because it is not sure that a for loop can atleast be executed one time.

Have a look at the following :

int main()
{
int i;
for(i=0;i>5;i++) //at first time only condition fails
printf("hi");
}

Ranganath M said:   1 decade ago
For 4th statement do_while loop only correct.


Post your comments here:

Your comments will be displayed after verification.