2. Basic Concepts

Module 2.0 • C++ Fundamentals, Variables, Constants, Flow Control & Functions

Introduction to C++

C++ represents a robust, high-level object-oriented language that supports both procedural and object-oriented programming paradigms. It was developed to enhance the capabilities of the C programming language by adding features that facilitate complex software development.

History of C++

Features of C++

Differences Between C and C++

Feature C C++
ParadigmProcedural programmingObject-oriented and procedural
Data AbstractionNo classes or objectsSupports classes and objects
InheritanceNot supportedSupports inheritance
Function OverloadingNot supportedSupported
Operator OverloadingNot supportedSupported
Standard LibraryLimited library supportRich Standard Template Library (STL)
Memory ManagementManual (malloc/free)Manual (new/delete) + smart pointers
Input/Outputprintf, scanfcout, cin with streams
NamespacesNot availableSupports namespaces
Exception HandlingNot supportedSupports exception handling

Basic Syntax

Here's an overview of basic data types including int, float, double, char, and bool.

Basic Data Types in C++

Data Type Description Example
intRepresents integer values (whole numbers).int age = 25;
floatRepresents single-precision floating-point numbers. Useful for representing decimal values but with less precision than double.float temperature = 36.5f;
doubleRepresents double-precision floating-point numbers. Provides more precision than float.double pi = 3.14159;
charRepresents a single character. Stored as a numeric value (ASCII).char grade = 'A';
boolRepresents a boolean value, which can be either true or false.bool isStudent = true;

Detailed Explanation

Example Usage in C++

#include <iostream>
 
int main() {
    // Integer
    int age = 30;
    
    // Float
    float height = 5.9f; // 'f' denotes it's a float
    
    // Double
    double pi = 3.14159;
 
    // Character
    char initial = 'A';
 
    // Boolean
    bool isMarried = false;
 
    // Output
    std::cout << "Age: " << age << std::endl;
    std::cout << "Height: " << height << std::endl;
    std::cout << "Pi: " << pi << std::endl;
    std::cout << "Initial: " << initial << std::endl;
    std::cout << "Is Married: " << std::boolalpha << isMarried << std::endl; // Displays true/false
 
    return 0;
}

Variables

Definition: A variable is a named storage location in memory that can hold a value and whose value can change during program execution.

Characteristics:

Declaring and Initializing Variables:

int age;              // Declaration
age = 25;            // Initialization
 
float height = 5.9f; // Declaration and initialization

Example:

#include <iostream>
 
int main() {
    int age = 30;          // Variable of type int
    float height = 5.9f;  // Variable of type float
    char initial = 'A';    // Variable of type char
 
    std::cout << "Age: " << age << std::endl;
    std::cout << "Height: " << height << std::endl;
    std::cout << "Initial: " << initial << std::endl;
 
    return 0;
}

Constants

Definition: A constant is a value that cannot be changed during the program execution. Constants provide a way to define fixed values that remain unchanged.

Characteristics:

Declaring Constants:
Constants can be declared using the const keyword or the constexpr keyword (for compile-time constants).

Using const:

const int DAYS_IN_WEEK = 7;  // Constant integer
const float PI = 3.14f;      // Constant float

Using constexpr:

constexpr int MAX_SIZE = 100; // Compile-time constant

Example:

#include <iostream>
 
int main() {
    const int MAX_USERS = 100; // Constant value
    const float PI = 3.14159f;  // Constant value
 
    std::cout << "Max Users: " << MAX_USERS << std::endl;
    std::cout << "Value of PI: " << PI << std::endl;
 
    // MAX_USERS = 150; // This would cause a compilation error
 
    return 0;
}

Summary

Input and output operations are performed cleanly (using cin and cout).

2.3 Control Structures

Conditional statements in C++ allow the program to make decisions based on certain conditions. They enable you to execute different blocks of code depending on whether a condition evaluates to true or false. The primary types of conditional statements in C++ are:

1. if Statement

The simplest form of a conditional statement. It checks a condition and executes a block of code if the condition is true.

if (condition) {
   // code to execute if condition is true
}

Example:

#include <iostream>
using namespace std;
 
int main() {
   int number = 10;
   
   if (number > 5) {
       cout << "Number is greater than 5." << endl;
   }
 
   return 0;
}

2. if-else Statement

This allows for an alternative action if the condition is false.

if (condition) {
   // code to execute if condition is true
} else {
   // code to execute if condition is false
}

Example:

#include <iostream>
using namespace std;
 
