Introduction to C++ Programming


What is Computer Program?


A computer program is a set of instructions that tells a computer what tasks to perform. We use programs to interact with and control computers.

On the other hand, computer programming is the process of creating those programs. It involves writing code using a text editor and a chosen programming language to develop software that performs specific tasks or solves problems.

Programming language is a formal system used to communicate instructions to a computer. It comprises a set of rules, symbols, and syntax that enables programmers to write code the computer can understand and execute. Programming languages are essential for developing software applications, websites, games, operating systems, and various other digital solutions.

Building blocks of a program are the essential structures and elements that form the foundation of any computer program. They are the core concepts that programmers rely on when designing, writing, and organizing code.

Building blocks of a program can be:

  1. Control Structures : within a program, control structures are programming components that dictate the direction of execution flow. Based on criteria or recurring events, they enable developers to specify how and when particular code blocks should be run.
  2. These structures typically include

    Conditional Statements

    Conditional statements are used to control the flow of execution. They allow certain blocks of code to run only when specified conditions are true. Basic programming constructs like if, if-else, and switch fall under this category and help determine which code executes based on given criteria.

    • You can use an if statement to print a message only if the condition is met.
    • The if-else statement provides an alternate block of code to execute when the condition is false.
    • The switch statement allows checking a variable against multiple values and executing a matching block of code.

    Looping Statements

    Looping statements are essential for repeating a block of code until a certain condition is met or becomes false. This is useful for tasks like processing elements in a collection, doing repeated calculations, or automating repetitive tasks. Common looping structures in C++ include for, while, and do-while loops.

  3. Functions: are strong tools that let you put a collection of instructions under one name and then use that group of instructions repeatedly in your program. Functions aid in the organization, modularity, and manageability of code. Code reusability and redundancy are reduced when you define a function only once and can call it from different sections of your code. Functions in C++ can be defined with a particular name, return type, and optional parameters.
  4. Syntax

    
    return_type function_name(parameters) {
        // Function body
        return value;  // Optional return statement
    }
    
    

    Note

    • return_type: Specifies the type of data (such as int, void, or float) that the function will provide as an output.
    • function_name: The identifier that is used to call or invoke the function.
    • parameters: Optional inputs that the function can accept, which may or may not be provided when calling the function.
    • Function Body: The block of code within the function that performs the desired task or computation.
    • return: If the function is designed to produce a value, it will use the return statement to send the result back.
    Example
    
    #include <iostream>
    using namespace std;
    void introduce(string name) {
        cout << "My Name is: " << name;
    }
    int main() {
        introduce("Yilma"); 
        return 0;
    }
    
    
  5. Objects and Classes: The ideas of classes and objects are central to object-oriented programming, or OOP. They enable you to represent and simulate real-world entities in a reusable and organized manner.
  6. Class

    When constructing things, a class functions similarly to a blueprint or template. It specifies the behaviors and attributes that the objects derived from this class will possess. It is merely a specification of how objects of that class will behave; it does not really take up memory.

    Object

    It is a class instance. You can make objects based on a class once it has been declared. Every object has a unique collection of actual values (or data) for the class-defined attributes that it can use to.
    Example
    
    #include <iostream>
    using namespace std;
    
    class Department {
      public:
        string name;  // Data member
        void Detail() {       // Member function
            cout << "Department Name:" << name;
        }
    };
    
    int main() {
      Department dept;  // dept is an object
      dept.name = "Information Systems";   // Assign values to dept's data member
      dept.Detail();      // Calling 
      return 0;
    }
    
    
  7. Arrays and Lists:are data structures used in C++ is to store several values under a single variable, but their implementation and usage are very different. All of the elements in an array are kept close to one another in memory since arrays are fixed-size, contiguous blocks of memory. This makes it possible to use an index to quickly and consistently access elements.
    However, it is inefficient to shift other components in order to add or remove elements because their size is defined at the time of declaration.
    On the other hand, lists in C++ are implemented as doubly linked lists, notably std::list from the Standard Template Library. Lists provide efficient insertion and deletion at any place since each element is kept independently in memory and connected by pointers.
  8. Example →Array
    
    #include <iostream>
    using namespace std;
    int main() {
        int num[5] = {1,8,2,3,4};  // Fixed-size array
        cout << "First element:" << num[0];  // Outputs 1
        return 0;
    }
    
    
    Example →List
    
    #include <iostream>
    #include <list>
    using namespace std;
    int main() {
        list<int> num = {10, 2, 3};   // Declare and initialize a list of integers
        num.push_back(4);   // Add at the end
        num.push_front(50);   // Add at the beginning
        cout << "elements:";
        for (int value : num) {
            cout << value;
        }
        return 0;
    }
    
    
  9. Exceptions or Error :Unexpected issues that may arise during program execution , and if they are not handled properly, they may result in program crashes or unpredictable behavior. This is where exception handling comes in, as it enables a program to handle these errors gracefully.
    A programming method called exception handling is used to identify and handle errors—also known as exceptions,that arise while a program is running. When something goes wrong, it transfers control to a particular block of code called a catch block, which is intended to address the error, rather than letting the program crash. This method improves the program's dependability and user experience by ensuring that it can either operate continuously or terminate gracefully.

