printf

printf's name comes from print formatted. It generates output under the control of a format string (its first argument) which consists of literal characters to be printed and also special character sequences--format specifiers--which request that other arguments be fetched, formatted, and inserted into the string.
 

There are quite a number of format specifiers for printf. Here are the basic ones :

%d print an int argument in decimal
%ld print a long int argument in decimal
%c print a character
%s print a string
%f print a float or double argument
%e same as %f, but use exponential notation
%g use %e or %f, whichever is better
%o print an int argument in octal (base 8)
%x print an int argument in hexadecimal (base 16)
%% print a single %

 

Data types

printf conversion specification

scanf conversion specification

long double

%Lf

%Lf

double

%f

%lf

float

%f

%f

unsigned long int

%lu

%lu

long int

%ld

%ld

int

%d

%d

short

%hd

%hd

char

%c

%c

Terminate a program

Another excellent thing to know when doing any kind of programming is how to terminate a runaway program. If a program is running forever waiting for input, you can usually stop it by sending it an end-of-file, as above, but if it's running forever not waiting for something, you'll have to take more drastic measures. Under Unix, control-C (or, occasionally, the DELETE key) will terminate the current program, almost no matter what. Under MS-DOS, control-C or control-BREAK will sometimes terminate the current program.

Using these two functions, we can write a very basic program to copy the input, a character at a time, to the output:

#include <stdio.h>

/* copy input to output */

main()
{
	int c;

	c = getchar();

	while(c != EOF)
		{
		putchar(c);
		c = getchar();
		}

	return 0;
}

When you run this program, it will probably seem to copy the input a line at a time, rather than a character at a time. You may wonder how a program could instead read a character right away, without waiting for the user to hit RETURN. That's an excellent question, but unfortunately the answer is rather complicated, and beyond the scope of our discussion here. (Among other things, how to read a character right away is one of the things that's not defined by the C language, and it's not defined by any of the standard library functions, either. How to do it depends on which operating system you're using.)