Beginner C++ Tutorial — Compiler, Types & I/O Basics
Table of Contents
Contents
- Getting a C++ Compiler and Compiling Your First Program
- Simple Datatypes and Declarations
- Operators and Expressions
- Input and Output (I/O)
- Selection Statements
- Iterative Statements
- Arrays
- Functions
1. Getting a C++ Compiler and Compiling Your First Program
Getting a C++ Compiler
For Windows users, especially beginners, I suggest using an integrated development environment (IDE). An IDE gives you syntax highlighting, debugging and compiling all in one package. For these tutorials I suggest Bloodshed Dev-C++ (GCC-based and free):
http://www.bloodshed.net/devcpp.html
If you prefer a different IDE or compiler that’s fine, but it will be easier if everyone on Windows uses the same environment for consistency. Microsoft’s Visual Studio and other compilers also work.
For Linux users, GCC is usually installed by default. If you want an IDE, KDevelop is a good option:
Mac users should use Xcode (available from Apple).
Compiling Your First Program
Dev-C++ Users
Steps:
- Open Dev-C++
- File → New → Project
- Choose “Console Application”
- Give the project a name and save it
Dev-C++ creates a project and a basic C++ file appears. Before the line that says system("Pause"), add:
cout << "Hello World\n";Save, then choose Execute → Compile & Run. If successful, a console will pop up and display “Hello World”.
GCC (command line) Users
Open your text editor and type the following program:
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
cout << "Hello World\n";
return 0;
}Save as program1.cpp. In a terminal, run:
g++ program1.cpp
Then run the produced executable:
./a.out
You should see “Hello World”. If your system names the compiler differently, try CC or gcc.
KDevelop Users
- Project → New Project → C++ → Simple Hello World Program
- Name the application and provide an author name
- Click Next three times, then Finish
- Build → Execute Program (confirm any dialogs)
When compiling finishes a window should display “Hello World!”
2. Simple Datatypes and Declarations
Datatypes
Imagine moving across the country: if you choose the wrong truck the contents may spoil. In C++ you must choose the correct storage type (datatype) for the data you store.
Common simple datatypes:
- int – integer (typically 4 bytes) – examples: 3, 10, -123
- char – character (1 byte) – examples: ‘a’, ‘%’, ‘T’
- float – single-precision floating-point (typically 4 bytes) – examples: 2.3f, -2.3f
- double – double-precision floating-point (typically 8 bytes) – more precision than float
- bool – boolean (true/false)
Use the correct type: floating-point values stored in an int will be truncated; storing a double in a float can lose precision.
Basic explanation of bits/bytes:
Computers use binary (base 2). A single binary digit is a bit. 8 bits = 1 byte. To estimate how many bits are needed to store a positive integer N:
log(N)/log(2) = number of bits (always round up)
Example: For N = 15, log(15)/log(2) ≈ 3.9 → need 4 bits. To get bytes, divide bits by 8 and round up.
Qualifiers (modify base datatypes):
- short – typically reduces integer size (e.g., short int)
- long – typically increases integer size on many platforms (exact size is platform-dependent)
- signed – allows negative values (default for integers)
- unsigned – only non-negative values
- const – value cannot be changed after initialization
Qualifiers can be combined: e.g., long long int, unsigned short int.
Variable Declarations
A variable is a named storage location. In C++ you must declare a variable’s type before using it.
Declaration format:
<qualifier(s)> <datatype> <variable_name>;
Examples:
unsigned int counter;double money;char letter;const double pi = 3.14159;
Rules for naming variables (summary):
- First character must be a letter or underscore
- Must not be a C++ keyword (see keyword list below)
- Variables are case-sensitive:
a!=A - Letters, numbers and underscores are allowed after the first character
Multiple declarations of the same type:
int counter1, counter2, counter3;
Initialization examples:
int a = 1;unsigned char b = 'c';double c = 2.4, d = 4.2, e = 2.7;
Assignment 1
Create a new C++ project and type:
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
char myCharacter = 'z';
cout << "The datatype int occupies " << sizeof(int) << " bytes!" << endl;
cout << "The variable has a value of " << myCharacter << endl;
return 0;
}Compile and run. Change variable declarations and try different qualifiers inside sizeof(). Find the size (in bytes) of long long int, unsigned short int, and unsigned long.
Reference link used in the text: https://www.physicsforums.com/showthread.php?t=32599
Keywords:
asm, auto, break, case, catch, char, class, const, continue, default, delete, do, double, else, enum, extern, float, for, friend, goto, if, inline, int, long, new, operator, private, protected, public, register, return, short, signed, sizeof, static, struct, switch, template, this, throw, try, typedef, union, unsigned, virtual, void, volatile, while
3. Operators and Expressions
Overview
As in mathematics, the result of an expression depends on operator precedence and associativity. Below are common operators beginners use. (Operator reference links are provided by external sites.)
Reference examples:
Common operators
- Addition:
+ - Subtraction:
- - Multiplication:
* - Division:
/ - Greater than:
> - Less than:
< - Greater than or equal:
>= - Less than or equal:
<= - Modulus (remainder):
%— e.g.,50 % 7 == 1 - Logical not:
!— e.g.,!true == false - Prefix increment:
++x(increments before use) - Postfix increment:
x++(increments after use) - Prefix decrement:
--x - Postfix decrement:
x-- - Pointer (indirection):
*(declares or dereferences pointers) - Address-of:
&(gives a variable’s address) - Type cast:
(datatype)— e.g.,y = (int)x; - Dynamic allocation:
new(reserve memory) - Deallocation:
delete(free memory) - Sizeof operator:
sizeof(returns bytes occupied) - Equality:
==(comparison; do not confuse with assignment=) - Logical AND:
&& - Logical OR:
|| - Ternary conditional:
?:— format:condition ? true_expr : false_expr; - Assignment operators:
=, +=, -=, *=, /=, %= - Comma operator:
,(separates expressions)
Type casting example
int y;
float x = 3.14f;
y = (int)x; // y becomes 3; x remains 3.14Assignment 2
Create a new C++ project and type the following program, then compile and experiment with it:
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int x = 1, y = 3, z = 4;
int *num;
const float pi = 3.14f;
z *= y;
y = x + (int)pi;
num = &y;
if (++z <= y--) {
cout << "Z: " << z << " <= Y: " << y << endl;
} else {
cout << "Z: " << z << " > Y: " << y << endl;
}
cout << "Z: " << z << endl;
cout << "Y: " << y << endl;
cout << "The base memory address of Y: " << num << endl;
cout << "The value pointed to by num: " << *num << endl;
return 0;
}Compile and run, then modify and observe changes. Experimentation helps you learn.
4. Input and Output (I/O)
Output (cout)
Use cout to print to the screen. A typical output statement looks like:
cout << <items...> << endl;
The main components:
- Insertion operator:
<< - Manipulators (formatting)
- Values to output
Common manipulators from <iostream> and <iomanip>:
endl– newline and flushdec,hex,oct– integer bases- From <iomanip>:
setw(n),setfill(c),left,right,showpos,noshowpos,boolalpha,noboolalpha,scientific,fixed,setprecision(n)
Examples (quotes show whitespace):
Statement: cout << "Hello World" << endl;
Output: “Hello World\n”
Statement: cout << "P" << "R" << "O" << "G" << "R" << "A" << "M" << endl;
Output: “PROGRAM\n”
Statement: cout << setw(10) << setfill('/') << setprecision(2) << 3.141;
Output: e.g. “//////3.14”
Statement: cout << "Harry" << endl << "Potter";
Output: “Harry\nPotter”
Input (cin)
Use cin to read user input. The extraction operator is >>.
Example:
int a, b, c;
cout << "Enter NUM1, NUM2, and NUM3" << endl;
cin >> a >> b >> c;
cout << "NUM1: " << a << endl;
cout << "NUM2: " << b << endl;
cout << "NUM3: " << c << endl;Note: Default behavior of formatted input skips whitespace (skipws). To change that behavior use noskipws from <iomanip> if needed.
Assignments 3
- Write a program that calculates and outputs the hypotenuse using the Pythagorean theorem from user-provided legs. Output should show 3 decimal places.
- Write a program that calculates the area of a triangle from base and height provided by the user. Output should show 5 decimal places.
- Write a program that computes the distance between two points in space and displays the result in scientific notation.
Note: Do not use ^ for exponentiation; that operator is bitwise XOR in C++. Multiply the number by itself instead, or use the pow() function from <cmath>.
5. Selection Statements
If Statement
Conditional statements execute code only when a condition is met.
Basic forms:
- Simple if:
if (condition) { statements; } - If-else:
if (condition) { statements; } else { statements; } - Nested/else-if:
if (cond1) { } else if (cond2) { } else { }
Example program that checks even/odd:
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int number;
cout << "Enter an Integer: ";
cin >> number;
if (number % 2 == 0) {
cout << number << " is even." << endl;
} else {
cout << number << " is odd." << endl;
}
return 0;
}Switch Statement
Use switch for menu-style selection when testing an integer or single character.
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int number;
cout << "1. Print Hello World\n";
cout << "2. Print Physics Forums\n";
cout << "3. Print C++\n";
cin >> number;
switch (number) {
case 1:
cout << "Hello World" << endl;
break;
case 2:
cout << "Physics Forums" << endl;
break;
case 3:
cout << "C++" << endl;
break;
default:
cout << "Input Error" << endl;
break;
}
return 0;
}Note: Omitting break causes execution to fall through to subsequent cases until a break is encountered.
Conditional (ternary) Operator
Shorthand for simple if-else:
result = (expression) ? value_if_true : value_if_false;
Example: time = (1 < 2) ? 6 : 7;
Assignment 4
Write a program that checks three inputs meet the following criteria:
- First input is a number with at least three digits
- Second input is a character between ‘A’ and ‘Q’
- Third input is divisible by 3
6. Iterative Statements
While Loop
Syntax:
while (condition) { statements; }
Example:
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
int x = 0;
while (x < 2) {
cout << "HELLO" << endl;
x++;
}
return 0;
}Output:
HELLO
HELLO
Do-While Loop
Syntax:
do { statements; } while (condition);
Example:
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
int x = 0;
do {
cout << "HELLO" << endl;
x++;
} while (x < 2);
return 0;
}Output:
HELLO
HELLO
For Loop
Syntax:
for (initialization; condition; update) { statements; }
Example:
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
for (int x = 0; x < 2; x++) {
cout << "HELLO" << endl;
}
return 0;
}Output:
HELLO
HELLO
Assignment 5
Create a menu-driven system (looping menu) that can:
- Calculate Pascal’s triangle — user enters number of rows. (http://mathworld.wolfram.com/PascalsTriangle.html)
- Calculate the Fibonacci sequence — user enters the number of terms. (http://mathworld.wolfram.com/FibonacciNumber.html)
- Average a user-specified list of numbers
7. Arrays
An array is a contiguous collection of elements. Declaration form:
<datatype> <name>[size];
Examples:
- 1D:
int myarray[3]; - 2D:
int myarray[3][4]; - 3D:
int myarray[3][3][7];
You can initialize arrays at declaration:
int myarray[3] = {1, 2, 5};
int myarray[3][2] = {{1,2}, {3,5}, {6,3}};
Array indices start at 0 and go to size - 1. Example to input a 2×2 matrix and compute its determinant (fixed loop bug):
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
int myarray[2][2];
cout << "Determinant Finder:" << endl;
cout << "Enter Matrix in the following format: X11 X12 X21 X22" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cin >> myarray[i][j];
}
}
cout << myarray[0][0] * myarray[1][1] - myarray[1][0] * myarray[0][1] << endl;
return 0;
}Input: 1 2 3 4 Output: -2
Assignment 6
Create a program to solve two simultaneous linear equations:
Ax + By = C
Dx + Ey = F
8. Functions
Functions allow encapsulation of repeated or modular code. You have already used the special main function.
Format:
<return_type> <function_name>(<parameter_list>) { ... }
The return type indicates the value returned. Use void if no value is returned.
Parameter passing:
- Pass by value: a copy of the data is passed (e.g.,
void f(int x)) - Pass by reference: the address is passed (e.g.,
void f(int &x)) — often more efficient for large objects
Example function that computes area and is used in main:
#include <iostream>
using namespace std;
double rectangle_area(double length, double width) {
return length * width;
}
int main(int argc, char **argv) {
double L, W;
while (true) {
cout << "Enter Length and Width (L=0 or W=0 to quit):" << endl;
cin >> L >> W;
if (L == 0 || W == 0) break;
else cout << "Area: " << rectangle_area(L, W) << endl;
}
return 0;
}Assignment 7
Use the concepts learned to build a text-adventure game using functions for rooms, inventory, and game logic.
Self Proclaimed Computer Geek | Programming | Technology Mentor










Leave a Reply
Want to join the discussion?Feel free to contribute!