Whats difference in the working of
while(i++<100)
and
while(i++<100);
Is this correct that in 1st case, i increases until its value reach to 99 but in 2nd case,; is an error that's why nothing is going to happen?
No:
while(i++<100); is a loop with a empty command (does nothing until i is 100), (there is no compilation error).
And while(i++<100) {commands} is a same loop but does someting.
The first one is not terminated by a ; - it will execute the the follows it until i reaches the limit.
The second one is terminated by a ; - which means that there's an implicit empty block there. In other words, it's equivalent to having while(i++<100) {}. I.e. - do nothing until i reaches the limit.
There is no syntax error, just second while loop keep on incrementing till it meats the condition,
while(i++<100);
Remember ; is statement terminator. Scope of while works with either on statement terminator, or scope delimiters {}.
while (i++ < 100) - Will execute block after this statement till condition is valid i.e. i < 100.
while (i++ < 100); - Will execute it self till i < 100.
in 2nd case,";" is an error
NO. Just think of this while() as a part of do...while loop. It's perfectly valid.
However, even in normal while() loop scenario, both the statements are valid, but their behavior is different.
while (i++ < 100)
it causes the next instruction or block following while() to be executed untill the condition goes to FALSE (i goes to 99).
while(i++<100);
essentially does nothing, execpt increasing the value of i till 99.
Related
I am trying to print numbers from 1-100 incremented by 5. This is my code:
printf( "Exercise 1" );
int number = 0;
for ( number = 0; number <= 100; number + 5 ){
printf( "%d", number );
}
Do you know what is wrong with this code?
This should fix it.
for ( number = 0; number <= 100; number +=5 )
If we look at the documentation of a for loop from cplusplus.com...
for (initialization; condition; increase) statement;
Like the while-loop, this loop repeats statement while condition is
true. But, in addition, the for loop provides specific locations to
contain an initialization and an increase expression, executed before
the loop begins the first time, and after each iteration,
respectively. Therefore, it is especially useful to use counter
variables as condition.
It works in the following way:
initialization is executed. Generally, this declares a counter variable, and sets it to some initial value. This is executed
a single time, at the beginning of the loop.
condition is checked. If it is true, the loop continues; otherwise, the loop ends, and statement is skipped, going directly to
step 5.
statement is executed. As usual, it can be either a single statement or a block enclosed in curly braces { }.
increase is executed, and the loop gets back to step 2.
the loop ends: execution continues by the next statement after it.
You had most of this right.. except the last parameter...
In your specific piece of code, that last piece of your for loop, number + 5, you need to increase your loop counter and assign it back to itself (assignment)
You can accomplish this two ways:
number = number + 5
number += 5 Since you are reassigning the same variable with it's own value plus a number, C has some built in "shortcuts" (assignment operators).
Both of these statements are equivalent, but note the better readability of list item 2.
for(print("a");print("b");print("c"))
{
printf("d");
}
This question was asked in an interview , my answer was "abdcabdcabdc....." .
I want to know the proper output an explanation.Please help me out.
First of all the print in the for loop would be printf.
The output of this code will be
abdcbdcbdcbdc... infinite times.
(a will be printed only once as we initialize the counter in loop only once)
EXPLANATION
As it's a for loop so the execution will be in the following order.
Initialization
Conditon Check
Body Execution
Increment counter
Here in the condition there is a printf statement which always return the number of characters it prints. Here, printf("d") returns 1 as it is printing only 1 character.
And in C, 1 is treated as TRUE and 0 is treated as FALSE.
So, here the condition is always TRUE, so it runs for infinite times.
for (i = 0; isspace(s[i]); i++) { ... }
The above for loop is the part of the program for converting a string to an integer in K&R on page 61.
There's no condition check in that for loop. How does it work?
The loop terminates whenever the condition expression evaluates to 0. If for instance you see an expression like i < 3, you can think of it as (i < 3) != 0. So in this case, it's isspace(s[i]) != 0 meaning it terminates at the first character that is not a space.
isspace(s[i]) is the condition, since it returns a zero value for 'false' (i.e. the provided character is not a space character), and non-zero values for 'true'. In this case, only one space character exists, but in other functions such as isalpha or isalphanum, non-zero values mean different things like 1 means it is an upper-case letter (so it is an alphabetical character), or 2 means it is a lower-case letter) and so on (I may have mixed those numbers up :/).
In otherwords, the for loop is treating this function as returning a boolean value, like most other expressions, meaning it treats zero-values as false, and non-zero as true.
First of all, you're going to get out of bounds, which is gonna give you a segfault. You're just increasing i, but not checking whether it's still in the bounds or not. For example, what if s would be equal to " "? isspace(i[0]) will return a non-zero value (treated as true) and the loop will continue and will try to access the second (non-existent!) value of s. You'd better add another tiny check: for (i = 0; (i<SIZE_OF_S) && isspace(s[i]); i++) { ... }
Let's now talk about the missing condition. No, it's not missing, it's here: isspace(s[i]). This function checks whether s[i] is considered space or not. It returns a non-zero value if yes, and 0 otherwise (docs). So, it is the missing condition, just in a slightly different form (maybe you're used to different comparisons, but there exist a lot more ways.
Yes If the for loop have without condition checking , the for loop will exit whenever the condition part will be zero
For example
`
int i ;
for (i=0; 7-i; i++)
printf("hello world \n");
getch();
return 0;
}`
See the above program the 'i' minus the seven each time . and the loop will exit whenever the value of condition part will be zero (ie 7-7) .
I have been asked to comment some code and describe what it does. All was fine and I had a good handle on what was being done in the the cases of the switch but now I am unsure whether any of the cases are ever met. I don't have anyway to run or test this code currently as my main machine with all my regular software is down.
Does either of the cases of the switch get used besides the default with the conditions of this while loop? is i simply incremented to 32 and the rByte returned before it even makes the switch? What is with the ; after the conditions of the while? Shouldn't it be followed by {....} rather than ; ?
while(pCommand[--Ptr.Five] > 10 && ++i <32);
if(i==32)
{
return rByte;
}
switch(pCommand[Ptr.Five++])
{
case 2: ... (lots of code)
break;
case 4: ... (lots of cod)
break;
default: ...
break;
}
Also, how is the --Ptr.Five handled vs. the Ptr.Five++? My understanding is the first moves the pointer back and uses that value while the second uses the current value and post increments.
Am I missing something? Even moving past the ; after the conditions of the while and the lack of {} after the while, wouldnt the value of Ptr.Five be > 10 and therefore never be 2 or 4 ever?
With the ; behind the conditions of the while, would i just get bumped to32 and the following if would return the rByte?
The loop
while(pCommand[--Ptr.Five] > 10 && ++i <32);
decrements Ptr.Five and increments i until
pCommand[Ptr.Five] <= 10, or
i >= 32,
whichever happens first. Since the changes to the interesting variables are done in the loop condition, the loop body should be empty. (Not that it's particularly good style, but I've seen worse.)
If i == 32, the switch isn't reached, otherwise, if i < 32, you know that pCommand[Ptr.Five] <= 10, so both non-default cases can be reached.
The semicolon by itself is an empty statement. So doing e.g.
while (complicated_expression)
;
Is the same as:
while (complicated_expression)
{
}
It's often used when complicated_expression has side-effects, so no loop body is needed.
It's impossible to answer your question. Even if we assume that i starts at 0, who knows what value pCommand[Ptr.Five] has at the start of this code block?
Addressing some of the questions that can be answered, would it help if we rewrote the while like this:
while(pCommand[--Ptr.Five] > 10 && ++i <32)
{
/* do nothing as the body of the loop... nothing at all.
* Everything happens in the condition.
*/
}
The syntax with the semicolon is valid, if a bit confusing at first: think of what the semicolon means in C/C++ (terminates a statement) and then think of what the statement being terminates is in this case (hint: it's a "no operation").
The difference between --Ptr.Five and Ptr.Five-- is what you describe: the first variant (the pre-decrement) will decrement Ptr.Five and then return the resulting value; the second variant (the post-decrement) will decrement the Ptr.Five but return the value before the decrement.
while(pCommand[--Ptr.Five] > 10 && ++i <32);
doesn't have a body, but the loop condition itself has side-effects, so it does do something.
We could re-write this as:
while (1) {
--Ptr.Five;
if (pCommand[Ptr.Five] <= 10)
break;
++i;
if (i == 32)
break;
}
if (i == 32) {
/* we never hit the pCommand condition */
}
As for why:
it searches backwards through pCommand, from offset Ptr.Five to at most 32 entries earlier, looking for a value <= 10
if it doesn't find such a value within 32 entries, it returns rByte
if it does find such a value, it switches on it and does some work
PtrFive is incremented to indicate the next entry after this value, after the switch is dispatched
Also, how is the --Ptr.Five handled vs. the Ptr.Five++? My understanding is the first moves the pointer back and uses that value while the second uses the current value and post increments.
That's exactly correct. In:
pCommand[--Ptr.Five] > 10
Ptr.Five is decremented before the rest of the expression is evaluated, whereas in:
pCommand[Ptr.Five++]
the expression is evaluated with the old value of Ptr.Five, and then it's incremented right after. Here, that means the switch is based on the old entry in pCommand (the one that ended the while loop because it's <= 10), but Ptr.Five is incremented before code inside the cases executes.
A quick note on side-effects: as John Bode points out in a comment, my description of the pre-decrement and post-increment expressions isn't quite accurate.
This is because storing the new value into Ptr.Five doesn't have to happen right away.
However since it does have to happen (as if) by the next sequence point, which is here the &&, there's no real ambiguity.
This generally only becomes an issue if you string multiple interdependent side-effecting expressions together in a single statement. So, you know, try and avoid that.
Presuming i started at 0 -- The while loop is parsing through 31 elements (1-31) of the pCommand array, decrementing Ptr.Five before checking the value, looking for a value that is less than 10. If it does not find one, the function returns rByte -- it then checks the value of pCommand[Ptr.Five] before it increments... therefore, the value used in the switch is the same as the value used in the while conditional. The value could well be any of the switch conditions as we know it is less than 10
What is the difference between while loop and do while loop. I used to think both are completely same.Then I came across following piece of code:
do {
printf("Word length... ");
scanf("%d", &wdlen);
} while(wdlen<2);
This code works perfectly. It prints word length and tascans the input. But when I changed it to
while(wdlen<2){
printf("Word length... ");
scanf("%d", &wdlen);
}
It gives a blank screen. It do not work. So there is some functional difference between both loops. Can anybody explain it?
Is there any other difference in these two?
The do while loop executes the content of the loop once before checking the condition of the while.
Whereas a while loop will check the condition first before executing the content.
In this case you are waiting for user input with scanf(), which will never execute in the while loop as wdlen is not initialized and may just contain a garbage value which may be greater than 2.
While : your condition is at the begin of the loop block, and makes possible to never enter the loop.
Do While : your condition is at the end of the loop block, and makes obligatory to enter the loop at least one time.
do {
printf("Word length... ");
scanf("%d", &wdlen);
} while(wdlen<2);
A do-while loop guarantees the execution of the loop at least once because it checks the loop condition AFTER the loop iteration. Therefore it'll print the string and call scanf, thus updating the wdlen variable.
while(wdlen<2){
printf("Word length... ");
scanf("%d", &wdlen);
}
As for the while loop, it evaluates the loop condition BEFORE the loop body is executed. wdlen probably starts off as more than 2 in your code that's why you never reach the loop body.
do while in an exit control loop.
while is an entry control loop.
While:
entry control loop
condition is checked before loop execution
never execute loop if condition is false
there is no semicolon at the end of while statement
Do-while:
exit control loop
condition is checked at the end of loop
executes false condition at least once since condition is checked later
there is semicolon at the end of while statement.
The difference is in when the condition gets evaluated. In a do..while loop, the condition is not evaluated until the end of each loop. That means that a do..while loop will always run at least once. In a while loop, the condition is evaluated at the start.
Here I assume that wdlen is evaluating to false (i.e., it's bigger than 1) at the beginning of the while loop, so the while loop never runs. In the do..while loop, it isn't checked until the end of the first loop, so you get the result you expect.
Do while loop will be executed atleast once.......but while loop will check the condition first and then it may or may not get executed depending on the condition.
In your example wdlen may assume any garbage value which is > 2 so while loop will never get executed.
whereas do while loop will be ececuted and will tell u to enter the value and check that value in terminating condition
while(wdlen<2){
...
}
If wdlen (assuming it's a stack variable) is not initialized or assigned a value before the while loop is entered, it will contain whatever was in that space in memory before (i.e. garbage). So if the garbage value is < 2, the loop executes, otherwise it doesn't.
do{
...
}while(wdlen<2)
will execute once and then checks on condition to run loop again, and this time it might succeed if by chance wdlen which is uninitialized is found to be less than 2.
Probably wdlen starts with a value >=2, so in the second case the loop condition is initially false and the loop is never entered.
In the second case the loop body is executed before the wdlen<2 condition is checked for the first time, so the printf/scanf is executed at least once.
while test the condition before executing statements within the while loop.
do while test the condition after having executed statement within the loop.
source: let us C
while test the condition before executing statements in the while loop.
do while test the condition after having executed statement inside the loop.
In WHILE first check the condition and then execute the program
In DO-WHILE loop first execute the program at least one time then check the condition
The difference between do while (exit check) and while (entry check) is that while entering in do while it will not check but in while it will first check
The example is as such:
Program 1:
int a=10;
do{
System.out.println(a);
}
while(a<10);
//here the a is not less than 10 then also it will execute once as it will execute do while exiting it checks that a is not less than 10 so it will exit the loop
Program 2:
int b=0;
while(b<10)
{
System.out.println(b);
}
//here nothing will be printed as the value of b is not less than 10 and it will not let enter the loop and will exit
output Program 1:
10
output Program 2:
[nothing is printed]
note:
output of the program 1 and program 2 will be same if we assign a=0 and b=0 and also put a++; and b++; in the respective body of the program.
While Loop:
while(test-condition)
{
statements;
increment/decrement;
}
Lower Execution Time and Speed
Entry Conditioned Loop
No fixed number of iterations
Do While Loop:
do
{
statements;
increment/decrement;
}while(test-condition);
Higher Execution Time and Speed
Exit Conditioned Loop
Minimum one number of iteration
Find out more on this topic here: Difference Between While and Do While Loop
This is valid for C programming, Java programming and other languages as well because the concepts remain the same, only the syntax changes.
Also, another small but a differentiating factor to note is that the do while loop consists of a semicolon at the end of the while condition.
The difference between a while constructs from Step 1 versus a do while is that any expressions within the do {} will be running at least once regardless of the condition within the while() clause.
println("\nStep 2: How to use do while loop in Scala")
var numberOfDonutsBaked = 0
do {
numberOfDonutsBaked += 1
println(s"Number of donuts baked = $numberOfDonutsBaked")
} while (numberOfDonutsBaked < 5)
Here is detail explaination: Explanation
Visit: coderforevers
The most important difference between while and do-while loop is that in do-while, the block of code is executed at least once, even though the condition given is false.
To put it in a different way :
While- your condition is at the begin of the loop block, and makes possible to never enter the loop.
In While loop, the condition is first tested and then the block of code is executed if the test result is true.