If we want to see what happens to the values as a computer runs through the program, we can use a function called print().
// Declare and initialize the variables int firstValue = 5; int secondValue = 17; int temporary = 0; // Print the values in the variables before swapping print(“Before swapping\n”); print(“firstValue is: ” + firstValue + “ and secondValue is: ” + secondValue + “\n”); // Swap the values in firstValue and secondValue temporary = firstValue; firstValue = secondValue; secondValue = temporary; //Print the values in the variables after swapping print(“After swapping\n”); print(“firstValue is: ” + firstValue + “ and secondValue is: ” + secondValue + “\n”);
The program should print in the console:
If you looked at the example above, you probably saw a few things that confused you, like quotation marks around certain words, the use of “\n,” and the use of the addition (+) operator.
In Processing, words are called Strings (with an uppercase “S”). You can tell the difference between a String and a variable name because a String has quotation marks around the word and a variable name has no quotation marks around the word.
When you are using a word processor, if you want to start a new line of text, you hit the “return” key on the keyboard. To start a new line of text while using the print() function, you need to use the two characters “\n” together with no spaces between the backslash and the letter n. This tells the computer that any text after “\n” needs to be on a new line.
print(“This sentence is on one line\n”); print(“This sentence is on the next line”);
println(“This sentence is on the first line”); print(“This sentence is on the second line ”); println(“ This sentence is not on a new line”); print(“This sentence is on the third line”);
String firstName = “George” String lastName = “Washington” print(“The president of the US is:” + firstName + secondName);
If you ran the previous example in Processing, you prob- ably noticed that there were no spaces between some of the words. We will have to add our own spaces.
String firstName = “George” String lastName = “Washington” print(“The president of the US is: ” + firstName + “ ” + secondName);
Leave a Reply