Name Syntax Explanation/Comment Example
• actual syntax
• what should be written
• explanatory
istreamVar refers to cin/ifstream variable/…
cout << expression/
Displays expression/ cout << endl; will move
manipulator <<
Output manipulator insertion point to next
expression/manipulator
#include<iostream> line
<< … ;
// single line comments
Comments /*…*/ multiple line
comments
Variables need to be
declared before they
Variable dataType identifier, double amountDue,
can be used
Identification identifier, …; count;
unsigned int can hold
only positive integers
Good practice for
named constants to const float
Constant data type const dataType identifier;
remain in uppercase CONVERSION = 2.54;
letters
Note that first character
of a string is in position
String declaration string str;
0
and initialisation str = “…”;
Needs header:
#include<string>
identifier += value;
identifier -= value; same as identifier =
Shortcut arithmetic
identifier *= value; identifier+value;
identifier /= value;
User inputs value
cin >> identifier >> #include<iostream>
Input statement
identifier >> …; >> skips all whitespace
until input found
static_cast<dataType>
(variableName);
Type conversion
or
dataType(variableName);
Displays expression to x
cout << setprecision(x) << digits for every output
Significant figures
expression; following this statement
#include<iomanip>
Displays expression to x
decimal points for every
cout << setprecision(x) <<
Decimal points output following
fixed << expression;
statement
#include<iomanip>
Name Syntax Explanation/Comment Example
Default decimal Disables fixed and
cout.unsetf(ios::fixed)
points returns output to default
#include<fstream>
i. Header
ii. Declare filestream
variables
ifstream inputData;
iii. Associate variables
ofstream outputData;
with input sources/
inputData.open(“…”);
output files
outputData.open(“…”);
iv. Use filestream variable
inputData >> variable1;
File stream with >>, << or other
…
input/output functions
outputData << variableN;
v. Close files
inputData.close();
Outputting to a file will
outputData.close();
rewrite everything that was
…
in the file
Prevent opening a file that
does not exist: if(!
fstreamVariable) {…}
\n newline
\t tab
Escape Sequences \\ prints backslash
\’ prints single quotation
\” prints double quotation
Includes all input for
Get function cin.get(varChar); char variable (including
whitespace)
Will ignore the the int cin.ignore(100, ‘\n’);
cin.ignore(intExpr, number of characters or will ignore the first 100
Ignore function
charExpr); the characters until the characters or until a
char is found newline is found
Takes the last variable
istreamVar.putback(varCh that get function took
Putback function
ar); and uses that as the
input
Returns the next
character from the
Peek function ch = istreamVar.peek(); sequence but does not
remove that character
from the stream
#include<iomanip>
cout << fixed << Ensures 0. is shown for
Showpoint
showpoint; numbers between -1
and 1
#include<iomanip> int a=8112, b=3715;
Outputs the value of the cout << setw(6) << a <<
cout << setw(a) << … expression immediately setw(5) << b;
Setwidth
<<setw(b) << …; after setw into specific Outputs:
no. of (right-justified) | | |8|1|1|2| |3|7|1|5| ie.
columns 8112 3715
Name Syntax Explanation/Comment Example
#include<iomanip>
Fills unused setw space
with ch character
Setfill ostreamVar << setfil(ch); Applies to rest of
program
To return to default: cout
<< setfill(‘ ‘);
Changes setw output
Left/Right
ostreamVar << left/right; from being right/left
Manipulators
justified
1- Input a whole line in a
getline(istreamVar, string, not just the first
strVar); characters until a
Getline whitespace
getline(istreamVar, strVar, 2- Inputs lines into a
chDelim); string until the delimiter
character
if (expression)
{
statements1
Two Selection if
}
Statement
else {
statements2
}
If expression1 is a max = (a>=b) ? a : b;
nonzero integer (true) ≡
expression1 ? expression2 : then result of conditional if(a>=b)
Conditional operator
expression3; expression is max = a;
expression2, otherwise else
result is expression3 max=b;
switch(expression)
{
case value1:
statements1:
break; //optional
Gives computer option
case value2:
Switch to choose from many
statements2:
alternatives
break; //optional
…
default: //optional
statements
}
#include<cassert>
If expression evaluates
to false the program will
Assert assert(expression); terminate
#define NDEBUG will
disable all asserts in a
program
Name Syntax Explanation/Comment Example
count=0
while(count<N)
Eventually count will
{
Counter-controlled equal N and while
…
while loop expression will evaluate
count++;
to false
…
}
cin >> var;
while(var != sentinel)
For case when the last
Sentinel-controlled {
entry of a list/file is a
while loop …
special value
cin >> var;
}
bool found = 0;
while(!found)
{
Flag-controlled while Bool variable controls
…
loop loop
if(expression)
found=1;
}
while(istreamVar) At the end of input data,
{ or when any faulty data
EOF-controlled while
… is read input stream
loop (end of file)
istreamVar >> variable; variable will return value
} of false
Logical expression that istream.inFile;
is true when program …
reads past end of input. while( !inFile.eof() )
Eof function istreamVar.eof() Function cannot tell {
whether the file is at the …
end but rather if the last inFile.get(ch);
input was faulty. }
for(initial statement; loop
Simplifies writing
condition; update
for loop counter controlled while
statement)
loops
{ statements}
Statements execute first
do and then expression is
do…while loop statements evaluated ie. loop will
while(expression) always execute at least
once
Skips the remainder of
Break break; break statement or exits
early from a loop
Name Syntax Explanation/Comment Example
Will skip remaining statements
in loop and continue with next
iteration of loop
Continue continue; Ina for loop, update statement
executes immediately after
continue and then loop test
evaluated
functionType
functionName( formal
Value-returning parameter list) functionType: data type
function (user- { of computed value
defined) statements
return x;
}
Formal parameter dataType identifier,
list dataType identifier,…
functionName (actual
Function call
parameter list)
Appears after
functionType preprocessors and before
Function prototype functionName( formal int main (declaration of
parameter list); function header, without
body)
void functionName()
Void function {
(without parameters) statements
}
void functionName(formal
parameter list)
Void function (with
{
parameters)
statements
}
Reference parameters
functionName can pass value from a
Reference
(dataType& identifier, function and change the
parameters
datatType& identifier,…) value of the actual
parameter
double z=3.1416;
allows for a global variable int main()
declared before a function/ { double z=2.0;
block to be accessible to cout << z << endl;
Scope resolution
::variableIdentifier function/block even if cout << z + ::z;
operator function/block has an }
identifier with the same //Outputs:
name as the variable 2.0
5.1416
Name Syntax Explanation/Comment Example
int main()
{
allows for a global variable
cout << z;
External variables extern dataType identifier; declared after function to
}
be used within function
extern int z = 2;
//Outputs 2
void counter()
{
static int count=0;
cout << count++;
}
Static variables hold
int main(0
Static variables static dataType identifier; their value through {
function calls for(int i=0;i<5;i++)
{
counter();
}
}
//Output : 0 1 2 3 4
enum typeName{value1,
Enumeration Data
value2, …};
Declaring enum enum sports{A, B, C, D};
typeName variable;
variables sporst mySport=A;
typedef existingTypeName declares newTypeName as
typedef
newTypeName; a synonym for a data type
Declare 1-D array dataType arrayName[intExp];
dataType
Declare 2-D array arrayName[intExp1][intExp2];
dataType
arrayName[intExp1][intExp2]
2-D array
= { { a1, b1, c1,…},
initialisation during { a2, b2, c2,…},
declaration … }}
Prefedined Math Functions:
Name Syntax Header and Explanation/
Comment
Power pow(x,y) // xy <cmath>
Square root sqrt(x) // √x <cmath>
Absolute abs(x) <cstdlib>
only for integers
Absolute fabs(x) <cmath>
for doubles
Floor floor(x) <cmath>
Name Syntax Header and Explanation/
Comment
Ceiling ceil(x) <cmath>
Round off round(x) <cmath>
Trig sin(x) <cmath>
cos(x) x is defined in radians
tan(x)
asin(x)
acos(x)
atan(x)
e exp(x) //ex <cmath>
log(x) // ln(x)
Predefined String, CString, and Character Functions
Header and Explanation/
Name Syntax
Comment
stringName.length(); <string>
String length
stringName.size(); Gives length of string
<string>
Return string character stringName.at(x); Returns character at position x of
string (1st character at pos. 0)
<string>
Character in string stringName[x] Allows you to work with xth
character in string
<string>
Searches str for expression
str.find(strExp); strExp. Will return position in
string of first character. Returns
n::pos if unsuccessful
Find
<string>
Searches str for expression
str.find(strExp, pos) strExp from character position,
pos. Will return position in string
of first character
<string>
Returns substring of str between
Substring str.substr(startPos, length)
two integers (startPos and
startPos+length)
<string>
Swop str1.swap(str2) Contents of str1 and str2 are
swapped
Header and Explanation/
Name Syntax
Comment
<string>
Puts the character ch at the end
Push back str.push_back(ch);
of string (and incr. string length
by 1)
<string>
From position x in string, the next
str.erase(x,y);
y characters will be deleted (incl.
Erase character x)
<string>
str.erase()
Removes all characters from str
<string>
str.insert(m,n,c) Insert n occurences of character
c into str from index m in string
Insert
<string>
str1.insert(m, str2) Insert str2 into str1 from index m
of str1
Test: letter/digit isalnum(ch) <cctype>
Test: letter isalpha(ch) <cctype>
Test: blank or tab isblank(ch) <cctype>
Test: digit isdigit(ch) <cctype>
Test: lowercase letter islower(ch) <cctype>
Test: uppercase letter isupper(ch) <cctype>
Test: whitespace (space, tab,
isspace(ch) <cctype>
vertical tab, return, newline)
Return lowercase tolower(ch) <cctype>
Return uppercase toupper(ch) <cctype>
<string>
Convert str.c-str() Converts a string to a cstring
(null-terminated character array)
String length (cstring) strlen(cStr) <cstring>
<cString>
String copy strcpy(cStr1, cStr2) Copies character array, cStr2,
into character array, cStr1
<cstring>
Concatenation strcat(cStr1, cStr2)
Adds cStr2 to the end of cStr1