GET EDUCATE

Contents
Basics of C Programming

⯈Basic C Programs

Width specifiers

  • Width specifiers says what is the maximum number of digits or characters that we want to read or print.
  • This we can use both with the scanf and printf.
  • If used with scanf, we can limit the number of characters or digits that we can read.
  • If used with printf, we can limit the number of characters or numbers that we can print.

Examples

Example 1:

int a;

If we want to read only a two-digit number from the scanf statement, we would write,

scanf(“%2d”,&a);

Even if we enter more than two digits the starting two digits (two characters, if we consider each number as a character, even ‘-‘ sign will be character) will be taken as the input and rest all the digits are discarded.

#include<stdio.h>
int main()
{
int a;
printf("Enter number:");
scanf("%2d",&a);
printf("a = %d\n",a);
return 0;
}

Output Window of above code

width specifier

We can clearly see that, if we enter number as 1234, only the starting two digits are stored in ‘a’ and the rest are discarded.

width specifier

If we enter number as -25, only the starting two characters -2 (- and 2) are stored and rest all are discarded.

Example 2:

If we want to print the number of digits after the decimal point in case of double / float number, we can use width specifiers. The decimal number will be rounded-off to nearest place.

double a = 9.2489;

If we want to print the value of ‘a’, up to two decimal places, we will write

printf(“%.2lf“,a);, It prints, 9.25

If you want to print up to three digits, we will wite,

printf(“%.3lf“,a);, It prints 9.249

#include<stdio.h>
int main()
{
double a = 9.2489;
printf("%.2lf\n",a);
printf("%.3lf\n",a);
return 0;
}

Output window of above code

width sepcifier
Scroll to Top