Wednesday, 4 March 2015

Displaying Numbers in C


When displaying numbers special care must be given to the data type. Each data type has to be used with printf function in a specific format. In order to display the correct values using the printf function conversion specifiers should be used. They are used to instruct the compiler about the type of numbers appearing in the program, which in turn determines the suitable memory storage locations.



The conversion specifiers are also referred as format characters or format specifiers. Table 2.5 summarises conversion specifies supported by the printf function. Consider the example given below:

/* Program-2.6 */

#include <stdio.h>
int main()
{
printf("%d\n",128);
printf("%f\n",128.0);
return 0;
}

Executing above program will display the following:

128
128.000000

The first number is of the type integer while the second number is of the type float. Conversion specifier %d stands for decimal while %f stands for float. Incorrect use of format characters would result in wrong outputs.


/* Program-2.7 */
#include <stdio.h>
int main()
{
printf("%d\n",65*2);
printf("%d\n",65/2);
printf("%f\n",65.0/2);
printf("%c\n",65);
printf("%x\n",255);
return 0;
}

/* Program-2.8 */

#include <stdio.h>
int main()
{
int a = 3;
float b = 10.0;
float c;
c = b/a;
printf("A is %d\n",a); //decimal value
printf("B is %d\n",b); //decimal value
printf("Answer is %f\n",c); //floating point value
return 0;
}

Executing Program-2.8 will display the following:

A is 3
B is 0
Answer is 3.333333

In Program-2.8 you may wish to see the answer appearing in a more manageable form like 3.3 or 3.33 rather than 3.333333. This can be achieved by using modifiers along with the format characters in order to specify the required field width.

The format %.0f will suppress all the digits to the right of the decimal point, while the format %.2f will display first two digits after that decimal point.


Program-2.9 illustrates the use of character variables.

/* Program-2.9 */
#include <stdio.h>
int main()
{
char first_letter;
first_letter = ‘A’;
printf("Character %c\n", first_letter); //display character
printf("ASCII value %d\n", first_letter); //display ASCII value
return 0;
}

Executing Program-2.9 will display the following:

Character A
ASCII value 65



No comments:

Post a Comment