C program to read an unsigned integer value using scanf

C program to read an unsigned integer value using scanf:

scanf can be used to read an unsigned integer in C. Before we move to the program, let me quickly explain what is unsigned integer and what is signed integer.

Signed and Unsigned integers:

Both signed and unsigned integers are 32 bit. Signed integers can hold both negative and positive values. Unsigned holds only positive values.

Signed integers are in the range of -2147483648 to 2147483647 and unsigned integers are in the range of 0 to 4294967295.

For both, MSB and LSB (most significant byte and least significant byte) are 0 and 3.

Unsigned integer variable in C:

Unsigned integer variables are defined as unsigned int in C. We have a format specifier defined for unsigned integers. It is %u. Using %u, we can read an unsigned integer value using scanf, and also we can write it using printf.

Example program:

The below program uses %u specifier to read and write an unsigned integer value.

#include <stdio.h>

int main()
    unsigned int unsignedInt;

    printf("Enter an unsigned integer: ");
    scanf("%u", &unsignedInt);

    printf("You have entered: %u\n", unsignedInt);

    return 0;

In this program

  • unsignedInt is an unsigned integer variable.
  • It asks the user to enter an unsigned integer. It reads the user-entered value and stores that value in unsignedInt.
  • The printf statement is printing the value on the console.

We are using %u for both scanf and printf statements.

Sample output:

If you run this program, it will print output as like below:

Enter an unsigned integer: 123
You have entered: 123

Enter an unsigned integer: 1002020
You have entered: 1002020

Enter an unsigned integer: -1
You have entered: 4294967295

Enter an unsigned integer: 4294967296
You have entered: 0

Enter an unsigned integer: 4294967297
You have entered: 1

C read unsigned int

You might also like: