Variables, Constants
We need to be able to work with data in our programs. You can create variables as placeholders for values that will change as the program runs, and you can create constants to name values that will be fixed throughout the code.
When you create a variable or constant, you have to indicate the type of data that it will store as well as give it a unique name within the code where it is declared.
To get started, there are three built-in types you can use:
string
- when you want to store text data like “Hello” or “7”.int
- to store whole numbers like 7 or -25.double
- to store real numbers like 3.1415, or -0.0017.
Example
This code contains a number of variables: userInput
, width
, height
, and delaySeconds
. The code also contains a single constant CIRCLE_RADIUS
.
using static SplashKitSDK.SplashKit;using static System.Convert;
// userInput is a variable that stores a string value.// It will store the text the user enters to our promptsstring userInput;
// This creates three variables// - width to store how wide the window will be// - height to store how high it will be// - delaySeconds to store how long to delay at the endint width, height, delaySeconds;
// The circle radius is fixed - so we have a constant for this.const int CIRCLE_RADIUS = 50;
// Prompt the user read text into userInputWrite("How wide do you want the window? Enter width: ");userInput = ReadLine();
// Convert user input to a numberwidth = ToInt32(userInput);
// Repeat for the heightWrite("How high do you want the window? Enter height: ");userInput = ReadLine();height = ToInt32(userInput);
// And for delay secondsWrite("How many seconds do you want it to show for? Enter seconds: ");userInput = ReadLine();delaySeconds = ToInt32(userInput);
// Open a window and draw a circle// Use the width and height for the window sizeOpenWindow("Test Window", width, height);
// Draw a circle in the center of the screen, using a random color// and the set circle radiusClearScreen(ColorWhite());FillCircle(RandomColor(), width / 2, height / 2, CIRCLE_RADIUS);RefreshScreen();
// Delay for the number of seconds - we have to multiply delaySeconds// by 1000 to get the millisecondsDelay(delaySeconds * 1000);
CloseAllWindows();
Activities
How would you declare each of these?
- A variable to store the user’s name.
- A constant for PI with the value 3.1415.
- An integer variable for a cost per unit.
- A variable to store a phone number.
- A constant to store the maximum number of lines, with the value 100.
Answers
- 1:
string name;
- 2:
const double PI = 3.1415;
- 3:
int costPerUnit;
- 4:
string phoneNumber;
While this is a "number" it is actually best handed as text. Consider area code etc. Do you ever need to multiply a phone number? - 5:
const int MAX_LINES = 100;