Computer Concept & Programming In C - Unit II - 2

Q.3 Explain putc ( ) and putchar ( ) with example.
Ans. Printing the Output on the screen: -
Beside getc ( ) and getchar ( ) for reading, the C language also provides two functions, putc ( ) and putchar ( ), for the writing.
Using the putc ( ) function: -
The putc ( ) function writes a character to the specified file stream, which in our case, is the standard output pointing to your screen.
The syntax for the putc ( ) function is:
  # include <stdio.h>
  int putc (int c, FILE * stream);
here, the first argument, int c, indicates that the output is a character saved in an integer variable c; the second argument, FILE * stream, specifies a file stream. If successful, putc ( ) returns the character written; otherwise it returns EOF.
The following example uses the standard output stdout to be the specified file stream in putc ( ). The putc ( ) function is used to put a character on the screen.
  # include <stdio.h>
  # include <conio.h>
  void main ( )
{
  int ch;
  ch = 65; /* The numeric value of A*/
  printf (“\ n The character that has numeric value of 65 is: \n”);
  putc (ch, stdout);
getch ( );
}
The output of the above program is below:
The character that has numeric value of 65 is: A.
Another Function for writing: putchar ( ): -
Like putc ( ), putchar ( ) can also be used to display a character on the screen. The only difference between the two functions is that putchar ( ) needs only one argument to contain the character. There is no need to specify the file stream, because the standard output (stdout) is the default file stream to putchar ( ).
The syntax for the putchar ( ) function is.
  # include <stdio.h>
  int putchar (int c);
Here, int c is the argument that contains the numeric value of a character (ASCII code). The function returns EOF if an error occurs; otherwise it returns a character that has been written.
An example of using putchar ( ) is given below.
  # include <stdio.h>
  # include <conio.h>
  void main ( )
{
  clrscr ( );
  putchar (65); /* prints A */
  putchar (10); /* new line */
  putchar (66); /* prints B */
  putchar (10); /* new line */
  putchar (67); /* print C */
  getch ( ); /* Wait for a key to be pressed*/
}
The output of the above program is
A
B
C
There is no variable declared in the program. Rather the integers are passed to putchar ( ) directly.
65, 66 and 67 are numeric values of characters A, B and C respectively. 10 is the value of new line character (\n).