Physics Forums Insights
  • Physics
    • Physics Articles
    • Physics Tutorials
    • Physics Guides
    • Physics FAQs
  • Math
    • Math Articles
    • Math Tutorials
    • Math Guides
    • Math FAQs
  • Bio/Chem/Tech
    • Bio/Chem Articles
    • Computer Science Tutorials
    • Technology Guides
  • Education
    • Education Articles
    • Education Guides
  • Interviews
  • Quizzes
  • Forums
  • Click to open the search input field Click to open the search input field Search
  • Menu Menu
c++ guide for beginners

Beginner C++ Tutorial — Compiler, Types & I/O Basics

January 2, 2020/0 Comments/in Computer Science Tutorials/by David Duardo
📖Read Time: 8 minutes
📊Readability: Accessible (Clear & approachable)
🔖Core Topics: intcoutendlhellooutput

Table of Contents

  • Contents
  • 1. Getting a C++ Compiler and Compiling Your First Program
    • Getting a C++ Compiler
      • Windows (Dev-C++)
      • Linux (GCC / KDevelop)
      • Mac (Xcode)
    • Compiling Your First Program
      • Dev-C++ Users
      • GCC (command line) Users
      • KDevelop Users
  • 2. Simple Datatypes and Declarations
    • Datatypes
      • Bits and Bytes
      • Qualifiers
    • Variable Declarations
      • Variable Naming Rules
      • Initialization and Multiple Declarations
      • Assignment 1
  • 3. Operators and Expressions
    • Overview
    • Common operators
      • Type casting example
      • Assignment 2
  • 4. Input and Output (I/O)
    • Output (cout)
      • Output Manipulators
    • Input (cin)
      • Assignments 3
  • 5. Selection Statements
    • If Statement
    • Switch Statement
    • Conditional (ternary) Operator
      • Assignment 4
  • 6. Iterative Statements
    • While Loop
    • Do-While Loop
    • For Loop
      • Assignment 5
  • 7. Arrays
    • 7. Arrays
      • Array Initialization
      • Assignment 6
  • 8. Functions
    • Function Format
    • Return Type
    • Parameter Passing
      • Assignment 7
    • More Related Articles

Contents

  1. Getting a C++ Compiler and Compiling Your First Program
  2. Simple Datatypes and Declarations
  3. Operators and Expressions
  4. Input and Output (I/O)
  5. Selection Statements
  6. Iterative Statements
  7. Arrays
  8. Functions

1. Getting a C++ Compiler and Compiling Your First Program

Getting a C++ Compiler

Windows (Dev-C++)

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.

Linux (GCC / KDevelop)

For Linux users, GCC is usually installed by default. If you want an IDE, KDevelop is a good option:

http://www.kdevelop.org/

Mac (Xcode)

Mac users should use Xcode (available from Apple).

Compiling Your First Program

Dev-C++ Users

Steps:

  1. Open Dev-C++
  2. File → New → Project
  3. Choose “Console Application”
  4. 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

  1. Project → New Project → C++ → Simple Hello World Program
  2. Name the application and provide an author name
  3. Click Next three times, then Finish
  4. 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)

Bits and Bytes

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

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;

Variable Naming Rules

Rules for naming variables (summary):

  1. First character must be a letter or underscore
  2. Must not be a C++ keyword (see keyword list below)
  3. Variables are case-sensitive: a != A
  4. Letters, numbers and underscores are allowed after the first character

Initialization and Multiple Declarations

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:

  • Operator precedence (programmershelp)
  • C++ operators (St. Mary’s)

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.14

Assignment 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:

  1. Insertion operator: <<
  2. Manipulators (formatting)
  3. Values to output

Output Manipulators

