Skip to content
Related Articles

Related Articles

unsigned specifier (%u) in C with Examples

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 10 Dec, 2021
View Discussion
Improve Article
Save Article

Pre-requisite: Format specifiers in C

The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, %u, etc.
This article focuses on discussing the format specifier %u. 

Introduction

This unsigned Integer format specifier. This is implemented for fetching values from the address of a variable having an unsigned decimal integer stored in memory. An unsigned Integer means the variable can hold only a positive value. This format specifier is used within the printf() function for printing the unsigned integer variables.

Syntax:

printf(“%u”, variable_name);

or

printf(“%u”, value);

Below is the C program to implement the format specifier %u:

C




// C program to implement
// the format specifier
#include <stdio.h>
  
// Driver code
int main()
{
    // Print value 20 using %u
    printf("%u\n", 20);
    return 0;
}

Output:

20

Explanation:

The positive integer value can be easily printed using “%u” format specifier.

Case 1: Print char value using %u

Below is the C program to demonstrate the concept:

C




// C program to demonstrate
// the concept
#include <stdio.h>
  
// Driver code
int main()
{
    // ASCII value of a character
    // is = 97
    char c = 'a';
  
    // Printing the variable c value
    printf("%u", c);
    return 0;
}

Output:

97

Explanation:

In the above program, variable c is assigned the character ‘a’. In the printf statement when %u is used to print the value of the char c, then the ASCII value of ‘a’ is printed.

Case 2: Print float value using %u

C




// C program to demonstrate
// the concept
#include <stdio.h>
  
// Driver code
int main()
{
    float f = 2.35;
  
    // Printing the variable f value
    printf("%u", f);
    return 0;
}

Output:

prog.c: In function ‘main’:
prog.c:11:10: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘double’ [-Wformat=]
printf(“%u”, f);
         ^

Case 3: Print negative integer value using %u

C




// C program to demonstrate
// the above concept
#include <stdio.h>
  
// Driver code
int main()
{
    // The -20 value is converted
    // into it's positive equivalent
    // by %u
    printf("%u", -20);
}

Output:

4294967276


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!