Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

WHERE WE USE %u INSTEAD OF 5d IN C PROGRAMMING??

+8 votes
asked Sep 1, 2024 by SHIVANSH SARASWAT (310 points)

1 Answer

0 votes
answered Sep 3, 2024 by Peter Minarik (101,340 points)
edited Sep 4, 2024 by Peter Minarik

Please, check the format specifiers of printf.

%u is for unsigned integer

%5d is for a signed integer printed on 5-digit width aligned to the right. This means that "3" would be printed as " 3" (notice the 4 spaces to the left so the whole number would take 5 digits of space). If the number is at least 5 digits long, there will be no padding, all digits will be printed.

Consider the following example:

#include <stdio.h>

int main()
{
    unsigned int unsignedNumber = 0xFFFFFFFF;
    signed int signedPositiveNumber = 0x7FFFFFFF;
    signed int signedNegativeNumber = 0x8FFFFFFF;
    
    printf("unsigned number printed as unsigned: %u\n", unsignedNumber);
    printf("signed positive number printed as unsigned: %u\n", signedPositiveNumber);
    printf("signed negative number printed as unsigned: %u\n", signedNegativeNumber);

    printf("unsigned number printed as signed: %5d\n", unsignedNumber);
    printf("signed postive number printed as signed: %5d\n", signedPositiveNumber);
    printf("signed negative number printed as signed: %5d\n", signedNegativeNumber);

    return 0;
}

The output would be:

unsigned number printed as unsigned: 4294967295
signed positive number printed as unsigned: 2147483647
signed negative number printed as unsigned: 2415919103
unsigned number printed as signed:    -1
signed postive number printed as signed: 2147483647
signed negative number printed as signed: -1879048193

I've highlighted with yellow formatted printing that prints the wrong number because wrong formatting is used and the number is misrepresented. This happens because on the bits representing the number (we worked above with 32 bit signed or unsigned numbers) would be interpreted differently as the 1st bit from the left (31th from the right) is a sign bit for signed numbers, but for unsigned numbers, it is just part of the number.

I hope this helps you better understand formatted printing and the difference between signed and unsigned numbers.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...