Syntax Cheat Sheet
This document summarizes the syntax patterns you should have memorized. In case you're wondering, no, you will not be allowed to use this during an exam.
General Structure
* Program name, author, purpose
*/
preprocessing directives
int main() {
what your program does
return 0;
}
Variable Declarations
[modifier] type name [= value];
double seconds = 23.6;
const char YES = 'y';
bool aceTest = true;
int cats, dogs; // multiple declaration
cats = dogs = 20; // multiple assignment
Expressions
Have a pragmatic understanding of operator precedence. When in doubt or to express clarity, use parenthesis.
int femaleDogs = 2;
int puppies;
puppies = maleDogs * femaleDogs;
puppies++; // one more puppy
puppies += 5; // five more puppies
puppies *= 5; // five times as many puppies!
int example = maleDogs / femaleDogs; // why does this yield 1?
example = 0 % maleDogs; // 0 % anything is always 0
Operations with Mixed Types
An int operator int yields an int. A double operator double yields a double.
Operations with mixed types will yield a value whose type is of the "greater precision," so to speak. A double operator int yields a double.
Console I/O
Using cout and cin requires the iostream library and declaring "using namespace std;" (more about namespaces later).
using namespace std;
int main() {
int age; cout << "Hello, how old are you?" << endl;
cin >> age;
cout << "Well, enjoy it while you're " << age << ". Want to party?" << endl; }
Example interaction of the above code:
21
Well, enjoy it while you're 21. Want to party?
Remember, when passing variables to cin
and cout
, datatypes matter. What would you see on the screen if the user enters 33.4
instead of 21
? What would you see on the screen if age
is declared as a double
? What if the user types q
or none of your beeswax
?
Flow control: if, else if, else
Remember, all boolean expressions get evaluated and yield a value. if
does one thing only, it checks to see if the provided condition evaluates to true
or false
.
if (condition) {
do something
}
if (condition) {
do something
} else {
do something else
}
if (condition) {
do this
} else if (another condition) {
or do this
} else {
or do something else
}
cout << "Do you like cookies? (enter Y or N)\n";
cin >> answer;
if (answer == 'Y') {
cout << "No way! I love cookies too!\n";
} else if (answer == 'N') {
cout << "Hm, maybe I can offer you some green beans.\n";
} else {
cout << "I'm confused. Guess I'll go eat a cookie.\n"
}
Remember, flow control constructs can be nested. Keep it tidy.
char likesArtichokes;
cout << "Do you like cookies? (enter Y or N)\n";
cin >> likesCookies;
if (likesCookies == 'Y') {
cout << "Ok, but do you like artichokes? (Y or N)\n";
cin >> likesArtichokes;
if (likesArtichokes == 'Y') {
cout << "Artichokes, nice!\n";
} else {
cout << "Geez, no artichokes?\n";
}
} else if (answer == 'N') {
cout << "Hm, maybe I can offer you some green beans.\n";
} else {
cout << "I'm confused. Guess I'll go eat a cookie.\n"
}
Flow control: while
Remember, a while loop assumes some initial state of the world before it begins, checks the terminating condition, and usually includes something to change the condition within the loop.
initialization
while ( condition ) {
do something
modifier
}
Here's one example, which prints the numbers 10 down to 1.
while ( countdown > 0 ) {
cout << countdown << endl;
countdown--;
}
Flow control: for
A for
loop has the same three main loop components (initialization, condition, modifier) as a while loop but in a more concise syntax.
for ( initialization; condition; modifier ) {
do something
}
Here's the above while loop rewritten as a for loop.
for ( int countdown = 10; countdown > 0; countdown-- ) {
cout << countdown << endl;
}
Text File I/O: Reading Data
When reading from text files, you will use an ifstream
object. Remember, you will always do at least four things: open the file, check for error, iterate over the data in the file stream, and close the file.
Here's an example of the typical "boilerplate" code:
using namespace std;
// ...
ifstream myData("filename");
if (!myData) {
// handle error
}
while ( myData >> myVar) {
// do stuff
}
myData.close();
Assuming the data file contains a series of decimal numbers, you might print the numbers like this:
using namespace std;
double score;
ifstream scores("scores.txt");
if (!scores) {
cerr >> "Could not read file.\n";
exit(1);
}
while ( scores >> score) {
cout << score << endl;
}
scores.close();
Text File I/O: Writing Data
When writing to text files, you will use an ofstream
object. Remember, you will always do at least four things: open the file, check for error, write to the file, and close the file.
Here's an example of the typical "boilerplate" code:
using namespace std;
// ...
ofstream myData("filename");
if (!myData) {
// handle error
}
myData << "Oh gee.\n";
myData << "I can write to a file similar to how I use cout.\n";
myData << "But instead of cout I just use...\n";
myData << " the name of the output stream.\n";
myData.close();
Defining Functions
Functions are always defined according to the following pattern.
returnType functionName(parameterList) {
// function drama
// properly indented, of course
}
Every function has a return type, name and parameter list. However, parameter lists can be empty if the function accepts no arguments. If the function does not return a value to its caller, then the return type should be void
.
More importantly, you need to be able to write a function given a particular definition. Here is one example: "Write a function called dance
that accepts one int
parameter called howLong
, one string
parameter called move
and returns a boolean value."
// function drama properly indented, of course
// returns some boolean value
}
Arrays
The general pattern for array declaration is like this:
dataType arrayName[size];
char letters[5]; // declares an array of ten characters
int scores[2] = {10, 20}; // declares and initializes values
int ratings[5] = {0}; // initializes all array values to 0
letters[0] = 'q'; // stores the value 'q' in the 0th position
int x = scores[1]; // assign the value in the 1th position to x
Arrays & Loops
Remember, for loops naturally complement arrays, and the for loop's counter variable is often used inside the loop to access the array.
int ages[NUMBER_OF_AGES];
for (int i = 0; i < NUMBER_OF_AGES; ++i) {
ages[i] = 21;
}
// ages now contains ten 21's. Have a root beer.
Two-dimensional Arrays
The general pattern for a 2D array declaration is like this:
dataType arrayName[rows][columns];
2D Arrays & Nested for
Loops
The key idea here is that the outer loop determines "which row" while the inner loop determines "which column."
const int WEEKS = 2;
int temperatures[WEEKS][DAYS_IN_WEEK];
for (int i = 0; i < WEEKS; ++i) {
for (int j = 0; j < DAYS_IN_WEEK; ++j) {
temperatures[i][j] = 0; // cold
}
}
// temperatures now contains two rows of seven values (all 0). Have a kombucha.
Using Objects
There are three key things to remember regarding the use of objects: instantiation, accessing data members, and accessing member functions.
Rectangle s(10, 10); // invokes parameterized constructor
cout << r.width; // accessing public member variable
r.height = 230; // assigning value to public member variable
cout << r.volume(); // calling member function
Vectors
Remember, a vector is like an array but without the extra baggage.
vector<int> numbers; // a vector called numbers that holds ints
vector<Bunny> rabbits; // a vector called rabbits that holds cute Bunny objects
Classes
Remember, your class definition needs a trailing ; after the closing brace.
bunny.hpublic:
Bunny();
Bunny(int c);
int getCuteness();
void setCuteness(int c);
private:
int cuteness;
};
bunny.cpp
cuteness = 100; // very cute
}
Bunny::Bunny(int c) {
cuteness = c;
}
int Bunny::getCuteness() {
return cuteness;
}
void Bunny::setCuteness(int c) {
cuteness = c;
}
Passing Arguments by Reference
Remember, the "rule of thumb" is to (almost always) pass objects by reference.
In order to tell the machine that a function should receive its argument by reference, you simply prepend a & before the parameter name.
sq.red = 255;
}
Square s;
changeRed(s);
// s.red is now 255
©2011 Yong Joseph Bakos