HSSLIVE Plus One Computer Science Chapter 5: Introduction to C++ Programming Notes

C++ represents a powerful, widely-used programming language that balances efficiency with abstraction capabilities. This chapter introduces the fundamentals of C++ programming, including program structure, basic syntax, and the compilation process that transforms source code into executable programs. It covers essential programming concepts such as identifiers, keywords, comments, and basic input/output operations, providing students with their first practical experience in translating algorithms into functional code that a computer can execute.

Chapter 5: Introduction to C++ Programming

C++ is a powerful, versatile programming language developed by Bjarne Stroustrup in 1979 as an extension of the C language. It supports multiple programming paradigms, including procedural, object-oriented, and generic programming. This chapter introduces the fundamentals of C++ programming.

History and Features of C++

Origin and Evolution:

  • Developed by Bjarne Stroustrup at Bell Labs
  • Initially called “C with Classes”
  • Renamed to C++ in 1983 (++ is the increment operator in C)
  • Standardized by ISO in 1998 (C++98)
  • Major updates: C++03, C++11, C++14, C++17, C++20

Key Features:

  • Object-oriented programming
  • Rich standard library
  • Low-level memory manipulation
  • High performance
  • Platform independence
  • Backward compatibility with C
  • Support for generic programming through templates
  • Exception handling

C++ Development Environment

Components of a C++ Development Environment:

  • Text editor or Integrated Development Environment (IDE)
  • C++ compiler (g++, Microsoft Visual C++, Clang)
  • Debugger
  • Build system (Make, CMake)

Popular C++ IDEs:

  • Visual Studio
  • Code::Blocks
  • Dev-C++
  • Eclipse CDT
  • Qt Creator
  • CLion

Structure of a C++ Program

A basic C++ program structure:

cpp

// Include directives
#include <iostream>

// Optional namespace declaration
using namespace std;

// Main function
int main() {
    // Statements
    cout << "Hello, World!" << endl;
    
    // Return statement
    return 0;
}

Components Explained:

  • Preprocessor Directives: Lines starting with # that are processed before compilation (e.g., #include)
  • Namespace: Collection of identifiers that helps prevent naming conflicts
  • main() Function: Entry point of every C++ program
  • Statements: Instructions that perform actions (terminated by semicolons)
  • Return Statement: Indicates the end of the function and returns a value

Basic Input and Output

Standard Output (cout):

cpp

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;  // Prints text
    cout << 42 << endl;               // Prints numbers
    cout << "Sum: " << 5 + 3 << endl; // Combines text and expressions
    return 0;
}

Standard Input (cin):

cpp

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "You are " << age << " years old." << endl;
    return 0;
}

Comments in C++

Comments are ignored by the compiler and used to explain code:

cpp

// This is a single-line comment
/* This is
   a multi-line
   comment */

Variables and Data Types

Variable Declaration:

cpp

data_type variable_name = initial_value;

Basic Data Types:

  • int: Integer numbers (e.g., -5, 0, 42)
  • float: Single-precision floating-point numbers (e.g., 3.14f)
  • double: Double-precision floating-point numbers (e.g., 3.14159)
  • char: Single characters (e.g., ‘A’, ‘5’, ‘+’)
  • bool: Boolean values (true or false)

Example:

cpp

int age = 25;
float height = 5.9f;
double pi = 3.14159265359;
char grade = 'A';
bool isStudent = true;

Type Modifiers:

  • short: Reduces the size of int
  • long: Increases the size of int or double
  • signed/unsigned: Determines whether a type can represent negative values

Constants:

cpp

const int MAX_STUDENTS = 50;  // Cannot be changed later
#define PI 3.14159  // Preprocessor constant

Operators

Arithmetic Operators:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulus (remainder): %
  • Increment: ++
  • Decrement: --

Relational Operators:

  • Equal to: ==
  • Not equal to: !=
  • Greater than: >
  • Less than: <
  • Greater than or equal to: >=
  • Less than or equal to: <=

Logical Operators:

  • AND: &&
  • OR: ||
  • NOT: !