Note: The above building blocks make up the language of programming used to write software.

Basic elements:are the core components of any programming language, defining how a program is structured and how it operates. They are the most minimal and essential units required to create a program. These elements work within the rules of the language’s syntax, meaning they must follow specific formats and conventions.

Examples of basic elements include variables, data types, operators, constants, reserved keywords, and punctuation marks like semicolons,braces and Each of these elements plays a specific role in telling the computer what to do.

Example

#include <iostream>
using namespace std;
int main() {
    int a = 8;       // 'int' is a data type, 'a' is a variable, '=' is an assignment operator
    int b = 9;
    int sum = a + b; // '+' is an arithmetic operator
    cout<<"A: " <<a; // 'cout' is used for output
    return 0;
}

Variables: Variables are designated (named) storage spaces in a computer’s memory that can hold values which may change during the program’s execution.They are fundamental to programming because they allow you to:

  • Store information (like numbers, text, etc.)
  • Retrieve and manipulate that information later
  • Think of a variable like a labeled container where you can place something (a value), take it out, or replace it with something else

Identifier:is the name you assign to components in your software so you can refer to them later in the program. These components include variables, functions, classes, structures, objects, constants, namespaces, and more. The main goal of using identifiers is to provide both the computer and the programmer with a clear, readable, and distinct name for each element in the code. This helps improve understanding, organization, and control throughout the development process.

Note :all identifiers are not variables, even if all variables are identifiers.

Rules of Syntax for Identifiers

  • Able to utilize underscores (_), numbers (0–9), and letters (A–Z, a–z).
  • Not able to begin with a number.
  • Special symbols like @, #, -, +, !, etc., cannot be used.
  • Languages such as C++, Java, and JavaScript are case-sensitive (e.g., score and Score are different).
  • Should not be the same as reserved keywords such as return, class, or int.
Example

#include<iostream>
using namespace std;
struct Person {   // 'Person' is an identifier for a structure
    string name;     // 'name' is an identifier (a member variable)
};
void info(string name) {  // 'info' is an identifier for a function
 cout<<"Name:"<<name;
}
int main() {
    Person p1;  // 'p1' is an identifier for a Person object
    p1.name = "Tom";
    info(p1.name);
    return 0;
}

    

Literals : are fixed values that represent constant data and are written straight into the code. Because their meaning is clear-cut (self-evident) and remains constant while the program is running, they are also referred to as constant values.

Since literals are hardcoded into the program, their values are stated clearly and aren't determined by calculation or other factors. These values stay the same during the program's execution and cannot be changed. Because literals are fixed and direct, their meaning is obvious and self-evident simply by looking at them; no assessment or calculation is necessary.

Integer literals

Whole numbers without any fractional or decimal components. They can be shown in hexadecimal, octal, or decimal notation.
  • Decimal: We utilize this conventional number system (0–9) on a daily basis.
    Example: int x = 1;
  • Octal: Leading 0 (zero) is used at the beginning of octal literals. The only numbers used are 0–7.
    Example: int y = 015;
  • Hexadecimal: Use numbers 0–9 and letters A–F, and start with 0x or 0X.
    Example: int z = 0xB;
  • Floating point literals: Real numbers represented with decimal points or scientific notation.
    Example: double c = 2.5e2;

Character literals

Are of type char and consist of a single character enclosed in single quotes.
Example: char grade = 'C';
Note: Every character literal corresponds to a Unicode or ASCII value. For instance, the ASCII value of 'A' is 65.

String literal

A sequence of one or more characters enclosed in double quotes (" "). Even an empty set of quotes ("") is a valid string literal representing an empty string.
Example: string name = "Yilma";

Note: The compiler automatically adds a null character ('\0') at the end of every string literal. Therefore, the total size of a string literal is always one character larger than the number of visible characters.i.e "abc" is same as "abc\0"

Constants: are variables with unchangeable fixed values. Once they are defined in the program, they are not changed while the program is running and kept in the program's code segment of memory as read-only tokens.Any C++ data type, including int, char, or string is acceptable for constants.

In c++,we can declare Constants in three ways:

const keyword

This method uses the const keyword in the variable definition.
Syntax:const DATATYPE variable_name = value;
A constant variable must be initialized at the time of declaration because its value cannot be changed later in the program.
Example:
const int id = 30; ← OK
const int id; id = 30; ← Error (not allowed)

constexpr keyword

Constants declared with constexpr are initialized at compile time.
The constexpr keyword is compatible with MinGW GCC (GNU Compiler Collection).
Syntax:
constexpr DATATYPE variable_name = value;
Example:
constexpr int hours = 24; ← OK

#define preprocessor

Constants created using the #define preprocessor are called macro constants.
This method is less preferable in C++ due to the lack of type safety.
Syntax:
#define MACRO_name replacement_value
Example:
#define Size 6 ← OK

Keywords:are words with predefined meanings.In most programming languages, keywords are reserved words that developers and programmers cannot use as the names of variables,constants, or functions.

In programming languages, keywords such as int, return, if, for, and class have specific predefined meanings. For instance, if starts a conditional statement, for starts a loop, class defines a class, return returns a value from a function, and int declares an integer variable. Variables, functions, and other identifiers cannot be named using these reserved terms.

Comments :are text notes that provide an explanation about the source code.it serves as a source code documentation and make the program easier to read.

Datatypes: are the type of data it can store, the range of values it can hold. To instruct the computer on how to handle and understand the data stored in a variable, you assign it a datatype when you declare it.Data types assist the compiler or interpreter in deciding what kinds of operations are permitted on the data and allocating the proper amount of memory.

Data types can be

Primitive Data types

These are built-in basic types that store simple, single values. They are not composed of other data types. When declaring variables like characters or numbers, these are the fundamental types.
Example → Primitive data types:
  • Integer numbers like 10 or -3 are stored in the int type.
  • A single character, such as "A" or "z," can be stored in the char type.
  • The double type offers better precision for larger or more precise decimal values, while the float type stores values like 3.14.
  • Boolean values, either true or false, are represented by the bool type and are commonly used in logic and conditionals.

Non-primitive Data types

These do not directly store data values; instead, they hold references (addresses) to memory locations where the actual data is stored. When using a non-primitive variable, you work with the reference, not the value itself.
They support dynamic memory allocation, complex data structures, and object-oriented programming.
Examples: String, Arrays, and Classes are common non-primitive (reference) types.
String b = "world"; ← creates a variable b that holds the address of the string "world".

