I have a Question About While Loop.
int space = 4;
while(space){
cout<< "*";
space --;
}
This While Loop will run 4 times and stop when value reaches to Zero 0, So my Question is we do not specify any condition like while(space > 0){...} then why it Stop.
Or this Zero 0 consider as False , and first our while loop is true and when Reaches to 0 it becomes False and Stop.
Please Tell me , i am little confused about it.
int gets converted to bool in a boolean context using space != 0.
The while loop takes a condition which is a bool. In this case, you've passed in an int instead, which will get implicitly converted to bool. That bool will be false if the int is 0, and will be true for any other value.
Related
I am currently trying to solve a problem set on codeforce where I need to check if an positive integer number has unique digits. My solutions includes a while loop and two for loops, which is quite a lot of for such an easy task.
I found a more elegant solution but I don't fully understand how the code works. I have commented it with my remarks. Could someone explain to me the second 2) and fifth 5) part?
int unique(long long int number){
/* 1) create array/list with 10 elements, the first element seen[0]
* is equal to zero */
char seen[10] = {0};
/* 2) what is the meaning of while(some random integer number)? I thought
* that the argument must be a statement that is either true or false. */
while (number) {
int digit = number % 10; // 3) get the last digit of the number
number /= 10; // 4) removes last digit of the number
/* 5) Could someone explain to me what seen[digit]++ does. And when its
* true or false? */
if (seen[digit]++)
return 0; /* not unique */
}
return 1; /* unique */
}
Of course I tried to figure out the fifth part on my own but
#include <iostream>
using namespace std;
int main(){
char seen[10] = {0};
cout << seen[7]++ << endl;
}
print outs nothing.
I'll go by parts:
2 ) The implicit conversion between a numeric type and bool returns false if the number is zero and true otherwise. You could read while(number) like while(number != 0)
5 ) This works the same way: seen[digit]++ is an expression with the same value as seen[digit] but that then increments its value (check how post-increment works). Therefore, the first time that digit is seen, seen[digit]++ has the value 0 (so the first time the condition is not met) and increments its value to 1 (so the second time the condition will be met, making the function return).
while(number) means the cycle will repeat until number is not zero. Non-zero number is equal to true
seen[digit]++ does following:
it return current value of seen[digit]. For the first time it will be zero - as no number met.
after returning current value - it increase value by one. So for the first call it will return 0 and the seen[digit] will become 1.
So for the second call it will return 1 - that mean this number already met, so it is not unique.
Q.1 what is the meaning of while(some random integer number)? I thought that the argument must be a statement that is either true or false.
=> Yes you are right while condition checks for true and false. In case of integer, 0 is treated as false and rest of the integers as true. So, whenever number become 0, while loop will break.
Q.2 Could someone explain to me what seen[digit]++ does. And when its true or false?
=> seen is declared as an array of size 10 and initialized all entries as 0. So initially every entry of array seen is zero i.e. seen[0] = 0, seen[1] = 0, seen[2] = 1... seen[9] = 0. Now when we find digit and perform seen[digit]++ it will increase value by 1 every time.
Ok so:
Every number not equal to 0 is true and equal to 0 is false. For example 1 2 and 3 are true, but 0 is false. So while (number) will iterate as long as number != 0
seen[digit]++ first returns the value, then increments itself by one after returning the value.
The condition if(number) is same as if(number != 0).
Point 2: After we have processed the last digit in the number, the value of number/10 will be 0 (as the last digit belongs to 0-9) and there we end our loop.
Point 5: The increment number will increment the value in the array and return the old value. If the value is incremented to 2, then it means that the digit is not unique and increment operation returns us 1 and the if condition is satisfied.
In C++ 0 evaluates to false and any other number evaluates to true. That "random number" is actually modified inside the loop with number /= 10. Division of integer numbers in C++ is special in the sense that it does not yield fractions so 51/10 = 5 and 5/10 = 0. At some point number equals 0 and the loop ends.
seen[digit]++ is a commonly used trick. You lookup the table seen at position digit return the current value and increment the value by 1. So if you would modify your example code like this:
#include <iostream>
using namespace std;
int main(){
int seen[10] = {0};
cout << seen[7]++ << endl;
cout << seen[7] << endl;
}
Your console output should be:
0
1
There is also ++seen[digit] which would first increment and then return the value so you would get:
1
1
Found as a user submission on leetcode for the problem Plus One.
vector<int> plusOne(vector<int>& digits) {
for (int i=digits.size(); i--; digits[i] = 0)
if (digits[i]++ < 9)
return digits;
digits[0]++;
digits.push_back(0);
return digits;
}
Normally there's something in the conditional like i >= 0; How is this for loop terminating and not accesing some -i element?
A for loop terminates when the second expression is false or when contextually converted to a bool value produces false. In C++, 0 is contextually converted to false; all other integers convert to true in a bool context. (Thanks to M.M.for the link.)
So at the beginning of each loop the expression i-- is evaluated. It's just an expression, so it will produce a result. If the result it produces is zero, the loop will end. If you haven't seen this expression before, here is how it works:
It both decrements i and returns the original value of i before it was decremented. So if i were 5, evaluating i-- will have the "result" 5, but as a side effect, i will be 4 after the evaluation.
The big picture: i is decremented by 1 each time, so assuming it starts off positive, it will get down to 0, at which time evaluating i-- will produce 0.
Sorry for a probably stupid question.
My loop does not stop at 0 and I have no idea why.
This loop will stop at i = 1
for (unsigned int i = 3 ; i > 0 ; i--)
Whereas this will stop at i = 4294967295 instead
for (unsigned int i = 3 ; i >= 0 ; i--)
Why? Do I miss anything?
In fact this i >= 0 for unsigned int is always true. So you cannot use it as loop invariant.
Use this instead:
for (unsigned int i = 4 ; i-- > 0 ;)
println(i);
it will print 3,2,1,0
A for loop iterates until the break condition evaluates to false.
In your case the loop will repeatedly check:
is i>0 (i>=0 respectively) true? If so, execute body and decrement i, else skip the loop-body.
Your first loop will at some point reach i=1. i>0 will evaluate to true. The body will be executed, i will be decremented. i will then be 0. Hence i>0 will evaluate to false and the body will not be executed and you will break out of the loop.
Your second loop will not stop (tested with g++). Why? Your i will reach 0. i>=0 will evaluate to true. The body will be executed, i will be decremented. But since you are using an unsigned int this will then assign 4294967295 to i. Since 4294967295>=0, the loop will continue, reach 0 again and again assign 4294967295 to i thus executing indefinitely.
This happens since an unsigned int represents 0 as all 0s in binary and subtracting 1 from it will yield all 1s which is interpreted as 4294967295.
How to avoid the problem? As mentioned in the comments a simple way out of it would be to use an int instead of an unsigned int.
for (; cnt--; dp += sz)
{
pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
}
Could some one explain how this for loop works? It belongs to a cpp file.
I dont understand the condition in the for loop and how it is being checked. (The function is being invoked)
The general form of for statement looks like this:
for (init-statement; condition; expression)
statement
init-statement is used to initialize or assign a starting value that is modified over the course of the loop. condition serves as the loop control. As long as condition evaluates as true, statement is executed. expression is evaluated for each iteration only if condition is true
Back to your code:
for (; cnt--; dp += sz)
init-statement here is a null statement that does nothing. condition is cnt-- which evaluates its value as cnt then decrements 1. If cnt is non-zero, condition is true, if cnt is zero, condition is false.
The condition is being interpreted as a true or false scenario.
If it's 0, then it will be false, else true.
This is equivalent to the following code -
for(; cnt-->0; dp += sz);
Because as long as a value is not equal to 0, it is considered to be true.
Remember that normal integers can be used as boolean values as well, where zero is false and everything non-zero is true.
This means that the loop will continue until cnt is zero, and then the loop will end. However that's not the whole story, since the post-decrement operator is used the value of cnt after the loop have ended will be -1.
It is similar to
while(cnt--)
{
pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
dp += sz;
}
hope this is helpful.
So syntax for for loop is
for (<initialization(optional)>; <condition(Optional)>; <increment(Optional)>)
{
...
}
Say for cnt is 2 your loop works as follows,
for(; cnt--; dp+=size)
{
...
}
Execution flow is,
1. initialization statement will be executed once. Since you dont have one nothing will be executed
2. Next condition statement will be executed. In your case cnt-- which result in cnt value is considered as condition result. So, if cnt is 2 then value 2 is considered as condition result. Hence all non-zero are considered as TRUE and zero is considered as FALSE. After evaluating to TRUE it decrements cnt by 1
3. Once the condition results in TRUE then it executes the statement part say, pair_sanitize_struct(rec_id, ctx->api_mode, dp, FALSE);
4. At the last it executes the increment statement of for loop,in you case it is dp-=size;
5. It executes from 2 till condition evaluated to ZERO ie FALSE it comes out of loop.
In c++, the value for a condition being true or false is determined by being non 0 (true) or 0 (false).
The above loop would continue iterating as long as cnt is NOT 0. It will terminate when cnt becomes 0.
UPDATE:
To clear an important point here, it is the value 0 that terminates the loop. If for some reason, cnt already starts with a negative value, the loop will never terminate
Here is the code which compiles :
int select_object = 0;
if( select_object ) //condition returns an int
{
printf("Hello");
}
if condition returns an int and not a boolean will the hello be printed ? When I tested this it printed hello.
Any idea why even for an int it executes the print statement.
THanks
In C and C++, any nonzero integer or pointer is considered true. So, since select_object is 0, it should not be printing Hello.
Boolean logic
1 = True
0 = False
1 && 0 = False 0
1 && 1 = True 1
1 || 1 = True 1
1 || 0 = True 1
So the answer is for non-zero it is considered true, for 0 it is considered false. If your value (your int) returns 0 it won't execute. If it returns a value that is not 0 it will execute.
In C or C++, a bool is just a fancy way of saying 'int with special values'. Every logical test (if, while, for, etc) can use an int or a pointer for its test instead of a bool, and anything that isn't 0 is true. NULLs and 0 are equal in this sense.