Monday, 1 June 2015

Tutorial 3 - Printing in C printf statement

    This is the third tutorial of series  and in this we will be discussing about the printf() Statement used for showing or printing outputs in c programming language.

So in the previous tutorial we have learned the basic structure of C program and in that we have used printf("") statement and promised you to discuss it in very next tutorial So here we go....

What is printf() and why to use it ????

  • Simply you can say that its an statement to send output or formatted output to your console screen i.e. stdout.
  • We are going to use it as it's simple and most widely used statement for displaying messages or for printing outputs on the screen.
So first thing is we need to understand the syntax of printf statement
         printf(const char *format, .......);

So now let me explain you the format used above with the examples..
                                  

  Format

 While printing any message on the screen sometimes we also need to print the values of some variables or we need to display formatted output so in that case there are certain rules like if you want to print a simple integer or what to print the string on screen for that case there are certain symbols that tells about the nature of variable you need to print on screen these are format specifiers.

There is one thing you need remember that format specifier always starts with the '%' percentage or modulus symbol.

So prototype for format is %[flags][width][.precision][length]specifier

Don't be worried meaning of all these are explained below:-

lets get started with the specifier one first

Specifier is a one word which is specifying the data type of variable you want to print on your output console screen.
                        Like if you need to print an integer then your specifier will be "d" and your format will become "%d". Then your printf() statement will look like :-
  Suppose "a" is a variable.

  •     printf("Value of a is %d",a);
Here is the list of C language specifier.

Specifier
Used for printing
c
Character
d or i
Signed decimal integer
e
Scientific notation (mantissa/exponent), Using e
E
Scientific notation (mantissa/exponent), Using E
o
Unsigned octal
x
Unsigned hexadecimal integer
X
Unsigned hexadecimal integer(Uppercase)
f
Decimal floating point, lowercase
F
Decimal floating point, uppercase
g
Short form of %e or %f
G
Short form of %E or %F
a
Hexadecimal floating point, lowercase
A
Hexadecimal floating point, uppercase
s
String
p
Address of pointer
n
Nothing
%
Followed by % for printing single % to the stream.

Example illustrating usage of all specifier:-

#include<stdio.h>
#include<conio.h>
void main()
{ int a=10; //declaring and initializing integer variable
  char c='s'; //declaring and initializing Character variable
  float d=10.2; //declaring and initializing Float variables
  char e[]="Sahib Singh"; //declaring and initializing String
  int *f; //declaring int pointer 
  f=&e; //initializing pointer

  printf("\nC contains : %c",c);
  printf("\nInteger 'A' contains %d",a);
  printf("\nIn Exponential form %e",.314);
  printf("\nIn Exponential Form %E (Uppercase)",3.14);
  printf("\n100 In octal %o",100);
  printf("\n100 In Hexadecimal %x",100);
  printf("\n100 In Hexadecimal %X (Uppercase)",100);
  printf("\nFloat 'd' contains %f",d);
  printf("\nFloat 'd' contains %F (Uppercase)",d);
  printf("\nUsage of g %g",.314);
  printf("\nUsage of G %G",3.14);
  printf("\nString e contains:  %s", e);
  printf("\n pointer address %p",f);
  getch();

}

OUTPUT


Basically we will be using '%d','%f','%c'& '%s' for integers,float (Digits with points) ,single character and whole sentence respectively.

Now flags are used to print formatted output.
                                                                         Like you need spaces or to adjust the pads or we need to specify our output to certain width then we are going to use flags.
   Table of available flags in C
flags
Used for
-
Left justifying output within the given width
+
Preceding the output with ‘+’ if +ive else ‘-‘
(space)
Inserting spaces within specified width
#
Preceding octal and hexadecimal numbers with 0 and 0x respectively
0
Filling up the ‘0’ in left padding case instead of space.

Example:- Now our examples will contain specifier and flags both so that's gonna be more funnn.....
   we can use our flags with any specifiers.