Expression In programming, an expression is a set of variables, operators, functions, and values that are evaluated to yield a different value. The equation a + b, for instance, evaluates to a single value after the + operator adds the values of a and b.

Three common categories can be used to classify expressions.

Arithmetic expression

These perform mathematical operations such as addition, subtraction, multiplication, and division using arithmetic operators.

Relational expression

These compare two values and return a boolean result of true or false. They are useful for decision-making, such as in if statements.
Operators include: less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=).

Logical expression

These combine multiple relational expressions to form more complex conditions, returning true or false.
Common operators are: AND (&&), OR (||), and NOT (!).

Statement: A statement in C++ is a single instruction that instructs the computer to carry out a certain task. It functions as a program's basic unit of execution.Simple activities like declaring a variable or more intricate ones like loops, conditionals, or function calls can all be done with statements. Statements run in the order they appear by default, unless control flow constructions change this.

Common Types of Statements

Expression Statements

Lines of code that evaluate an expression to perform tasks like computing results, executing functions, or assigning values. They often update the program state.
Example: y = 4; (assignment statement)

Declaration Statement

Defines the data type and identifier of variables or constants, allocating memory and informing the compiler about the data type.
Syntax: data_type variable_name;
Example: int age;

Control Flow Statement

Instructions that alter the sequence of code execution, allowing decisions or repetitions based on conditions:
  • If statement: Executes a block if a condition is true.
  • Else statement: Provides alternative execution if condition is false.
  • For loop: Repeats code a set number of times.
  • While loop: Repeats as long as a condition is true.
  • Do-while loop: Executes at least once, then repeats if condition is true.

Jump Statement

Control flow commands that interrupt normal execution to transfer control elsewhere. Useful for loops, skipping code, or exiting functions.
Examples:
  • break: Exit a loop or switch immediately.
  • continue: Skip to the next loop iteration.
  • return: Exit a function and optionally return a value.

Compound Statement

A group of statements enclosed in curly braces { }, used where a single statement is expected.
Example:
{ int x = 16; x += 5; }

Function Call Statement

Invokes a previously defined function, causing program control to jump to the function and return after execution.
Example: add();

Empty Statement

A semicolon ; by itself that performs no action.
Example: for(int i=0; i<4; i++);

Switch Statement

A control flow structure to execute different code blocks based on the value of a variable or expression. Useful instead of multiple if-else statements.
Syntax:
switch(value) {
case 1: Statement 1; break;
case 2: Statement 2; break;
case 3: Statement 3; break;
}

Operators are unique class of functions that accept one or more parameters and return an altered result. It is a symbol that instructs the compiler to carry out the logical and mathematical operations. Operators in C++ can be

Arithmetic operators: Symbols that perform basic mathematical operations on variables or numbers, such as addition, subtraction, multiplication, and division. Essential for any computational tasks in programs.
Relational operators: Used to compare two values or expressions to determine their relationship. They return true or false and are vital for decision-making in control structures like if, while, and for loops.
Logical operators: Combine or modify multiple conditions to produce a true or false result, helping in complex decision-making.
Common logical operators include:
  • AND (&&): Returns true only if all combined conditions are true.
  • OR (||): Returns true if at least one condition is true.
  • NOT (!): Negates a condition, changing true to false and vice versa.
Assignment operators: Used to assign or update the value of variables. The basic assignment operator is =, but compound operators combine assignment with arithmetic or bitwise operations.
Example: +=, -=, *=, /=, %= combine arithmetic with assignment, while &=, |=, ^=, <<=, >>= combine bitwise operations with assignment. These operators make code concise and efficient.
Bitwise operators: Operate directly on the binary bits of integer operands. Unlike arithmetic operators working on whole numbers, bitwise operators manipulate individual bits, enabling low-level programming tasks like masking, flag setting, and optimization.Operands are first transformed into their binary forms, and then the operator is applied gradually.
AND (&): Applies a bitwise AND operation to each pair of bits. The result bit is 1 only if both bits are 1; otherwise, it's 0.

