Skip to content

Commit

Permalink
Introduction to C++ Fundamentals: Syntax, Structure, and Basic Compon… (
Browse files Browse the repository at this point in the history
subhadipbhowmik#536)

* Introduction to C++ Fundamentals: Syntax, Structure, and Basic Components

* Add content of day 08 subhadipbhowmik#504
  • Loading branch information
nihasinghania22 authored Jul 20, 2024
1 parent 3d63b83 commit 5e98d64
Show file tree
Hide file tree
Showing 3 changed files with 382 additions and 1 deletion.
217 changes: 216 additions & 1 deletion docs/day-02/first-cpp-program.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,222 @@ Examples:
- `cout << "Hello, World!" << endl;` - Prints "Hello, World!" to the console.
- `if (age >= 18) { ... }` - Conditional statement to check if age is greater than or equal to 18 and execute code within the block if true.
- `for (int i = 0; i < 3; i++) { ... }` - Loop that iterates three times.
6. Comments (Optional):

Additional Syntax Elements:


5. Semicolons (;):

In C++, semicolons are used to terminate most statements.
They act as a separator between different instructions.
Example:
cppCopyint x = 5;
cout << "Hello";

Forgetting semicolons is a common mistake for beginners and can lead to compilation errors.

6. Curly Braces ({}):

Used to group multiple statements into a single block.
Essential for defining the scope of functions, loops, and conditional statements.
Also used to define the body of classes and namespaces.
Example:
cppCopyif (condition) {
// Multiple statements can be placed here
statement1;
statement2;
}


7. Parentheses ():

Used in function declarations and calls to enclose parameters.
Required in conditional statements and loops to enclose conditions.
Example:
cppCopyint add(int a, int b) {
return a + b;
}

if (x > 0) {
// Do something
}



Data Types:

C++ provides several built-in data types:

Integer types:

int: Whole numbers (e.g., -5, 0, 42)
short: Smaller range integer
long: Larger range integer
unsigned variations of the above


Floating-point types:

float: Single-precision decimal numbers
double: Double-precision decimal numbers


Character types:

char: Single character (e.g., 'A', '7', '$')


Boolean type:

bool: True or false values


Derived types:

arrays: Collections of elements of the same type
pointers: Store memory addresses
references: Aliases for existing variables



Example:
cppCopyint age = 25;
float pi = 3.14159f;
char grade = 'A';
bool isStudent = true;
int numbers[5] = {1, 2, 3, 4, 5}; // Array
int* ptr = &age; // Pointer
int& ageRef = age; // Reference

8. Operators:

C++ provides various types of operators:
a. Arithmetic operators:

Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%)
Example: int result = 10 + 5 * 2; // result is 20

b. Comparison operators:

Equal to (==), Not equal to (!=), Greater than (>), Less than (<),
Greater than or equal to (>=), Less than or equal to (<=)
Example: if (age >= 18) { cout << "Adult"; }

c. Logical operators:

AND (&&), OR (||), NOT (!)
Example: if (age > 18 && hasLicense) { cout << "Can drive"; }

d. Assignment operators:

Simple assignment (=)
Compound assignments (+=, -=, *=, /=, %=)
Example:
cppCopyint x = 5;
x += 3; // Equivalent to x = x + 3;



9. Control Structures:

Control structures direct the flow of program execution:
a. if-else statements:
cppCopyif (condition) {
// Code executed if condition is true
} else if (another_condition) {
// Code executed if another_condition is true
} else {
// Code executed if all conditions are false
}
b. switch statements:
cppCopyswitch (variable) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}
c. Loops:

for loop: Used when number of iterations is known
cppCopyfor (int i = 0; i < 5; i++) {
cout << i << " ";
}

while loop: Executes while a condition is true
cppCopywhile (condition) {
// Code to repeat
}

do-while loop: Executes at least once, then repeats while condition is true
cppCopydo {
// Code to repeat
} while (condition);



10. Functions:

Functions are reusable blocks of code:

Function declaration: Tells compiler about function name, return type, and parameters
Function definition: Provides the actual body of the function
Example:
cppCopy// Declaration
int add(int a, int b);

// Definition
int add(int a, int b) {
return a + b;
}

// Function call
int result = add(5, 3);


Function overloading: Multiple functions can have the same name if they differ in parameter types or number.

11. Basic Input/Output:

C++ uses streams for input/output operations:

cout for output:
cppCopycout << "Hello, " << name << "!";

cin for input:
cppCopyint age;
cin >> age;

Formatting output:
cppCopy#include <iomanip>
cout << fixed << setprecision(2) << 3.14159; // Outputs 3.14



12. Header Files:

Header files contain declarations of functions and variables:

