C++ An Introduction: Part 3
C++: An Introduction: Part 3
- Note: I will be using a changelog from now on, to document changes to every post of this series.
- 2-23-2020 1750: fixed typo that @Highwayman found!
- Thanks for the support people!
- Questions? Comments? Errors to point out? Tag me in the comments(@ipastrano) and upvote if you like!
This post will focus on variables(easier than it sounds).
- Variables hold pieces of information such as integers, decimals, characters, words, phrases, etc. The variables can be operated on (arithmetic, printing to the screen, etc.)
- Each variable holds a certain amount of space in the computer, but it's unlikely to fill up your computer unless there are a LOT. (I have made ~35-50 programs on repl all in c++, and they total less than 1MB!)
- Variables cannot hold information that they aren't meant to(ex. an integer variable cannot hold a character, etc.)
- Here, I will introduce you to numeric variables.
- To create an integer variable, use
intin this fashion:
- Just so you know, x is not really a good variable name. Make the name useful.
- Here are a few examples:
- I'm holding the square footage of a house: use squareFeet or better yet, houseSquareFeet.
- I am holding the number of apples to buy from the store: use apples, or numApples.
- I am holding the number of people who read this post. Use numPeople or peopleRead.
- Note that the variable name cannot start with a digit, or be a keyword such as if, int, else, for, while, do, float, double, char... the list goes on.
- No special characters such as !, @, #, $, %, ^, &, *, (, ), =, or +.
- There are two widely accepted ways to define variables:
camelCase. I prefer camel case, but it is ultimately your choice!
- Here are the different numeric variables(integers only).
short= for short integers.
unsigned short= for short whole numbers.
int- for integers.
unsigned int- for whole numbers.
long= for long integers.
unsigned long= for long whole numbers.
long long= for REALLY LONG integers.
unsigned long long= for REALLY LONG whole numbers.
- To assign, put the variable name on the left hand sign of an equals(=) and put the value on the other.
int apples; apples = 5;
- Before assignment, the variable
appleshad a garbage value such as 1945738. Then I put the value 5 into apples.
- To display the number, use cout in this fashion:
cout << apples;
- This will display 5. nothing more, nothing less.
- To add some context, use text:
cout << "This apple pie recipe requires " << apples << " Fuji apples.\n";
This apple pie recipe requires 5 Fuji apples.
That's all folks: Tune in next Sunday!
Note to self: Insert jazz music here
You are viewing a single comment. View All