Your First C++ Program
#include <iostream>
using namespace std;
int main(){
cout << "Hello World" << endl;
return 0;
}
Running your programs
You can use one of the many online IDEs to run your programs directly from your browser.
However, I recommend having a compiler installed locally (I'll be using
g++
) and getting familiar with an editor/IDE of your choice (I'll be using VSCode). Typically I would keep the input in a file called
in.txt
and the expected output in a file called out.txt
. If the program is in
filename.cpp
, then I will typically run the following commands from a terminal:g++ filename.cpp -O2 -o run; ./run < in.txt > myout.txt; diff out.txt myout.txt
This has the effect of:
- Compiling the program into the executable
run
.
- Feeding the executable with the input from
in.txt.
- Writing the output of the program into the file
myout.txt
.
- Comparing the contents of
myout.txt
without.txt
.
- If the terminal shows no output, then 😎 — the program worked exactly as expected, at least on this particular input file. Otherwise, it's debugging time! 🧐
When still fleshing out a solution we might just want to run the following:
g++ filename.cpp -O2 -o run; ./run < in.txt
This will have the effect of:
- Compiling the program into the executable
run
.
- Feeding the executable with the input from
in.txt
.
- Writing the output of the program to the console for visible examination.
Yet another way of achieving the effect above is to include the following in your program itself, which redirects the standard input output streams to the files specified below.
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("myout.txt", "w", stdout);
#endif
The preprocessing directive
ifndef ONLINE_JUDGE
is used so as to avoid this redirection in your program when it is being compiled by an online judge.Variables
- Variables are declared to reserve some memory, typically with the intention of storing some data.
- The value that a variable has can change (hence the notion of a variable, as opposed to, say, a constant).
- Variables can be assigned values at the time declaration already but this is not mandatory.
- If a variable is declared but not assigned, it will typically hold some meaningless values.
- Syntax: <type> <variable name> = <value>;
- Variable names: alphanumeric and underscores (no spaces; cannot start with a digit) that are not keywords
Keywords are words reserved by the C++ compiler (words like
main
, if
, etc), and that have a special assigned meaning in the language. Typically, in an IDE that supports syntax highlighting, you will see keywords getting a special color. 🤩int a = 40;
bool b = true;
char c = 'c';
Data types
- Determines what type of data is stored by the variable.
- The amount of memory allocated to a variable is determined by its type.
- Unlike Python, in C++ you do need to explicitly indicate the type of a variable at the time of declaration.
- Some common data types in C++ are:
- int and friends (long, short, signed, unsigned, etc.)
- float, double, and friends (e.g, long)
- bool (true or false)
- char
- Can use
sizeof()
to determine the number of bytes of memory allocated by your compiler to a particular datatype.
- Can use constants like
INT_MAX
to determine the largest integer that be stored by anint
variable.
#include <iostream>
using namespace std;
int main(){
int n = INT_MAX;
cout << n << " " << sizeof(n);
return 0;
}
- Note that if you have an
int
variablen
that stores a value larger thanINT_MAX
, then the actual value shown will be a garbage value (very likely a negative number). Try it out!
This is a common source of issues in problems that involve large numbers. Watch out for the types!
- More on types at this reference.
Operators
- Math operations (addition, division, etc.)
Watch out for precedence! Use parentheses liberally to priortize order of operations.
- Comparators (less than, greater than, etc.)
- Don't mix up equality (
==
) with assignment (=
).
- Logical (AND, OR, etc.)
- Note: C++ specifies
and
as an alternative spelling for&&
andor
as an alterative spelling for||
. - Remember to not get confused between the bitwise versions of these operators.
Note on how and is evaluated (from these docs):
The first operand is completely evaluated and all side effects are completed before evaluation of the logical AND expression continues.
The second operand is evaluated only if the first operand evaluates to true (nonzero). This evaluation eliminates needless evaluation of the second operand when the logical AND expression is false. You can use this short-circuit evaluation to prevent null-pointer dereferencing, as shown in the following example:
char *pch = 0;
// ...
(pch) && (*pch = 'a');
// If pch is null (0), the right side of the expression is never evaluated. This short-circuit evaluation makes the assignment through a null pointer impossible.
Can you think of other interesting use-cases for this type of short-circuiting?
- Bitwise (e.g, XOR)
- Use
&
,|
, and^
for bitwise AND, OR, and XOR, respectively. - The operators
>>
and<<
are rightshift and leftshift operators respectively. - Find out more about bit shifts here (Wikipedia) and here (C++ Docs).
Eg:
1 << x
is 2^x
(provided x is reasonably small - how small?)- Assignment (the
=
operator)
- Other (some unary, binary, and ternary operators)
y = x++
first assigns the value of x to y and then increments it; whiley = ++x
first increments x and then assigns the value to y.
Conditionals
- if and else
Which method is a more efficient way of checking if a number is even or odd?
int x;
cin << x;
if(x % 2 == 0) {
cout << "EVEN";
} else {
cout << "ODD";
}
int x;
cin << x;
if(x & 1) {
cout << "EVEN";
} else {
cout << "ODD";
}
- if and else if
int x;
cin << x;
if(x % 3 == 0) {
cout << "DIVISIBLE BY 3";
} else if (x % 3 == 1) {
cout << "OF THE FORM 3X + 1";
} else{
cout << "OF THE FORM 3X + 2";
}
- switch
- More succinct way of doing a sequence of if/else-if type of conditionals.
Loops
- for
- General syntax:
for(initalize, terminating-condition, incrementor) { LOOP BODY }
- Example
// Printing a list of space-separated numbers from 0 to 9
for(int i = 0; i < 10; i++){
cout << i << " ";
}
- while
- General syntax:
while(terminating-condition) { LOOP BODY }
- Example
int i = 1, ans = 0, a = 3, b = 7;
// Calculating a*b
while(i <= b){
ans = ans + a;
i++;
}
cout << ans;
- do-while
- General syntax:
do{ LOOP BODY } while(terminating-condition)
. - Similar to while except that the loop executes at least once irrespective of the terminating condition.
- for-each
- TBA