#include<stdio.h>
#include<conio.h>
void main()
{ char c='s';  //declaring and initializing character
  int a=10;
  /*
   Justification and preceding example
  */  
   printf("\n\n\t\t Justification and preceding\n");
  printf("\n\t\t\tUsing Flags");
  printf("\nRight Specified C : %10c",c);
  printf("\nLeft Specified C : %-10c",c);
  printf("\nWith default precede: %d",a);
  printf("\n Without default precede: %+d",a);
  printf("\nUsing both right justification and precede %-+10d",a);
  printf("\nUsing both left justification and precede %+10d",a);

  /*using # 
    basically # is used with octal and hexadecimals to print them 
    in thier natural way of writing
  */
   printf("\n\n\t\t Using #\n");
   printf("\n 100 in octal without # %o",100);
   printf("\n 100 in octal with # %#o",100);
   printf("\n 100 in Hexadecimal without # %x",100);
   printf("\n 100 in Hexadecimal with # %#x",100);
   /*
    Padding or filling spaces with o(zeros)
   */
   printf("\n\n\t\t Filling up spaces with 0\n");
   printf("\nRight Specified string filled with 0 : %010s","sahib");
 
  getch();

}

OUTPUT


Now it's turn for width although I have used in above examples but let me explain you what it is. Its is used for specifying the width of our output and than we can specify our justification and spacing.

Here's the table available option in width


Width
Used for
(number)
Specifying the width of our output.
*
In this case no width is specified but the argument preceding the width argument need to be executed.

Example program

#include<stdio.h>
#include<conio.h>
void main()
{ char c='s';  //declaring and initializing character
  int a=10;
  /*
   width example
  */  
   printf("\n\n\t\t Using Width\n");
  printf("\nRight Specified width 10 C : %10c",c); //here width is 10 
  printf("\nLeft Specified width 15 C : %-15c",c);
  printf("\nWith default precede(No width): %d",a);


  getch();


}


Output


 Precision what it actually do is these are used to specify the minimum number of digits to print and    '0' itself to the number if the number is smaller than minimum specified digits and only applies to  integer digits.
 Example illustrating the concept is given below.

.precision
Used for
.number
Only for integers specifies the minimum number of digits to be printed and ‘0’ additional if less than minimum digits.
.*
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

Example

#include<stdio.h>
#include<conio.h>
void main()
{ char c='s';  //declaring and initializing character
  int a=10;
  /*
   width example
  */  
   printf("\n\n\t\t Using Width\n");
  printf("\nRight Specified width 10 C : %.10c",c); //Percision will not working on characters
  printf("\nLeft Specified width 15 C : %.5d",a);
  printf("\nWith default precede(No width): %d",a);

  getch();
}

Output



 Last but not least length these are additional specifier used to for printing various other types of datatypes like unsigned, long double etc. Table is given below specifying all the additional specifiers used with general specifier to print datatypes.

Length
Used for
h
Printing short int or unsigned int i.e. applies only to the integer specifiers.
l
Printing long int or unsigned long int i.e. applies only to integer specifiers and for printing wide character or wide character strings.
L
Printing long double data type and applies to floating point specifier.

  Example

#include<stdio.h>
#include<conio.h>
void main()
{ char c='s';  //declaring and initializing character
  int a=10;
  /*
   width example
  */  
   printf ("Decimals: %d %ld\n", 1977, 650000L); //Printing long double 
  getch();
}
Output


Some other features of printf() command

Now we will learn some features like how to move on to new line etc. using printf in c.

'\n' for new line, you may have seen '/n' operator I used in above program is simple used for moving our printing pointer to the new line in the output screen.
'\t' is for leaving a tab space on the output screen.
'\f' for moving on to the new page.
'\b' for backspace that's for moving our pointer to back by one character.
'\v' for specifying vertical tabs.

Usage of all the escape operator will shown in other tutorials.

Stay tuned for more tutorials and Thanks for patience reading hope you have got much knowledge about the printf command.

Video Explanation
Sorry Guys Explanation of this tutorial will be posted later this month.




No comments:

Post a Comment