Basic output in C

From Wikiversity

(Redirected from Basic Output)
Jump to: navigation, search

Output 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:

Thumb

Contents

[edit] The amazing printf() function

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.

[edit] 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)

[edit] Examples

Some Odyssey

[edit] Exercises

Quoth the Raven


Project: Topic:C
Previous: Introduction to C — Basic output in C — Next: Data Types and Keywords