Common manipulators from <iostream> and <iomanip>:

  • endl – newline and flush
  • dec, 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

  1. Write a program that calculates and outputs the hypotenuse using the Pythagorean theorem from user-provided legs. Output should show 3 decimal places.
  2. Write a program that calculates the area of a triangle from base and height provided by the user. Output should show 5 decimal places.
  3. 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:

  1. First input is a number with at least three digits
  2. Second input is a character between ‘A’ and ‘Q’
  3. 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:

  1. Calculate Pascal’s triangle — user enters number of rows. (http://mathworld.wolfram.com/PascalsTriangle.html)
  2. Calculate the Fibonacci sequence — user enters the number of terms. (http://mathworld.wolfram.com/FibonacciNumber.html)
  3. Average a user-specified list of numbers

7. Arrays

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];

Array Initialization

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.

Function Format

Format:

<return_type> <function_name>(<parameter_list>) { ... }

Return Type

The return type indicates the value returned. Use void if no value is returned.

Parameter Passing

Parameter passing:

  1. Pass by value: a copy of the data is passed (e.g., void f(int x))
  2. 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.

Discussion Thread

David Duardo

Self Proclaimed Computer Geek | Programming | Technology Mentor

More Related Articles

  • All About the Einstein Field Equations
    Tags: programming
    Share this entry
    • Share on Facebook
    • Share on X
    • Share on WhatsApp
    • Share on LinkedIn
    • Share on Reddit
    • Share by Mail
    https://www.physicsforums.com/insights/wp-content/uploads/2020/03/c-guide-beginners.png 135 240 David Duardo https://www.physicsforums.com/insights/wp-content/uploads/2019/02/Physics_Forums_Insights_logo.png David Duardo2020-01-02 10:42:552026-02-17 07:17:46Beginner C++ Tutorial — Compiler, Types & I/O Basics
    You might also like
    programming gpu CUDA Regression Line: GPU Parallel Programming Guide
    AVX-512 conclusion AVX-512 Assembly Programming: Opmask Registers for Conditional Arithmetic Conclusion
    recursion in programming Recursion in Programming and When to Use or Not to Use It
    AVX-512 registers AVX-512 Assembly Programming: Opmask Registers for Conditional Arithmetic
    setup raspberry pi cluster Raspberry Pi Cluster Guide: Parts, MPI & Slurm Tips
    qualitycontrol Hardware, Software, and C Programming Quality Tips
    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply Cancel reply

    You must be logged in to post a comment.

    Trending Articles

    • Explosion-Generated Collapsing Vacuum Bubbles Reach 20,000 Kelvin
    • Explore Some Sins in Physics Didactics
    • It’s Elemental! The Periodic Table Quiz
    • Do Black Holes Really Exist?
    • Grab Bag Science Quiz and Trivia

    Physics Forums

    • Classical Physics
    • Atomic and Condensed Matter
    • Quantum Physics
    • Special and General Relativity
    • Beyond the Standard Model
    • High Energy, Nuclear, Particle Physics
    • Astronomy and Astrophysics
    • Cosmology
    • Other Physics Topics

    Receive Insights Articles to Your Inbox

    Enter your email address:

    Blog Information

    • Become a Member!
    • Write for Us!
    • Table of Contents
    • Blog Author List

    Popular Topics

    astronomy (17) black holes (17) classical physics (35) cosmology (16) education (23) electromagnetism (19) general relativity (19) gravity (24) interview (21) mathematics (39) mathematics self-study (21) Physicist (26) programming (18) Quantum Field Theory (31) quantum mechanics (36) quantum physics (24) relativity (40) Special Relativity (16) technology (19) universe (21)
    2026 © Physics Forums, ALL RIGHTS RESERVED - Contact Us - Privacy Policy - About PF Insights
    • Link to X
    • Link to Facebook
    • Link to LinkedIn
    • Link to Youtube
    Link to: Video Analysis of Spheres Falling Through Two Liquids Link to: Video Analysis of Spheres Falling Through Two Liquids Video Analysis of Spheres Falling Through Two Liquidsfluid dynamics experimentLink to: Why We Don’t Discuss Perpetual Motion Machines (PMM) Link to: Why We Don’t Discuss Perpetual Motion Machines (PMM) perpetual motion machinesWhy We Don’t Discuss Perpetual Motion Machines (PMM)
    Scroll to top Scroll to top Scroll to top