Standard library headers: <iostream>, <string>, <vector>, etc.
User-defined headers: Created for custom libraries
Usage:
cppCopy#include <iostream> // Angular brackets for standard headers
#include "myheader.h" // Quotes for user-defined headers



13. Compilation Process:

C++ programs go through several stages before execution:

Preprocessing: Handles directives like #include and #define
Compilation: Converts C++ code to object code
Linking: Combines object code with libraries to create an executable

14. Comments (Optional):

- Lines starting with `//` (single line comment) or `/* ... */` (multi-line comment).
- Provide explanations within the code for better understanding.
Expand Down
7 changes: 7 additions & 0 deletions docs/day-08/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"label": "Day 08",
"position": 8,
"link": {
"type": "generated-index"
}
}
159 changes: 159 additions & 0 deletions docs/day-08/strings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
1. Introduction to Strings in C++

A string is a sequence of characters. In C++, there are two main ways to work with strings:

1. C-style strings (character arrays)
2. The C++ string class


2. C-style Strings

C-style strings are inherited from the C language. They are essentially arrays of characters ending with a null character '\0'.
Example:

cppCopychar str[] = "Hello"; // Equivalent to {'H','e','l','l','o','\0'}
Pros:

Low-level control
Compatibility with C code

Cons:

Prone to buffer overflow errors
Limited built-in functionality


3. C++ String Class

The C++ string class is part of the Standard Template Library (STL). It's much more powerful and safer to use than C-style strings.
To use the string class, include the <string> header:
cppCopy#include <string>
using namespace std;

string str = "Hello, World!";

4. String Declaration and Initialization

You can declare and initialize strings in several ways:
cppCopystring s1; // Empty string
string s2 = "Hello"; // Initialize with a string literal
string s3("World"); // Initialize using constructor
string s4(5, 'A'); // Initialize with 5 'A' characters: "AAAAA"
string s5 = s2; // Copy initialization

5. String Operations

a. Concatenation:
cppCopystring a = "Hello";
string b = "World";
string c = a + " " + b; // c is "Hello World"

b. Appending:
cppCopystring str = "Hello";
str += " World"; // str is now "Hello World"

c. Accessing characters:
cppCopystring str = "Hello";
char ch = str[0]; // ch is 'H'

d. Length:
cppCopystring str = "Hello";
int len = str.length(); // or str.size(); both return 5

e. Substring:
cppCopystring str = "Hello, World!";
string sub = str.substr(7, 5); // sub is "World"

f. Finding:
cppCopystring str = "Hello, World!";
size_t pos = str.find("World"); // pos is 7

g. Replacing:
cppCopystring str = "Hello, World!";
str.replace(7, 5, "C++"); // str is now "Hello, C++!"

6. String Input/Output

a. Output:
cppCopystring str = "Hello";
cout << str << endl;

b. Input:
cppCopystring name;
cout << "Enter your name: ";
cin >> name; // Reads until whitespace

c. Reading a line:
cppCopystring line;
getline(cin, line); // Reads entire line, including spaces

7. String Comparison

You can compare strings using relational operators:
cppCopystring s1 = "apple";
string s2 = "banana";
if (s1 < s2) {
cout << "apple comes before banana" << endl;
}

8. String Conversion

a. To C-style string:
cppCopystring str = "Hello";
const char* cstr = str.c_str();

b. Number to string:
cppCopyint num = 123;
string str = to_string(num);

c. String to number:
cppCopystring str = "123";
int num = stoi(str); // string to int
double d = stod(str); // string to double

9. String Iteration

You can iterate through a string using range-based for loop or traditional for loop:
cppCopystring str = "Hello";
for (char c : str) {
cout << c << " ";
}

10. String Modifiers

a. Insert:
cppCopystring str = "Hello";
str.insert(5, " World"); // str is now "Hello World"

b. Erase:
cppCopystring str = "Hello World";
str.erase(5, 6); // str is now "Hello"

c. Clear:
cppCopystring str = "Hello";
str.clear(); // str is now an empty string

11. String Capacity

a. Resize:
cppCopystring str = "Hello";
str.resize(10, '!'); // str is now "Hello!!!!!"

b. Capacity:
cppCopystring str = "Hello";
cout << str.capacity(); // Prints the current capacity

12. Advanced String Operations

a. Regular expressions (C++11 and later):
cppCopy#include <regex>
string str = "Hello, 123";
regex pattern("\\d+");
if (regex_search(str, pattern)) {
cout << "String contains digits" << endl;
}

b. String view (C++17):
cppCopy#include <string_view>
string_view sv = "Hello, World!";
cout << sv.substr(0, 5); // Efficient substring operation

0 comments on commit 5e98d64

Please sign in to comment.