How to teach C to a violinist (Part II)
Posted by jayzeegp en julio 14, 2008
If you did not see part I, please click here.
On this entry we will learn how to make Output in C. Basic Output will appear on screen.
We will learn the use of printf function in order to do this.
In the past we learned how to declare variables and make some easy operations with them.
But, how can we know if our program does the operations well if we can’t see the values of the variables on screen?
This is what we will learn today. We will learn (in the easiest way I can explain it) how to print data on screen.
We just know int variables so I will just explain how to put integers on screen (also normal text).
A little example to understand it:
printf(“This message will appear on screen\n”);
As you see, you must put the “ symbol before and after the sentence you want to appear on screen.
The \n makes that, the next time you put something on screen, it will appear on the next line. Is like when you press Enter key on a text processor.
I want to put the value of variable a (created on part I) on screen! How can I do that?
I will show you an example:
printf(“A values %d”,a);
%d? Are you crazy?
I will try to explain it easily, you put %d where you want the number which a contains to appear. If a has the value 4, on screen will appear:
A values 4
After the symbol , you put the name of the variable whose value you want to appear on screen.
How can I put several variable values?
I think you will understand it soon if you understood the last part:
printf(“A values %d and B values %d”,a,b);
You just need to pay attention to put them in order.
Now you should be able to modify your program and make it show the value of the variables on the screen.
I want to prove that I am a genious! Give me an exercise!
Ok, but I hope you will post it on the comments to let me see😛
1.- Make a program with 3 variables, you can put the names you want, the first one will value 4, the second one will value 8 and the third one will value the addition of first and second. Then, you will print a message on screen with some text and the value of every variable.
Note: when you declare a variable, you can’t make it use the values of other variables, so, with the third variable, you will have to declare it without value (int nombre; ) and after that, change its value.
2.- Use the program you did on first exercise and put comments (explained on Part I) explaining with your own words what do you think the program is doing on every “command” you typed.