C/Basic Output
< COutput is information that the program tells the user. The most basic way to do this is writing text to the console. The program below will demonstrate the writing of the text Hello world! to the console. Note that system passes its argument to the host environment to be executed by a command processor, it is up to the command processor how it deals with a command it does not understand.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("Hello world!\n\n");
if ( system(NULL) )
/* The following is a DOS command, it will fail in UNIX */
system("PAUSE");
else
puts("No command processor is available");
return 0;
}
If you compile the above program and run it on an MS-DOS system, you will get this output:

printf()
The line in the above example code that says printf("Hello world!\n\n"); is the one that outputs the Hello world! text to the console. printf() is reading what is called a string. In this case, the string is "Hello world!\n\n" part, including the double quotes. You can write almost any text you want.
Printing variables
Variables can be printed and formatted using the printf()
function. Consider the following piece of code:
#include <stdio.h>
int main() {
char a = 'A';
printf("%c\n", a);
printf("%d\n", a);
return 0;
}
/* OUTPUT
A
65
*/
In this code, we used %c
to print the character a
, but also %d
to print the integer version of a
.
Escape sequences
The \n tells the console to start a new line. \n falls under a category called escape sequences. These are commands denoted by the backslash. If you took out \n\n from the string, the result would be something like this:
Hello world!Press any key to continue...
This is because there is nothing telling the console to put a new line between the "Hello world!" and "Press any key to continue" strings.
Here is a table of most of the escape sequences.
Escape Sequence | Description |
---|---|
\' | Single quote |
\" | Double quote |
\\ | Backslash |
\nnn | Octal number (nnn)* |
\0 | Null character (really just the octal number zero) |
\a | Audible bell |
\b | Backspace |
\f | Formfeed |
\n | Newline |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\xnnn | Hexadecimal number (nnn)* |
*For both Hexadecimal and Octal number escape sequences, \nnn or \xnnn evaluates to a character with character code nnn. For example, \101 evaluates to the character A, as A has the character code of 101 in octal format.
Examples
Exercises
Project: Topic:C |
Previous: Introduction to C — C/Basic Output — Next: Data Types and Keywords |