Pages

Saturday, July 30, 2016

Precision specifier

The printf precision specifiers set the maximum number of characters (or minimum number of integer digits) to print. A printf precision specification always begins with a period (.) to separate it from any preceding width specifier. Like [width], precision is specified in one of two ways:
  • directly, through a decimal digit string
  • indirectly, through an asterisk (*)

If you use an "*" for the precision specifier, the next argument in the call (treated as an int) specifies the precision. If you use "*" for the width or the precision, or for both, the width argument must immediately follow the specifiers, followed by the precision argument, then the argument for the data to be converted.

.precDescription
(none) Precision set to default:
  • 1 for d, i, o, u, x, X types
  • 6 for e, E, f types
  • All significant digits for g, G types
  • Print to first null character for s types
  • No effect on c types
.0 For d, i, o, u, x types, precision set to default;
for e, E, f types, no decimal point is printed.
.n n characters or n decimal places are printed. If the output value has more than n characters, the output might be truncated or rounded. (Whether this happens depends on the type character.)
* The argument list supplies the precision specifier, which must precede the actual argument being formatted.

No numeric characters will be output for a field (i.e., the field will be blank) if the following conditions are all met:
  • you specify an explicit precision of 0
  • the format specifier for the field is one of the integer formats (d, i, o, u, or x)
  • the value to be printed is 0

How [.prec] affects conversion

Type CharEffect of [.prec] (.n) on Conversion
d i o u x X Specifies that at least n digits are printed.
  • If input argument has less than n digits, output value is left-padded with zeros.
  • If input argument has more than n digits, the output value is not truncated.
e E fSpecifies that n characters are printed after the decimal point, and the last digit printed is rounded.
g GSpecifies that at most n significant digits are printed.
cHas no effect on the output.
sSpecifies that no more than n characters are printed.

Examples
CodeOutput
printf("%.0d",0);
printf("%.0d",1);1
printf("%.0d",123);123
printf("%.0f",12.3456);12
printf("%.5d",12);00012
printf("%.1f",12.3456);12.3
printf("%.3f",12.3456);12.346
printf("%.3s","Education");Edu

Width Specifier

The printf width specifier sets the minimum width for an output value. Width is specified in one of two ways:
  • directly, through a decimal digit string
  • indirectly, through an asterisk (*)
If you use an "*" for the width specifier, the next argument in the call (which must be an int) specifies the minimum output field width.

Nonexistent or small field widths do NOT cause truncation of a field. If the result of a conversion is wider than the field width, the field is expanded to contain the conversion result.

WidthDescription
n At least n characters are printed. If the output less than n characters, the output is padded with blanks (right-padded if "-" flag is given, left-padded otherwise).
0n At least n characters are printed. If the output value has less than n characters, it is filled on the left with zeros.
*The argument list supplies the width specifier, which must precede the actual argument being formatted.

