From 5e98d640f8246fc862a0b08537ac39f8fafc7b03 Mon Sep 17 00:00:00 2001 From: Niha Singhania <89926534+nihasinghania22@users.noreply.github.com> Date: Sat, 20 Jul 2024 14:34:03 +0530 Subject: [PATCH] =?UTF-8?q?Introduction=20to=20C++=20Fundamentals:=20Synta?= =?UTF-8?q?x,=20Structure,=20and=20Basic=20Compon=E2=80=A6=20=20(#536)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Introduction to C++ Fundamentals: Syntax, Structure, and Basic Components * Add content of day 08 #504 --- docs/day-02/first-cpp-program.md | 217 ++++++++++++++++++++++++++++++- docs/day-08/_category_.json | 7 + docs/day-08/strings.md | 159 ++++++++++++++++++++++ 3 files changed, 382 insertions(+), 1 deletion(-) create mode 100644 docs/day-08/_category_.json create mode 100644 docs/day-08/strings.md diff --git a/docs/day-02/first-cpp-program.md b/docs/day-02/first-cpp-program.md index a176d8db..81cefec1 100644 --- a/docs/day-02/first-cpp-program.md +++ b/docs/day-02/first-cpp-program.md @@ -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 +cout << fixed << setprecision(2) << 3.14159; // Outputs 3.14 + + + +12. Header Files: + +Header files contain declarations of functions and variables: + +Standard library headers: , , , etc. +User-defined headers: Created for custom libraries +Usage: +cppCopy#include // 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. diff --git a/docs/day-08/_category_.json b/docs/day-08/_category_.json new file mode 100644 index 00000000..2a56a494 --- /dev/null +++ b/docs/day-08/_category_.json @@ -0,0 +1,7 @@ +{ + "label": "Day 08", + "position": 8, + "link": { + "type": "generated-index" + } + } \ No newline at end of file diff --git a/docs/day-08/strings.md b/docs/day-08/strings.md new file mode 100644 index 00000000..58d69c1a --- /dev/null +++ b/docs/day-08/strings.md @@ -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 header: +cppCopy#include +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 +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 sv = "Hello, World!"; +cout << sv.substr(0, 5); // Efficient substring operation