Sample Video Frame
Exercise 3: Formatted Printing
Keep that Makefile around since it'll help you spot errors, and we'll be adding to it when we need to automate more things.
Many programming languages use the C way of formatting output, so let's try it:
#include <stdio.h>
int main()
{
int age = 10;
int height = 72;
printf("I am %d years old.\n", age);
printf("I am %d inches tall.\n", height);
return 0;
}
Once you've finished that, do the usual make ex3 to build and run it. Make sure you fix all warnings.
This exercise has a whole lot going on in a small amount of code, so let's break it down:
First we're including another header file called
stdio.h. This tells the compiler that you're going to use the standard Input/Output functions. One of those isprintf.Then we're using a variable named
ageand setting it to 10.Next we're using a variable
heightand setting it to 72.Then we're adding the
printffunction to print the age and height of the tallest 10-year-old on the planet.In
printf, you'll notice we're including a format string, as seen in many other languages.After this format string, we're putting in the variables that should be "replaced" into the format string by
printf.
The result is giving printf some variables and it's constructing a new string and then printing it to the terminal.
Register for Learn C the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.