Q&A: Variables

What is a variable? A variable is a location in memory where we can store data. A variable has a name that we refer to. We can access its data via the name, and we can overwrite the value in a variable.

What is a data type? The type of data a specific variable stores.

What is a named constant? A declared space in memory similar to a variable but the value cannot be changed after the first declaration.

What does an integer, float, boolean, char, and string store? give examples of declaring and assigning values to variables with each of these data types.

int age = 100;
int total_cats = 4;
float price = 8.75;
float temp = 98.5;
string street = "12345 College Blvd";
string email = "Blah@domain.net";
char currency = '$';
char answer = 'Y';

What is an assignment statement? How is it structured? An assignment statement is used to store a value in a variable. It uses the assignment operator, which is the = sign. The general form is VARNAME = VALUE;. The value can be another variable (its data will be copied over), a literal value (hard-coded value), or the result of an expression, such as a math operation.

float tax, price, price_plus_tax;

// Storing literal values
tax = 0.091;
price = 9.95;

// Storing the result of an expression
price_plus_tax = price + ( price * tax );

string cat1, cat2, favorite_cat;

// Storing literal values
cat1 = "Kabe";
cat2 = "Luna";

// Copying the value from another variable
favorite_cat = cat1;

What does increment and decrement mean? What are the three ways each you can write these statements? Increment means adding 1 to an (integer) variable and storing it back in the same variable. Decrement means subtracting 1 from an (integer) variable and storing it back in the same variable.

int num = 5;

num++;         // add 1
num += 2;      // add 2
num = num + 3; // add 3

num--;         // subtract 1
num -= 2;      // subtract 2
num = num - 3; // subtract 3

Author: Rachel Wil Sha Singh

Created: 2023-10-27 Fri 15:12