int main() {
   int number = 3;
   
   if (number > 5) {
       cout << "Number is greater than 5." << endl;
   } else {
       cout << "Number is not greater than 5." << endl;
   }
 
   return 0;
}

3. else if Statement

This is used to check multiple conditions.

if (condition1) {
   // code if condition1 is true
} else if (condition2) {
   // code if condition2 is true
} else {
   // code if both conditions are false
}

Example:

#include <iostream>
using namespace std;
 
int main() {
   int number = 7;
 
   if (number > 10) {
       cout << "Number is greater than 10." << endl;
   } else if (number > 5) {
       cout << "Number is greater than 5 but less than or equal to 10." << endl;
   } else {
       cout << "Number is 5 or less." << endl;
   }
 
   return 0;
}

4. switch Statement

This is used to select one of many code blocks to execute based on the value of a variable.

switch (variable) {
   case value1:
       // code to execute if variable == value1
       break;
   case value2:
       // code to execute if variable == value2
       break;
   // more cases...
   default:
       // code to execute if no cases match
}

Example:

#include <iostream>
using namespace std;
 
int main() {
   int day = 3;
 
   switch (day) {
       case 1:
            cout << "Monday" << endl;
            break;
       case 2:
            cout << "Tuesday" << endl;
            break;
       case 3:
            cout << "Wednesday" << endl;
            break;
       case 4:
            cout << "Thursday" << endl;
            break;
       case 5:
            cout << "Friday" << endl;
            break;
       case 6:
       case 7:
            cout << "Weekend" << endl;
            break;
       default:
            cout << "Invalid day" << endl;
   }
 
   return 0;
}

Summary

Conditional statements are crucial in C++ programming, allowing you to create logic in your applications. By using if, else if, else, and switch statements, you can direct the flow of execution based on various conditions. This enables the creation of dynamic and responsive programs.

2.3.2 Loops in C++

An overview of loops in C++ with examples for each type of loop: for, while, and do-while.

1. For Loop

The for loop is used when you know how many times you want to execute a statement or a block of statements.

for (initialization; condition; increment) {
   // code to execute
}

Example:

#include <iostream>
using namespace std;
 
int main() {
   for (int i = 0; i < 5; i++) {
       cout << "Iteration: " << i << endl;
   }
   return 0;
}

2. While Loop

while (condition) {
   // code to execute
}

Example:

#include <iostream>
using namespace std;
 
int main() {
   int i = 0;
   while (i < 5) {
       cout << "Iteration: " << i << endl;
       i++;
   }
   return 0;
}

3. Do-While Loop

A do-while loop is similar to a while loop, but it guarantees that the block of code will execute at least once before verification checks.

do {
   // code to execute
} while (condition);

Example:

#include <iostream>
using namespace std;
 
int main() {
   int i = 0;
   do {
       cout << "Iteration: " << i << endl;
       i++;
   } while (i < 5);
   return 0;
}

Summary

2.4 Functions

In C++, functions are blocks of code designed to perform a specific task. They help in organizing code, promoting reusability, and improving readability. Here’s a detailed explanation of functions, including function declaration, definition, and calling, along with examples.

1. What is a Function?

A function is a self-contained block of code that can be called to perform a particular task. It can take inputs (parameters) and can return a value.

2. Function Declaration

A function declaration tells the compiler about the function's name, return type, and parameters. It is often placed before the main function.

returnType functionName(parameterType parameterName);

Example:

int add(int a, int b);

3. Function Definition

A function definition contains the actual code that defines what the function does. It includes the return type, function name, parameters, and the body of the function.

returnType functionName(parameterType parameterName) {
    // function body
}

Example:

int add(int a, int b) {
    return a + b; // returns the sum of a and b
}

4. Function Calling

To use a function, you call it by its name and pass the required arguments.

functionName(arguments);

Example:

int main() {
    int result = add(5, 3); // Calling the function
    cout << "The sum is: " << result << endl; // Output: The sum is: 8
    return 0;
}

Complete Example

Here is a complete C++ program that demonstrates function declaration, definition, and calling:

#include <iostream>
using namespace std;
 
// Function Declaration
int add(int a, int b);  // Declaring the function
 
// Function Definition
int add(int a, int b) {
    return a + b; // The function returns the sum of a and b
}
 
int main() {
    int num1, num2;
    
    cout << "Enter two numbers: ";
    cin >> num1 >> num2; // Taking input from the user
    
    // Function Calling
    int sum = add(num1, num2); // Calling the function to get the sum
    
    cout << "The sum is: " << sum << endl; // Displaying the result
    
    return 0;
}