Assignment Operators:

  • Simple assignment: =
  • Add and assign: +=
  • Subtract and assign: -=
  • Multiply and assign: *=
  • Divide and assign: /=
  • Modulus and assign: %=

Type Conversion

Implicit Conversion (Automatic):

cpp

int x = 10;
double y = x;  // Automatically converts int to double

Explicit Conversion (Casting):

cpp

double pi = 3.14159;
int intPi = (int)pi;  // C-style cast
int intPi2 = static_cast<int>(pi);  // C++ style cast

Basic Programming Examples

Example 1: Area of a Rectangle:

cpp

#include <iostream>
using namespace std;

int main() {
    double length, width, area;
    
    cout << "Enter length: ";
    cin >> length;
    
    cout << "Enter width: ";
    cin >> width;
    
    area = length * width;
    
    cout << "Area of rectangle: " << area << endl;
    
    return 0;
}

Example 2: Temperature Conversion:

cpp

#include <iostream>
using namespace std;

int main() {
    double celsius, fahrenheit;
    
    cout << "Enter temperature in Celsius: ";
    cin >> celsius;
    
    fahrenheit = (celsius * 9.0/5.0) + 32.0;
    
    cout << celsius << " degrees Celsius is " << fahrenheit << " degrees Fahrenheit." << endl;
    
    return 0;
}

Error Types in C++

Syntax Errors:

  • Mistakes in the structure of the code
  • Detected during compilation
  • Examples: missing semicolons, unmatched parentheses

Semantic Errors:

  • Mistakes in the meaning of the code
  • May be caught during compilation or at runtime
  • Examples: type mismatches, undefined variables

Runtime Errors:

  • Errors that occur during program execution
  • Examples: division by zero, out-of-bounds array access

Logical Errors:

  • Program runs but produces incorrect results
  • Most difficult to find and fix
  • Examples: incorrect algorithm implementation, incorrect operators

Understanding the basics of C++ programming provides a foundation for exploring more advanced programming concepts in subsequent chapters. As you progress, you’ll build on these fundamental concepts to create more complex and powerful programs.

Chapter 6: Data Types and Operators

Data types and operators are fundamental building blocks in C++ programming. This chapter explores various data types available in C++ and the operations that can be performed on them.

Primitive Data Types

C++ provides several built-in data types:

Integer Types

int: The standard integer type

  • Size: Typically 4 bytes (platform-dependent)
  • Range: Typically -2,147,483,648 to 2,147,483,647

short: Smaller integer type

  • Size: Typically 2 bytes
  • Range: Typically -32,768 to 32,767

long: Larger integer type

  • Size: Typically 4 bytes (8 bytes on 64-bit systems)
  • Range: At least -2,147,483,648 to 2,147,483,647

long long: Even larger integer type

  • Size: Typically 8 bytes
  • Range: At least -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Example:

cpp

int regular = 42;
short small = 123;
long larger = 1234567L;
long long largest = 123456789012345LL;

Floating-Point Types

float: Single-precision floating-point

  • Size: Typically 4 bytes
  • Precision: About 7 decimal digits

double: Double-precision floating-point

  • Size: Typically 8 bytes
  • Precision: About 15 decimal digits

long double: Extended-precision floating-point

  • Size: Typically 12 or 16 bytes (platform-dependent)
  • Precision: At least as much as double, typically more

Example:

cpp

float pi_approx = 3.14159f;
double pi_better = 3.141592653589793;
long double pi_precise = 3.141592653589793238L;

Character Types

char: Basic character type

  • Size: 1 byte
  • Range: -128 to 127 or 0 to 255

wchar_t: Wide character type

  • Size: Typically 2 or 4 bytes
  • Used for representing larger character sets

char16_t and char32_t: Unicode character types

  • char16_t: For UTF-16 encoding (16 bits)
  • char32_t: For UTF-32 encoding (32 bits)

Example:

cpp

char letter = 'A';
wchar_t wide_letter = L'Ω';
char16_t utf16_char = u'Ω';
char32_t utf32_char = U'Ω';

Boolean Type

