6
Numbers

We’ve used numbers to measure and display temperature, weight, and how long to cook a turkey. Now let’s take a closer look at how numbers work in C programming. On a computer, numbers come in two flavors: integers and floating-point numbers. You have already used both. This chapter is an attempt to codify what a C programmer needs to know about these numbers.

printf()

But before we get to numbers, let’s take a closer look at the printf() function you’ve been using. printf() prints a string to the log. A string is a string of characters. Basically, it’s text.

Reopen your ClassCertificates project. In main.c, find congratulateStudent().

v​o​i​d​ ​c​o​n​g​r​a​t​u​l​a​t​e​S​t​u​d​e​n​t​(​c​h​a​r​ ​*​s​t​u​d​e​n​t​,​ ​c​h​a​r​ ​*​c​o​u​r​s​e​,​ ​i​n​t​ ​n​u​m​D​a​y​s​)​
{​
 ​ ​ ​ ​p​r​i​n​t​f​(​"​%​s​ ​h​a​s​ ​d​o​n​e​ ​a​s​ ​m​u​c​h​ ​%​s​ ​P​r​o​g​r​a​m​m​i​n​g​ ​a​s​ ​I​ ​c​o​u​l​d​ ​f​i​t​ ​i​n​t​o​ ​%​d​ ​d​a​y​s​.​​n​"​,​
 ​ ​ ​ ​ ​ ​ ​ ​ ​s​t​u​d​e​n​t​,​ ​c​o​u​r​s​e​,​ ​n​u​m​D​a​y​s​)​;​
}​

What does this call to printf() do? Well, you’ve seen the output; you know what it does. Now let’s figure out how.

printf() is a function that accepts a string as an argument. You can make a literal string (as opposed to a string that’s stored in a variable) by surrounding text in double quotes.

The string that printf() takes as an argument is known as the format string, and the format string can have tokens. The three tokens in this string are %s, %s, and %d. When the program is run, the tokens are replaced with the values of the variables that follow the string. In this case, those variables are student, course, and numDays. Notice that they are replaced in order in the output. If you swapped student and course in the list of variables, you would see

C​o​c​o​a​ ​h​a​s​ ​d​o​n​e​ ​a​s​ ​m​u​c​h​ ​M​a​r​k​ ​P​r​o​g​r​a​m​m​i​n​g​ ​a​s​ ​I​ ​c​o​u​l​d​ ​f​i​t​ ​i​n​t​o​ ​5​ ​d​a​y​s​.​

However, tokens and variables are not completely interchangeable. The %s token expects a string. The %d expects an integer. (Try swapping them and see what happens.)

Notice that student and course are declared as type char *. For now, just read char * as a type that is a string. We’ll come back to strings in Objective-C in Chapter 14 and back to char * in Chapter 34.

Finally, what’s with the ? In printf() statements, you have to include an explicit new-line character or all the log output will run together on one line. represents the new-line character.

Now let’s get back to numbers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset