home

Tutorials index

C Tutorial II: Input, mathematics

            Displaying a message is one thing, giving an answer is another. In the previous tutorial I showed you how to display text to the user, this time we will allow the user to tell us something, and we will give him an answer. But first thing first, a revision on priority in calculations.
You probably remember that parentheses are calculated first, powers next, multiplication and division next, and finally addition and subtraction. This is how it works for C too. There are some differences though, and the biggest of all is that you cannot uses brackets and such, but only parentheses. Another difference is that powers are calculated by calling a function called pow(), n-th roots can either be called by raising to the 1/n or by consecutive calls to sqrt() –you guessed it right, it stands for square root- if appropriate.
Other than that, we have to formalize symbols. For multiplication you might have used x, a dot, or just about anything else. In programming we generally use the asterisk * symbol. Division is done with the slash /. Powers are sometimes written with an upper arrow ^ in mathematics, and this is a very important difference, this symbol in C stands for XOR, X-OR, or eXclusive OR, whatever you want to call it. This is a logical function that you will probably never use, but if you are itching to find out what it is, either go google it up, or wait until I make a tutorial related to this. Since though there are no more symbols to explain, I can tell you that this means that an odd number of the total arguments passed is true, to cut it down to size, if you have two conditions, this will be true if only one is true, while if both are true or both are false, this returns false.
Another little issue of notation which I deny to call mathematical is that of assignment. You assign a value to a variable when you want it to store that valye and discard any previous one. This is done with a single equal = symbol. A big amount of your mistakes will be confusing this with the logical equality statement, which performs a comparison and returns 1 if the numbers are equal and 0 if not, it’s symbol is the double equal ==. An assignment will generally always return true, so it’s important that you pay attention to these two symbols. Let’s do some basic arithmetic, using variables as they were described in the previous tutorial.

int x;
int y;
int z;
x = 5;
y = 7;
z = x + y;

this piece of code declares 3 variables, named x, y, and z, assigns the values 5 and 7 to x and y, and then the sum of x and y to z. Obviously these names are dull, I’d rather name them Roger, John and Bishop, but I’d suggest you name them something that makes sense, like integer1, integer2, and sum, so you can remember what’s what.
The arithmetic is pretty elemental over here, so I’m not going to explain anything much, I just gave you a working example on something rather simple. However I should tell you about naming rules.
Variable names are a single word. This doesn’t mean you can’t combine words, for example if I wanted to name my variables Tim Burton and Johnny Depp, I still could do that. The obvious way is omitting the space inbetween first and last name. The other way is putting an underscore _ between the two. The underscore is “legal” to use as a character, though some programmers will say that you should not use it in the beginning or ending of the name as the system might already be using that, however, even though the chances that something like this will happen are few, I tend to follow that advice. Also allowed are numbers, digits to be more precise. After that, I would really not suggest using anything else, as neither do I know if you are allowed to, nor should you find yourself in such need.
But what use is the above piece of code if we cannot see the result? If you are curious, you already have tried to output the result with printf(), but I did not tell you the missing piece of information you need in the last tutorial. In any function, arguments are told apart by use of commas. To display a number in printf(), you have to do some magic in the quotes, and add the number as another argument. The magic is as follows, first you type the percentage symbol %, then you write a unique letter reserved for each type of variable. Integers are represented by d, floats by f, doubles by lf (that’s short for long float), and long doubles with llf. Variations may occur depending on the compiler. However there are the two weird variables, char and string, they are represented by c and s respectively, and I’ve let them out so we can talk about them a bit less briefly.

int x = 5;
printf(“%d”,x);

            Yes, before you ask, you can assign a value while declaring. And yes, you can display multiple numbers, all you have to do is add another %d and then the numbers separated by commas in the right order.
To assign a value to a char, you can either go to the ASCII table and find the numeric value of the character you want to store, or you can put it in single quotes ‘c’. The string is written in double quotes, and assignment works properly. To properly use a string you probably have to #include <string.h>, though again I have come across compilers that take care of that. Let’s see how we can read stuff then.
This works in a similar way to printf(). The new function is scanf(). However scanf() doesn’t take as an argument the value itself, but rather it’s address in the memory. This is the actual location where it is, and with some maneuvering you can display that, though I usually do that by creating an access violation error in Windows. Note that this last error is also called a segmentation fault, or segfault, and most frequently uses the two word name in unix systems, without telling us which unallocated or forbidden address we tried to access.
Back to scanf(). Luckily for you, C takes care of addresses, all you have to do is place the ampersand & symbol in front. That way the address of x is always &x. The only exception to getting input using the address is the string type. As mentioned before, strings are arrays of chars, and this becomes a little deep knowledge, but any reference to an array hides a memory address reference behind it, as will be explained in arrays and pointers tutorials, however, this does not apply to accessing a single element of an array. Let’s see it in action then, shall we?

int x;
scanf(“%d”, &x);
printf(“ The number augmented by 1 is %d”, x+1);

            I’ve probably shocked you right now, I love doing that. Yes, you can actually perform arithmetic inside printf(). X will not change, we did not assign it anything, though I believe it is time to show you how it could change. Also notice I left a blank space before writing “The number…”. I’ll explain both.
The mathematical part is simple, the result is what is displayed. However, because programmers are lazy, they invented some shortcuts for frequently used stuff. If you typed x = x + 1, it would be ok. However, if you had to type Hellena_Bonham_Carter = Hellena_Bonham_Carter + 1, that would start becoming boring after a while. This is why they invented ++. Typing x++ is equivalent to typing x = x+1. A small detail, though you can use x++ in an equation, and the result is stored into x, the ++ part will take effect after the equation is calculated. To make it take place before, you would write ++x. Also note that this is the only operation that can be done within another arithmetic operation without use of a function. There is of course the opposite operation, the decrement by one, x--.
Other usual programming bores are the addition of a value different than 1. Hellena_Bonham_Carter = Hellena_Bonham_Carter + 5 cannot be written with the ++, so other instructions were created, in this case, the entire part from the assignment operator to the end can be replaced with +=5. Correspondingly we have -=, *= and /=. This should pretty much cover you as far as math is concerned, I’ll only make one more example.

int x;
scanf(“%d”, &x);
x += 5;
printf(“%d”, ++x);

            This will print the value of x increased by 6, as you first increase it by five and the additional increase in the printf() is done before outputting to the screen.
Escaping from math, we have to see how we can change line to make our output more readable. This is done with escape characters. When you type a backslash \, the compiler automatically takes it and the following character and replaces them with the corresponding command. This is because many commands cannot be expressed by the keyboard, a very elemental example is \t, which tells the program to tab in, though you could use tab, 1) how would the program represent it on the screen, 2) how would it know if you wanted to actually display a tab or move one tab inwards? And in the second case you could say that if it is in text it is the same, however you can instruct the program to set a number of spaces for the tab, other than that of your IDE, in which case it could actually be different, much more if that number changes during runtime. These “codes” are called escape codes, and the backslash is generally an escape character.
The most useful escape characters are the tab(\t), the new line command (\n), and the backslash itself, represented by a double backslash (\\). All escape sequences are placed in your text without need of blank spaces flanking them or anything at all, they are replaced wherever found. So, while the previous example, if we entered 5, would have

511

written on the screen, if we change the last command to

printf(“\n%d”, ++x);

it should output:

5
11

since we also told the machine to change line.

 

            What now? Now you have added interactivity, the user can give you some input and you can process it before outputting. You can try making a string, reading the users name, and then telling him hello while also printing his name next to the hello. But further more, you can read two values and then print their sum, difference, as well as the results of their multiplication, division, and just about anything using the mathematical rules listed above.
For fun: Try making a simple guessing game, tell the user to guess a number between 1 and 10, then output your number minus his number divided by half, tell him that he will know his guess was right when the result is 0. What data type will the result have to be so that if your number was 6 and his 5 it will not show 0?

Call me mean for that last one, but you will understand how important it is that you think about such simple or annoying matters soon enough, have fun, experiment, and read on!