Summary

Key Points: Functions improve code organization and reusability. You can have multiple functions in a program, each performing different tasks. Functions can return values or can be void (do not return a value).

2.4.2 Function Overloading

Function overloading in C++ allows you to define multiple functions with the same name but different parameters. This feature enables you to create functions that perform similar tasks but handle different types or numbers of inputs. Here’s a detailed explanation with examples:

What is Function Overloading? Function overloading is a compile-time polymorphism feature in C++. It allows you to define multiple functions with the same name but with different parameter types, numbers, or both. The compiler differentiates these functions based on their signatures.

Syntax:

returnType functionName(parameterType1 parameterName1);
returnType functionName(parameterType2 parameterName2);

Examples of Function Overloading

Example 1: Overloading with Different Parameter Types

#include <iostream>
using namespace std;
 
// Function to add two integers
int add(int a, int b) {
    return a + b;
}
 
// Function to add two doubles
double add(double a, double b) {
    return a + b;
}
 
int main() {
    int intSum = add(5, 3); // Calls the integer version
    double doubleSum = add(5.5, 3.3); // Calls the double version
 
    cout << "Integer Sum: " << intSum << endl; // Output: Integer Sum: 8
    cout << "Double Sum: " << doubleSum << endl; // Output: Double Sum: 8.8
 
    return 0;
}

Example 2: Overloading with Different Number of Parameters

#include <iostream>
using namespace std;
 
// Function to multiply two integers
int multiply(int a, int b) {
    return a * b;
}
 
// Function to multiply three integers
int multiply(int a, int b, int c) {
    return a * b * c;
}
 
int main() {
    int product2 = multiply(2, 3); // Calls the two-parameter version
    int product3 = multiply(2, 3, 4); // Calls the three-parameter version
 
    cout << "Product of 2 numbers: " << product2 << endl; // Output: Product of 2 numbers: 6
    cout << "Product of 3 numbers: " << product3 << endl; // Output: Product of 3 numbers: 24
 
    return 0;
}

Example 3: Overloading with Reference Parameters

#include <iostream>
using namespace std;
 
// Function to swap two integers
void swap(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}
 
// Function to swap two doubles
void swap(double &a, double &b) {
    double temp = a;
    a = b;
    b = temp;
}
 
int main() {
    int x = 5, y = 10;
    double m = 5.5, n = 10.5;
 
    swap(x, y); // Calls the integer version
    swap(m, n); // Calls the double version
 
    cout << "Swapped integers: " << x << ", " << y << endl; // Output: Swapped integers: 10, 5
    cout << "Swapped doubles: " << m << ", " << n << endl; // Output: Swapped doubles: 10.5, 5.5
 
    return 0;
}

Summary

Key Points: Function overloading is limited to differences in the type or number of parameters; it cannot be done by return type alone. Overloaded functions can coexist in the same scope without any issues.

2.4.3 Default Arguments and Inline Functions

Default Arguments in C++

Definition: Default arguments allow a function to have predefined values for parameters. If the caller does not provide values for those parameters, the default values are used.

Example of Default Arguments:

#include <iostream>
using namespace std;
 
// Function with default argument
void greet(string name, string greeting = "Hello") {
    cout << greeting << ", " << name << "!" << endl;
}
 
int main() {
    greet("Alice");        // Uses default greeting
    greet("Bob", "Hi");   // Uses custom greeting
    return 0;
}

Expected Output:

Hello, Alice!
Hi, Bob!

Explanation: The greet function has a default parameter for greeting. When called with just one argument, it uses the default value "Hello". When greet is called with two arguments, it uses the provided greeting "Hi".

Inline Functions in C++

Definition: Inline functions are used to suggest to the compiler to insert the function code directly at the call site, reducing the overhead of a function call.

Example of Inline Functions:

#include <iostream>
using namespace std;
 
// Inline function to calculate the square
inline int square(int x) {
    return x * x;
}
 
int main() {
    int num = 5;
    cout << "Square of " << num << " is: " << square(num) << endl;
    return 0;
}

Expected Output:

Square of 5 is: 25

Explanation: The square function is declared as inline, which means the compiler will attempt to replace calls to square with the actual code for the function. This can lead to performance improvements, especially for small functions that are called frequently.

Summary

Key Points: Default arguments can be mixed with non-default arguments, but must be at the end of the parameter list. Inline functions should be short and simple; large functions might not be inlined even if declared as such.

Verify Comprehension: Technical Knowledge Assessment

Click your choice for each question to view feedback immediately. Complete all questions to evaluate your metric score.