0

Could anyone please explain this code to me

Here is a code, C, that I dont understand. --------------------- #include<stdio.h> #include<math.h> int main (void) { int c = 0; long long v = 88888; while (v > 0) { v = v / 10; c++; } printf("%lli", c); } ---------------------- When I run the code , the 'printf' format string returns '5' as a the equivalent of the variable 'c'. And 'c' from the onset was declared as 0. How come the 'c++' in the while loop changes to 5? How does the 'v' variable pass its result to 'c'as 4 instead of 8888.8? Thank you.

28th May 2020, 7:24 AM
Ninety5
Ninety5 - avatar
5 Answers
+ 3
The while loop goes on if v > 0. Since v is declared as 88888, it is > 0. Now, v gets divided by 10 and is 8888 (you declared it as int) and in the next line c gets incremented by 1 and is now 1. The loop goes on until v stops being greater than 0. So: Initially: v = 88888, c = 0 1st loop: v = 8888, c = 1 2nd loop: v = 888, c = 2 3rd loop: v = 88, c = 3 4th loop: v = 8, c = 4 5th loop: v = 0, c = 5 loop ends, as v is no longer > 0
28th May 2020, 7:36 AM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 3
v = v/10 is integer division since we don't have a floating point type. This basically drops the number in the ones position off of the value of v with each iteration of the loop until v = 0 and the loop stops. c++ is the same as c = c + 1 So the value is incremented with each iteration of the loop. Thus, equaling 5 when the loop stops and exits.
28th May 2020, 7:33 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
I am really greatful for this, thank you. Namit Jain Kuba SiekierzyƄski ChaoticDawg
28th May 2020, 7:40 AM
Ninety5
Ninety5 - avatar
+ 1
ChaoticDawg But v will always remain positive
28th May 2020, 7:36 AM
Namit Jain
Namit Jain - avatar
+ 1
Kuba SiekierzyƄski Ohhk👏👏👍👍👌👌
28th May 2020, 7:37 AM
Namit Jain
Namit Jain - avatar