Examples
CodeOutput
printf("%5d",10);   10
printf("%05",10);00010
printf("%8s","Hello");   Hello
printf("%08s","Hello");   Hello (doesn't pad 0 for string)
printf("%*s",0,"Hello");Hello
printf("%*s",8,"Hello");   Hello (width given by argument)

Size Modifier

These modifiers determine how printf functions interpret the next input argument, arg[f].

ModifierType of argarg is interpreted as ...
F Pointer (p, s and n) A far pointer
N A near pointer (NOTE: N can't be used with any conversion in huge model.)
h d i o u x X A short int
l d i o u x X A long int
e E f g G A double
L e E f g G A long double

These modifiers affect how all the printf functions interpret the data type of the corresponding input argument arg.

Both F and N reinterpret the input variable arg. Normally, the arg for a %p, %s, or %n conversion is a pointer of the default size for the memory model.

h, l, and L override the default size of the numeric data input arguments. Neither h nor l affects character (c, s) or pointer (p, n) types.

Flag Characters

The printf flag characters specify output justification, numeric signs, decimal points, trailing zeros, and octal and hex prefixes. The flag characters can appear in any order and combination.

FlagDescription
- Left-justifies the result, pads on the right with blanks. If not given, right-justifies result, pads on left with zeros or blanks.
+ Signed conversion results always begin with a plus (+) or minus (-) sign.
blank If value is non-negative, the output begins with a blank instead of a plus; negative values still begin with a minus.
# Specifies octal and hexadecimal format.
Plus (+) takes precedence over blank ( ) if both are given.

Examples
CodeOutput
printf("%5d",10);   10
printf("%-5d test",10);10    test
printf("%10s world","Hello");     Hello world
printf("%-10s world","Hello");Hello      world
printf("%+d",10);+10
printf("%+d",-10);-10
printf("% d",10); 10
printf("% d",10);-10
printf("%o",255);377
printf("%#o",255);0377
printf("%x",255);ff
printf("%#x",255);0xff

Type Characters

The information in this table is based on the assumption that no flag characters, width specifiers, precision specifiers, or input-size modifiers were included in the format specifier. NOTE: Certain conventions accompany some of these format specifiers.

Type Char Expected Input Format of output
Numerics
d i Integer Signed decimal integer
o Integer Unsigned octal integer
u Integer Unsigned decimal integer
x Integer Unsigned hexadecimal int (with a, b, c, d, e, f)
X Integer Unsigned hexadecimal int (with A, B, C, D, E, F)
f Floating point Signed value of the form [-]dddd.dddd
e Floating point Signed value of the form [-]d.dddd or e[+/-]ddd
g Floating point Signed value in either e or f form, based on given value and precision. Trailing zeros and the decimal point are printed if necessary
E Floating point Same as e; with E for exponent
G Floating point Same as g; with E for exponent if e format used
Characters
c Character Single character
s String pointer Prints characters until a null-terminator is pressed or precision is reached
% None Prints the % character
Pointers
n Pointer to int Stores (in the location pointed to by the input argument) a count of the chars written so far
p Pointer Prints the input argument as a pointer; format depends on which memory model was used. It will be either XXXX:YYYY or YYYY (offset only)

Infinite floating-point numbers are printed as +INF and -INF. An IEEE Not-A-Number is printed as +NAN or -NAN.

Examples
CodeOutput
printf("%d",123);123
printf("%i",123);123
printf("%o",123);173
printf("%u",54321);54321
printf("%x",123);7b
printf("%X",123);7B
printf("%f",12345.678);12345.678000
printf("%e",12345.678);1.234568e+04
printf("%e",0.0001234567);1.234567e-04
printf("%E",12345.678);1.234568E+04
printf("%E",0.0001234567);1.234567E-04
printf("%g",12345.678);12345.7
printf("%g",1234567.8);1.23457e+06
printf("%G",1234567.8);1.23457E+06
printf("%g",0.001234567);0.00123457
printf("%g",0.00001234567);1.23457e-05
printf("%G",0.00001234567);1.23457E-05
printf("%c",'A');A
printf("%s","test");test
printf("%%");%
int a; printf("%p",&a);FFF8 (address may vary)

Sunday, July 24, 2016

Data Type

Data type is type of data according to the nature and use of data. Every data type has limited size and range of values it can hold. There are two types of data types.
  1. Primary Data Type
    • int
    • float
    • char
    • void
  2. Secondary Data Type
    • Array
    • Pointer
    • Structure (struct)
    • Union (union)
    • Enumeration (enum)
  • int: It represent integer number. As stated above it has limited size depend on compiler and platform for which it is targeted. Size of int for 16 bit platform and compiler is 16 bit (2 Byte), for 32 bit platform and compiler is 32 bit (4 Byte) and so on. Range of int is depend on its size, we can get by following formula

    -(2 n-1) to 2 n-1

  • float: It represent real numbers. Its size is 32 bit (4 Byte) and its range is ±1.18 x 10-38 to ±3.4 x 1038.

  • char: It represent character/symbols. Its size is 8 bit (1 Byte) for ASCII standard. As char and int values are interchangeable according to ASCII standard, it can be used as 1 Byte integer in C/C++ language.

  • void: It represent no type, so doesn't have any size or range.
Secondary data types are constructed by using primary data type. It will be discussed later.

Data Type Modifier : Data type modifiers modify the base data types. There are two types of modifiers.
  1. Sign Modifier
    • signed It distributes half of the range of integer, long and char to negative. By default all data types are signed therefore there is no need to use it.
    • unsigned It make full range of integer, long and char to positive. Since all data types are signed by default, we explicitly declare unsigned data types to get more values in positive side.
  2. Range Modifier
    • short It has size of at least 16 bit (2 Byte) or half of the bits of integer size depend on OS to decrease the size and range of int.
    • long It has size of double bits of integer size depend on OS to increase the size and range of int. It can be used with double to further increase size and range of float.
    • double It has size of double bits of float size to increase the size and range of float.

You will get examples of all data types and modifier in further blogs.

Thursday, July 21, 2016

Format Specifier

Format specifiers defines the format of data to be printed on standard output or to be read from standard input. In printf format strings, format specifiers have the following form:

% [flags] [width] [.prec] [size] type_char

Each format specifier begins with the percent character (%). After the % come the following, in this order:

ComponentRequirementDescription
[flags] Optional Flag character(s)
Output justification, numeric signs, decimal points, trailing zeros, octal and hex prefixes
[width] Optional Width specifier(s)
Minimum number of characters to print, padding with blanks or zeros
[.prec]Optional Precision specifier(s)
Maximum number of characters to print; for integers, minimum number of digits to print
[size]Optional Size modifier(s)
Override default size of next input argument
N = near pointer    h = short int
F = far pointer     l = long int
L = long double
type_char Required Conversion type character(s)

Every component is explained with examples in another post specific to component. So go to component post by link either in table or in archive for detailed study.

Thursday, July 14, 2016

Escape Sequences

Escape sequences are used in many programming languages (with some variations) like C, C++, Java and C#. An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal, but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly.

In C, all escape sequences consist of two or more characters, the first of which is the backslash, \; the remaining characters determine the interpretation of the escape sequence. e.g \n is an escape sequence that denotes a newline character.

Suppose we want to print out Hello, on one line, and world! on the next line. One could attempt to code as follows:

#include <stdio.h>
int main() {
    printf("Hello,
            world!");
}

This is not valid in C, since a string literal may not span into multiple lines in source code. This can be worked around by printing the newline character using its numerical value (0x0a in ASCII),

#include <stdio.h>
int main() {
        printf("Hello,%cworld!", 0x0a);
}

This program prints Hello,, followed by the byte whose numerical value is 0x0a, followed by world!. While this will indeed work when the machine uses the ASCII encoding, it will not work on systems that use other encodings, that have a different numerical value for the newline character. It is also not a good solution because it still does not allow us to represent a newline character inside a literal, and instead takes advantage of the semantics of printf. In order to solve these problems and ensure maximum portability between systems, C interprets \n inside a literal as a newline character, whatever that may be on the target system:

#include <stdio.h>
int main() {
    printf("Hello,\nworld!");
}

In this code, the escape sequence \n does not stand for a backslash followed by the letter n, because the backslash causes an "escape" from the normal way characters are interpreted by the compiler. After seeing the backslash, the compiler expects another character to complete the escape sequence, and then translates the escape sequence into the bytes it is intended to represent. Thus, "Hello,\nworld!" represents a string with an embedded newline, regardless of whether it is used inside printf or anywhere else.

This raises the issue of how to represent an actual backslash inside a literal. This is done by using the escape sequence \\.

The following escape sequences are defined in standard C. This table also shows their ASCII value. However, these escape sequences can be used on any system with a C compiler, and may map to different values if the system does not use a ASCII encoding.

Escape sequence Hex value in ASCII Character represented
\a 07 Alert (Beep, Bell) (added in C89)
\b 08 Backspace
\f 0C Formfeed
\n 0A Newline (Line Feed)
\r 0D Carriage Return
\t 09 Horizontal Tab
\v 0B Vertical Tab
\\ 5C Backslash
\' 27 Single quotation mark
\" 22 quotation mark
\? 3F Question mark
\nnn any The byte whose numerical value is given by nnn interpreted as an octal number
\xhh… any The byte whose numerical value is given by hh… interpreted as a hexadecimal number

Wednesday, July 13, 2016

Keywords

C90 has 32 reserved words, also known as keywords, that cannot be used for any purposes other than those for which they are predefined. Following are keyword in group according to their use.

Data type
char, double, float, int, long, short, signed, unsigned, void

Custom Data Type Definer
enum, struct, union

Jump Instruction
break, continue, goto, return

Control Instruction
case, default, else, if, switch

Loop Instruction
do, for, while

Scope Definer
auto, extern, register, static

Other
const, sizeof, typedef, volatile


Introduction

C is a general-purpose, imperative, high-level programming language developed by Dennis Ritchie to develop the UNIX operating system at Bell Labs in 1972. It has since become one of the most widely used programming languages of all time.

It supports structured programming, variable scope, recursion and static type system that prevents many unwanted operations. C efficiently maps it's code to machine instructions, and hence it is suitable for applications that is to be coded in assembly language, including operating systems and application software for various computers ranging from supercomputers to embedded systems.

C has been standardized by the American National Standards Institute (ANSI) since 1989 (see ANSI C) and after that by the International Organization for Standardization (ISO).

Despite its low-level capabilities, the language was designed to encourage cross-platform programming. A standards-compliant and portably written C program can be compiled for a very wide variety of computer platforms and operating systems with few changes to its source code. The language has become available on a very wide range of platforms, from embedded microcontrollers to supercomputers.

For more information go to Wikipedia

Programming in C is much easy, you can write your first Hello World program as below and compile the code with any C compiler to generate executable file and execute that file to get output.
#include<stdio.h>
void main()
{
    printf("Hello World");
}

In above code #include is pre-processor statement. It gives instruction to compiler to replace this statement with content of stdio.h (file inside of <>) before compilation.
void main() is main function and entry point for program. Statements to be executed in program is written inside of {}.
printf is function to print given message, string and any other formatted values on screen.