Managing Input/Output Operations

To tell the user that you need to do something, you need to put something on the
console window, usually text, but sometimes combined with the results of other
workings of your program. There are a few functions that help us to do this:
printf – Used almost everywhere to show almost anything!
puts – Put a string to the screen and puts the cursor onto the next line
putchar – Put a character to the screen

The program below shows an example using only puts and putchar:
#include <stdio.h>
#include <conio.h>
void main()
char name[31];
puts( "Enter your name: "
); gets( name );
puts( "The first letter of your name is "
); putchar( name[0] );
And here's the results:
Enter your name:
The first letter of your name is
A better way to do it is:
#include <stdio.h>
#include <conio.h>
void main()
char name[31];

printf( "Enter your name: "
); gets( name );
printf( "The first letter of your name is %c", name[0]
); getch();
giving these results:

Enter your name: Prasad
The first letter of your name is P
The way printf works is to take the first item, which is always a string, and replaces
any occurences of % followed by a letter (sometimes with a bit more between) with
whatever follows after the comma (the next parameter). In this case, %c means
"put a character here" and name[0] is what is replaced – the first character of the
name character array – this first letter of the name that was typed in.

You can list as many of these % elements as you like, but make sure you have the
right number of replacement items to follow.
Note also that backslashes and the following letter are interpreted different ways –
e.g. \n means "new line" – i.e. move the cursor to the next line down and to the left
of the console.

Custom Search

%d bloggers like this: