Introduction to C++ Programming


C++ Programming Overview for Beginners

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 : are mechanisms that control the flow of the program.It may contains loops like for, while and conditionals such as if, else
  2. Functions: are reusable blocks of code that perform a specific task.
  3. Objects and Classes: are structures that represent data and behaviors in object oriented programming languages.
  4. Arrays and Lists: are collections of data items, which can be indexed.
  5. Exceptions or Errors :are mechanisms used for handling problems in the program.

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

Basic elements:are the fundamental components of a program and are the smallest units that are essential for writing any program and operate at the syntax level.

Example :int, return, if, while

Variables: are named storage locations that hold data like int x = 5; of a system and exposing only the necessary parts to make programming more easier.

Statements: are instructions that can perform actions, like variable assignments, loops, and conditionals

Identifier: is a name given for any program element,such as function,variable,structure, class, or other user-defined item in a program. The purpose of an identifier is to assign a distinct name to an object.Identifier may be written with underscores, characters, and numbers in both uppercase and lowercase.

Note :all identifiers may not be variables.

Literals : are values such as numbers,characters,or string whose values are self-evident.

  1. Integer literals → is a literal number with a fixed point. integer literals come in decimal,octal,or hexadecimal notation.
    • Decimal: is normal representation → Example:10
    • Octal integer literals that begin with 0(zero) →Example:012
    • Hexadecimal integer literal that begins with either 0x or 0X // Example:0xA, after grouped into 4 digits
    • Floating point literals: either a decimal point or an exponent expressed in scientific notation.
  2. Characters literals: are characters enclosed within single quotes is a literal of type char.
  3. String literals: are zero or more characters enclosed in double quotation marks. It is an array of constant chars.

Note:Every string literal is appended by the compiler with a null character ('\0')at the end.So, the size of string literal is one more than the actual size.

Example "abc" → 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:

  1. const keyword: in this method, we include the const keyword in the variable definition.
    Syntaxconst 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 but,const int id; id = 30; ← display error
  2. constexpr Keyword constants are initialized at compiler time. constexpr keyword is compatible for MinGW GCC(GNU compiler collection) compiler type;
    Syntax constexpr DATATYPE variable name = value;
    Example constexpr int hours =24; // ok
  3. #define preprocessor constants that are created using #define preprocessor are called macro constants. It is less preferable way to define a constant in C++ due to 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.

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 simly variable declarations and defines a certain domain of values and operations such as additions,substraction,etc.

Data types can be

  • Primitive Data types: built in data types that store simple value.
    Example int,char,float,double, signed int, unsigned int,etc
    int a =80; ← create a new variable "a" and assign the value on it
  • Non primitive data types are reference data types. Because, it references a memory location where data is stored.
    Example String,Arrays,classes.
    ← create a new variable b and assign the address of "world" to it.

Expression is a list of operators followed by their operands.Statements can't always be expressions, but all expressions can be statements.

We can categorize expressions into three types,such as relational, logical, and arithmetic expressions

  1. Arithmetic expression: employs arithmetic operators such as addition, multiplication, subtraction, division, etc.
  2. Relational expression:that uses relational operators.
  3. Less than,greater than, less than or equal to,greater than or equal to are some operators.
  4. Logical expression:is an expression that makes use of logical operators.AND (&&),OR (||),and NOT(!) are a few examples.

Statement It can be thought as an instruction that the program executes. It can be as simple as a variable declaration or as complex as a loop or conditional block. C++ statements are executed sequentially, one after the other, unless altered by control structures like loops, conditionals, or function calls.

Few statement types

  • Expression Statement: type of statement that evaluates an expression, usually performing some kind of computation or assignment
    Example y =4; ← assignment statement
  • Declaration Statement :declares a variable or a constant
    Example data_type variable_name; ←int age
  • Control flow statement:used to alter the flow of execution based on certain conditions or loops.common control flow statements are:
    if, else, for, while, do-while
  • Jump statements: alter the flow of control in a program by jumping to a different part of the program. break,continue,and return are examples
  • Compound statement: is a group of statements enclosed in curly braces {}. It is used to group multiple statements together where a single statement is expected, such as inside functions or control structures.
    Example { int x = 16; x += 5; }
  • Function Call Statement: used to call a given function.
    Example add();
  • Empty Statement is an empty statement is just a semicolon (;) with no other code. It does nothing.
    Example for(int i=0;i<4;i++);
  • Switch Statement: used for multi-way branching based on the value of an expression. Example 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 :are operators such as Addition, multiplication,subtraction,and division on the operands are carried out.
  • Relational operators :operators that are used to compare the values of two operands. Less than, greater than are examples.
  • Logical operators: operators that combine two or more conditions. AND,OR,NOT are examples
  • Assignment operators: operators that are used to assign a value to a variable. The operand of the assignment operator is a value on the right side of the operator, and a variable on the left.
  • Bitwise operators :operators that operate at the bit level on the operands In bitwise operators, operands are calculated after the operators have first been converted to bit level.
    Example AND(&),OR(|),XOR(^),COMPLEMENT(~ tild sign),LEFT SHIFT(<<),and RIGHT SHIFT(>>).
  • Control statements: are statements that reroute a program to allow for the execution of additional code. Conditionals 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.

Generally,we can inter rellate the above concepts with the following simple 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
    bool r = a > b; ← Relational
    final = a = b; ← Assignment
    final = a & b; ← Bitwise AND
    return 0;
}


Yilma Goshime

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

LetUsLearn