bool: Represents true or false values

  • Size: Typically 1 byte
  • Values: true or false

Example:

cpp

bool is_active = true;
bool has_permission = false;

Type Modifiers

Sign Modifiers

  • signed: Can represent both positive and negative values (default for most types)
  • unsigned: Can represent only non-negative values

Example:

cpp

unsigned int positive_only = 500; // Range: 0 to 4,294,967,295
signed int with_sign = -500; // Range: -2,147,483,648 to 2,147,483,647

Derived Data Types

Arrays

Collections of elements of the same type.

Example:

cpp

int numbers[5] = {10, 20, 30, 40, 50};
char name[10] = "John";

Pointers

Variables that store memory addresses.

Example:

cpp

int number = 42;
int* ptr = &number; // ptr holds the address of number

References

Alternative names for existing variables.

Example:

cpp

int original = 10;
int& reference = original; // reference is an alias for original

User-Defined Data Types

Structures (struct)

Groups related variables of different types.

Example:

cpp

struct Student {
    string name;
    int age;
    float gpa;
};

Student s1 = {"Rahul", 18, 9.2};

Enumerations (enum)

User-defined types with named constant values.

Example:

cpp

enum Day {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
Day today = WEDNESDAY;

Classes

Foundation of object-oriented programming, combining data and functions.

Example:

cpp

class Rectangle {
private:
    double length;
    double width;
public:
    void setDimensions(double l, double w) {
        length = l;
        width = w;
    }
    double area() {
        return length * width;
    }
};

Type Qualifiers

const

Makes variables unchangeable after initialization.

Example:

cpp

const double PI = 3.14159;
// PI = 3.14; // Error: Cannot modify a const variable

volatile

Indicates that a variable might be changed by external factors.

Example:

cpp

volatile int sensor_value; // Value might change unexpectedly

mutable

Allows modification of a member variable in a const member function.

Example:

cpp

class Example {
private:
    mutable int cache_value;
public:
    int getValue() const {
        cache_value = 42; // Allowed despite const function
        return cache_value;
    }
};

Type Conversion

Implicit Conversion (Coercion)

Automatic type conversion performed by the compiler.

Example:

cpp

int i = 10;
double d = i; // int implicitly converted to double

Explicit Conversion (Casting)

Manual type conversion specified by the programmer.

Example:

cpp

double d = 3.14159;
int i = (int)d; // C-style cast
int j = static_cast<int>(d); // C++ style cast

Operators

Arithmetic Operators

Perform mathematical operations on numeric values.

  • Addition +: Adds two values
  • Subtraction -: Subtracts the right operand from the left operand
  • Multiplication *: Multiplies two values
  • Division /: Divides the left operand by the right operand
  • Modulus %: Returns the remainder after division
  • Increment ++: Increases the value by 1
  • Decrement --: Decreases the value by 1

Example:

cpp

int a = 10, b = 3;
int sum = a + b;        // 13
int diff = a - b;       // 7
int product = a * b;    // 30
int quotient = a / b;   // 3 (integer division)
int remainder = a % b;  // 1
a++;                    // a becomes 11
b--;                    // b becomes 2

Relational Operators

Compare values and return boolean results.

  • Equal to ==: Returns true if operands are equal
  • Not equal to !=: Returns true if operands are not equal
  • Greater than >: Returns true if left operand is greater than right operand
  • Less than <: Returns true if left operand is less than right operand
  • Greater than or equal to >=: Returns true if left operand is greater than or equal to right operand
  • Less than or equal to <=: Returns true if left operand is less than or equal to right operand

Example:

cpp

int x = 10, y = 20;
bool isEqual = (x == y);      // false
bool isNotEqual = (x != y);   // true
bool isGreater = (x > y);     // false
bool isLess = (x < y);        // true
bool isGreaterEqual = (x >= y); // false
bool isLessEqual = (x <= y);  // true

Logical Operators

Perform boolean operations.

