Writing to the console

Location
  1. Courses

    /

  2. Quick C course

    /

  3. Writing to the console

Console?

Before creating windows and displaying graphics inside them, we must first get comfortable with the basics. So for now, we will use the console. What is a console? A console is simply an interface from which we can output and input text.

Here is a console:

A console with the text "Hello!" printed inside it:

When we launch a program written in C, a console automatically opens (Unless we configure the compiler otherwise).

C Standard Library

In programming, a library is a set of tools that we can include to our code.

The C Standard Library is the name of the library provided by the C language. It is divided in many files. To use their functionalities, we must include them inside our code. Here, we include the file 'stdio', which provides tools to read/write from/to the console:

#include <stdio.h>

Function

A function is a group of instructions. When we 'call' a function, its instructions are executed.

We would call a function named 'func' like such:

func();

A function may require parameters (Also called arguments). In that case, we put them between the parentheses, separated by commas:

func(arg1, arg2);

Printing text to the console

To print something to the console, we may use the function 'printf'. We must give it, as argument, the text to print. Note that in C, text must be surrounded by quotes.

Here we print the text "Your character leveled up!":

printf("Your character leveled up!");

The full code:

main.cpp

1
2
3
4
5
6
7
8
#include <stdio.h> int main() { printf("Your character leveled up!"); return 0; }

To print a new line, we must write '\n' where we want it to appear:

printf("Your character leveled up!\n");

Printing integer numbers

To print integer numbers, we must put '%d' where we want a number to appear in the text and then give the number in argument after the text:

main.cpp

1
2
3
4
5
6
7
8
9
10
#include <stdio.h> int main() { int health = 100; printf("Health: %d, Energy: %d\n", health, 20); return 0; }

Printing floating-point numbers

We print floating-point numbers the same way as integer numbers, but with '%f' instead.

main.cpp

1
2
3
4
5
6
7
8
9
10
#include <stdio.h> int main() { float averageDamage = 65.73; printf("Average damage: %f, Progress: %f%\n", averageDamage, 83.46); return 0; }

As you can see, the value of 'averageDamage' is 65.730003 and not 65.73. Remember, variables of floating-point types often approximate the number they represent.