C Programming/Basic Output

From Wikiversity
< C Programming(Redirected from C/Basic Output)
Jump to navigation Jump to search
Icon tools.svg Completion status: Almost complete, but you can help make it more thorough.

Objective[edit | edit source]

Books-aj.svg aj ashton 01f.png
  • Learn how to output text to the console.

Lesson[edit | edit source]

Output is information that the program tells the user. The most basic way to do this is writing text to the console. In the previous lesson, we output text to the console using the following program:

#include <stdio.h>
int main(void)
     printf("Hello world!\n\n");
     printf("Press any key to continue ...");
     return 0;

If you compile the above program and run it, you will get this output:


The function getch() is an input function that waits for the user to tap any key on their keyboard and returns a char representing that key. You will learn about input later on in this course.

printf()[edit | edit source]

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

Variables can be printed and formatted using the printf() function. Consider the following piece of code:

#include <stdio.h>

int main(void)
     char a = 'A';
     printf("%c\n", a);
     printf("%d\n", a);
     return 0;



First, we define a char called a and assign it the value of the character A. Then we pass to printf() a string with formatting instructions and a variable. We use %c to print the value of a as a char, and %d to print the value of a as an integer.

Escape sequences[edit | edit source]

\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 removed "\n" from the first printf() call in the previous example, the second printf() would not be printing on a new line, and you would see the following:


This is because there is nothing telling the console to put a new line between "A" and "65".

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

Further reading[edit | edit source]

Assignments[edit | edit source]

Crystal Clear app kedit.svg