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++
-
Origins:
- C++ was developed by Bjarne Stroustrup at Bell Labs in the early 1980s as an extension of the C programming language.
- The initial version, named "C with Classes," introduced features such as classes and basic inheritance.
-
Evolution:
- In 1983, the name was changed to C++ (the "++" symbol indicates the increment operator in C, reflecting the evolution of the language).
- The first edition of "The C++ Programming Language" was published in 1985, establishing C++ as a formal language.
-
Standardization:
- The first standard, C++98, was released in 1998, followed by updates in 2003 (C++03).
- C++11 introduced significant features like auto keyword, nullptr, range-based for loops, and lambda expressions.
- Subsequent standards include C++14, C++17, and C++20, each adding new features and improving the language.
Features of C++
- Object-Oriented Programming (OOP): Supports encapsulation, inheritance, and polymorphism, allowing for code reusability and modularity.
- Standard Template Library (STL): A powerful library that provides a set of common data structures (like vectors and lists) and algorithms (like sort and search).
- Low-Level Manipulation: Like C, C++ provides low-level memory manipulation through pointers, which can be useful for system programming.
- Strongly Typed: C++ enforces strong type checking, reducing errors related to data type mismatches.
- Function Overloading and Operator Overloading: Allows multiple functions with the same name and custom behavior for operators, respectively, improving code readability.
- Compatibility with C: C++ is largely compatible with C, enabling C code to be integrated into C++ programs.
- Rich Library Support: A wide array of libraries is available for various functionalities, including graphics, networking, and more.
Differences Between C and C++
| Feature | C | C++ |
|---|---|---|
| Paradigm | Procedural programming | Object-oriented and procedural |
| Data Abstraction | No classes or objects | Supports classes and objects |
| Inheritance | Not supported | Supports inheritance |
| Function Overloading | Not supported | Supported |
| Operator Overloading | Not supported | Supported |
| Standard Library | Limited library support | Rich Standard Template Library (STL) |
| Memory Management | Manual (malloc/free) | Manual (new/delete) + smart pointers |
| Input/Output | printf, scanf | cout, cin with streams |
| Namespaces | Not available | Supports namespaces |
| Exception Handling | Not supported | Supports 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 |
|---|---|---|
int | Represents integer values (whole numbers). | int age = 25; |
float | Represents single-precision floating-point numbers. Useful for representing decimal values but with less precision than double. | float temperature = 36.5f; |
double | Represents double-precision floating-point numbers. Provides more precision than float. | double pi = 3.14159; |
char | Represents a single character. Stored as a numeric value (ASCII). | char grade = 'A'; |
bool | Represents a boolean value, which can be either true or false. | bool isStudent = true; |
Detailed Explanation
- int (Integer): Size is typically 4 bytes (varies by system). Range is usually from -2,147,483,648 to 2,147,483,647. It is used for counting and whole number operations.
- float (Floating Point): Size is usually 4 bytes. Precision is approximately 6-7 decimal digits. It is used for representing decimal numbers with less precision.
- double (Double Precision): Size is usually 8 bytes. Precision is approximately 15-16 decimal digits. It is used when more precision is needed for decimal numbers.
- char (Character): Size is 1 byte. It is used to store a single character (e.g., 'a', 'B', '1'). Characters are stored using their ASCII values.
- bool (Boolean): Size is typically 1 byte (though it may vary). It can only hold true or false. It is used for conditions and logical operations.
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:
- Type: Each variable has a data type (e.g., int, float, char) that determines the kind of data it can hold.
- Scope: The scope of a variable defines where it can be accessed (local, global).
- Lifetime: The lifetime of a variable refers to the duration for which the variable exists in memory.
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:
- Type: Like variables, constants also have data types.
- Readability: Using constants improves code readability by giving meaningful names to fixed values.
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
- Variables are used to store data that can change during the execution of a program.
- Constants are used to define fixed values that should not be altered, enhancing code clarity and preventing accidental changes.
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:
- if Statement
- if-else Statement
- else if Statement
- switch Statement
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
- For Loop: Best used when the number of iterations is known beforehand.
- While Loop: Useful when the number of iterations is not known and depends on a condition.
- Do-While Loop: Ensures that the loop body is executed at least once before the condition is checked.
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
- Function Declaration: Provides the function's signature to the compiler.
- Function Definition: Contains the actual implementation of the function.
- Function Calling: Executes the function using its name and passing necessary arguments.
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
- Function Overloading: Allows the same function name to be used with different parameter types or counts.
- Compile-Time Polymorphism: The decision of which function to call is made at compile time based on the arguments provided.
- Benefits: Improves code readability and organization by allowing similar functions to be grouped together.
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
- Default Arguments: Simplifies function calls by providing predefined values, enhancing flexibility.
- Inline Functions: Optimize performance by suggesting to the compiler to replace the function call with the actual function code.
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.
Click your choice for each question to view feedback immediately. Complete all questions to evaluate your metric score.