While i am running the program below it outputs like 109876543210-1-2-3-4-5-6-78-9-10-11-12-and s0 on. Why so? What is the concept of unsigned integer?
main ()
{
unsigned int i;
for (i = 10; i >= 0; i--)
printf ("%d", i);
}
C and C++ are unusual amongst languages nowadays in making a distinction between signed and unsigned integers. An int is signed by default, meaning it can represent both positive and negative values. An unsigned is an integer that can never be negative.
In the case of an unsigned integer, only positive numbers can be stored. In this data type, all of the bits in the integer are used to store a positive value, rather than having some reserved for sign information.
In C, unsigned is also one data type in which is a variable type of int this data type can hold zero and positive numbers. There is also a signed int data type in which it is a variable type of int data type that can hold negative, zero, and positive numbers.
An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation. The most significant byte is 0 and the least significant is 3.
Unsigned integers are always non-negative, that is greater than or equal to 0. When you subtract 1 from 0 in an unsigned integer type you end up with MAX_INT.
Therefore, your for loop will never terminate.
However, you need to use "%u" not "%d" in your printf if you want it to print the unsigned value rather than the signed value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With