int a = 2;  // binary:  0010
int b = 3;  // binary:  0011
int c = a & b;  // binary result: 0010 (decimal 2)

    
OR (|): Applies a bitwise OR to each pair of bits. The result bit is 1 if at least one bit is 1; it is 0 only if both bits are 0.

int a = 2;  // binary:  0010
int b = 3;  // binary:  0011
int c = a | b;  // binary result: 0011 (decimal 3)

    
XOR (^): Performs a bitwise exclusive OR. The result bit is 1 if the bits are different, and 0 if they are the same.

int a = 2;  // binary:  0010
int b = 3;  // binary:  0011
int c = a ^ b;  // binary result: 0001 (decimal 1)

  
COMPLEMENT (~): Unary operator that flips all bits of the operand, changing 1s to 0s and 0s to 1s.

int a = 2;  // binary:  0010
int b = ~a;  // binary: 1101 (in 4-bit representation)

    
LEFT SHIFT (<<): Moves the operand's bits a specified number of places to the left. Each shift to the left effectively multiplies the number by two.

int a = 3;      // binary: 0011
int c = a << 1; // binary result after left shift by 1: 0110 (decimal 6)

    
RIGHT SHIFT (>>): Moves the bits a specified number of places to the right. Each right shift effectively divides the integer by two, ignoring any remainder.

int a = 3;       // binary: 0011
int c = a >> 1;  // binary result after right shift by 1: 0001 (decimal 1)

    
  • Control statements: are statements that reroute a program to allow for the execution of additional code.conditionals such as if-else, switch and loops for, while, do-while are examples.

  • Flow control statements :are called jump statements which are used to change how the program runs. It is used to halt the execution of a function or to end or resume a loop within a program. break, continue, goto, and return are some examples.
    Flow control statements are especially helpful for:
    • Break out of a loop early
    • In a loop, skip the current iteration.
    • Go to a particular section of the code.
    • Leave a function and give back a value.

    In general, the concepts discussed above,demonstrated together using the following simple example.

    Example
    
    #include <iostream>
    using namespace std;
    const int Value = 100;  // const keyword
    constexpr int HOURS = 24;  // constexpr keyword
    #define Size 5   // #define macro constant
    void showMessage() {    //Function definition
        cout <<"Hello";
    }
    int main() {
    	showMessage();  //Function call
        char sex = 'M'; //identifier
        string studentName = "John";   // non-primitive identifier
        int a = 10;   //Decimal integer literal
        int b = 012; //Octal literal (starts with 0)
        int c = 0xA;   //Hexadecimal literal (starts with 0x)
        float d = 12.5; // Floating-point literal
        char e = 'b'; //Character literal
        string f = "Hello"; //String literal, implicitly ends with '\0'
        const int age = 30;    // Must be initialized at declaration
        int total = a + b; //Arithmetic expression
        bool isValid = score > 50; // Relational expression
        if (score >= 50) { //Control flow statement
            cout << "valid";
        } else {
            cout <<"Try again.";
        }
        for (int i = 0; i < 5; i++) {  // Jump statement
            if (i == 3) continue;  // Skip when i is 3
            cout << "i = " << i;
        }
        for (int i = 0; i < 3; i++);  // Empty statement
        int num = 2;
        switch (num) {                // Switch statement
            case 1:
                cout << "Number 1";
                break;
            case 2:
                cout <<"Number 2";
                break;
            default:
                cout << "Another number";
                break;
        }
        int a = 5, b = 3;
        int final;
        final = a + b;    //arithmetic operator
        bool r = a > b;   //relational operator
        final = a = b;   //assignment operator
        final = a & b; //Bitwise AND operator
        return 0;
    }
    
        
    ← Previous Post File Handling in C++
    Next Post → OOP in C++ Tutorial
    Yilma Goshime

    I’m committed to providing tailored solutions and always ready to assist if any issue arises.

    LetUsLearn
    Back to Top