  • Logical AND &&: Returns true if both operands are true
  • Logical OR ||: Returns true if at least one operand is true
  • Logical NOT !: Returns the opposite of the operand’s value

Example:

cpp

bool a = true, b = false;
bool andResult = a && b;     // false
bool orResult = a || b;      // true
bool notResult = !a;         // false

Bitwise Operators

Perform operations at the bit level.

  • Bitwise AND &: Sets each bit to 1 if both bits are 1
  • Bitwise OR |: Sets each bit to 1 if at least one bit is 1
  • Bitwise XOR ^: Sets each bit to 1 if only one of the bits is 1
  • Bitwise NOT ~: Inverts all bits
  • Left shift <<: Shifts bits left, filling with zeros
  • Right shift >>: Shifts bits right, filling with sign bit or zero

Example:

cpp

int a = 5;  // Binary: 0101
int b = 3;  // Binary: 0011

int bitwiseAnd = a & b;   // 0001 = 1
int bitwiseOr = a | b;    // 0111 = 7
int bitwiseXor = a ^ b;   // 0110 = 6
int bitwiseNot = ~a;      // 1010 = -6 (in two's complement)
int leftShift = a << 1;   // 1010 = 10
int rightShift = a >> 1;  // 0010 = 2

Assignment Operators

Assign values to variables.

  • Simple assignment =: Assigns value
  • Addition assignment +=: Adds and assigns
  • Subtraction assignment -=: Subtracts and assigns
  • Multiplication assignment *=: Multiplies and assigns
  • Division assignment /=: Divides and assigns
  • Modulus assignment %=: Takes modulus and assigns
  • Bitwise assignment &=, |=, ^=, <<=, >>=: Perform bitwise operation and assign

Example:

cpp

int x = 10;
x += 5;    // Same as x = x + 5, x becomes 15
x -= 3;    // Same as x = x - 3, x becomes 12
x *= 2;    // Same as x = x * 2, x becomes 24
x /= 4;    // Same as x = x / 4, x becomes 6
x %= 4;    // Same as x = x % 4, x becomes 2

Other Operators

  • Conditional/Ternary Operator ? :: Three-operand operator that evaluates a condition and returns one of two values
    cpp

    int max = (a > b) ? a : b;  // If a > b, returns a, otherwise returns b
  • sizeof Operator: Returns the size of a variable or type in bytes
    cpp

    int size = sizeof(int);  // Typically returns 4
  • Comma Operator ,: Evaluates multiple expressions and returns the value of the rightmost expression
    cpp

    int x = (a = 5, a + 2);  // a becomes 5, x becomes 7
  • Scope Resolution Operator ::: Accesses identifiers in different scopes
    cpp

    std::cout << "Using namespace explicitly";
  • Member Access Operators . and ->: Access members of objects or pointers to objects
    cpp

    student.name = "Priya";    // Using dot operator
    studentPtr->name = "Raj";  // Using arrow operator

Operator Precedence and Associativity

Operators have different precedence levels that determine the order of operations. When operators have the same precedence, associativity determines the order.

High to low precedence (partial list):

  1. Scope resolution ::
  2. Member access ., ->, [], function calls ()
  3. Unary operators ++, --, ~, !, unary + and -, sizeof
  4. Multiplication, division, modulus *, /, %
  5. Addition, subtraction +, -
  6. Shift operators <<, >>
  7. Relational operators <, <=, >, >=
  8. Equality operators ==, !=
  9. Bitwise AND &
  10. Bitwise XOR ^
  11. Bitwise OR |
  12. Logical AND &&
  13. Logical OR ||
  14. Conditional operator ?:
  15. Assignment operators =, +=, -=, etc.
  16. Comma operator ,

Example of precedence in action:

cpp

int result = 5 + 3 * 2;  // Multiplication happens first, result is 11
int result2 = (5 + 3) * 2;  // Parentheses override precedence, result is 16

Understanding data types and operators is fundamental to programming in C++. These concepts form the building blocks for more complex operations and algorithms that you’ll explore in future chapters.

Complete Chapter-wise Hsslive Plus One Computer Science Notes

Our HSSLive Plus One Computer Science Notes cover all chapters with key focus areas to help you organize your study effectively:

Leave a Comment