Cplusplus Abs Beginer
Cplusplus Abs Beginer
#include <string>
// Dynamic array implementation Evaluates to 0 (false)
Logical NOT ! !(x > 3 && x < 10) because ! is used to
#include <vector> reverse the result
For loop // Automatically determining the size and initializing the array with
values 1, 2, 3, 4, and 5
The for loop is used to execute a block of code for a set number of times. int nums4[] = {1,2,3,4,5};
for (int i = 0; i < 5; i++) { Another example of creation is by initializing an integer array with a maximum capacity and
std::cout << i << std::endl; allowing users to input the size of the array at runtime and then iterate through the array
} elements up to the user-defined size, potentially operating on each element.
int counter = 3; const int capacity = 100; // Maximum capacity of the array
cout << "Enter a string (terminate with '.'): "; // Iterate over each element 'i' of array 'A'
cin >> sym; // sjdkfJHAAAH.N2671637A // Using a range-based loop, print each element separated by a space
for(int &i : A) {
while (sym != '.') std::cout << i << " "; // Output: 2, 3, 4
{ }
if (sym >= 'A' && sym <= 'Z')
countCapAlphas++; return 0;
}
cin >> sym;
}
Example 3
cout << "Number of uppercase letters: " << countCapAlphas << endl;
Multi-dimensional arrays
return 0; A multi-dimensional array is an array of arrays that stores similar types of data in tabular form.
}
// Declaring a 2D array with 3 rows and 4 columns and initializing it with
specific values
int 2dArray[3][4] = {{ 1, 2, 3, 4 }, { 5, 6, 7, 8 }, {9, 7, 1, 3}};
Access
int 2dArray[3][4] = {{ 1, 2, 3, 4 }, { 5, 6, 7, 8 }, {9, 7, 1, 3}};
// Output: 1
std::cout << "Element at 2dArray[0][0]: " << 2dArray[0][0] << std::endl;
// Output: 8
std::cout << "Element at 2dArray[1][3]: " << 2dArray[1][3] << std::endl;
C++ FOR ABSOLUTE BEGINNERS
Operations
int 2dArray[3][4] = {{ 1, 2, 3, 4 }, { 5, 6, 7, 8 }, {9, 7, 1, 3}}; Declaring and initializing pointers
2dArray[1][3] = 20;
// Declaration
// Output: 20
int* ptr;
std::cout << "Modified element at arr[1][3]: " << 2dArray[1][3] << std::endl;
// Initialization
// Nested loops for iterating through the 2D array
int* ptr = nullptr;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
Functions
}
std::cout << 2dArray[i][j] << " "; Real-life example
A function is a reusable block of code that performs a specific task or a set of related tasks.
std::cout << std::endl; int a = 10;
} int* ptr = &a; // Pointer to the variable a
Note: A function body comprises a set of instructions that compute the result based on the
input parameters. Incrementing/Decrementing a Pointer
Practical examples of functions When a pointer is incremented (e.g., p++), it moves to the next memory location based on
the size of the data type it points to. Similarly, decrementing a pointer (e.g., p--) moves it to
the previous memory location by subtracting the size of the data type. Here’s an example
Example 1: Pass arguments by value demonstrating pointer increment/decrement:
#include <iostream>
#include <iostream>
using namespace std;
// Function to compute the cube of a number
double cube(double number) {
int main() {
return number * number * number;
int numbers[] = {10, 20, 30, 40};
}
int* p = numbers; // Pointer to the first element of the array
int main() {
cout << "Address of p: "<< &p << " pointing to: "<< p << " have value
double num = 4;
at: "<<*p << endl;
double result = cube(num);
p++; // Moves the pointer to the second element of the array
// Output: 64
cout << "Address of p: "<< &p << " pointing to: "<< p << " have value
std::cout << "The cube of " << num << " is: " << result << std::endl;
at: "<<*p << endl;
return 0;
p++; // Moves the pointer to the third element of the array
}
cout << "Address of p: "<< &p << " pointing to: "<< p << " have value
at: "<<*p << endl;
Example 2: Pass arguments by reference
p++; // Moves the pointer to the fourth element of the array
#include <iostream> cout << "Address of p: "<< &p << " pointing to: "<< p << " have value
at: "<<*p << endl;
// Function to compute the cube of a number using reference (include the &
operator before the parameter name) p--; // Moves the pointer to the third element of the array
void cube(double& number) { cout << "Address of p: "<< &p << " pointing to: "<< p << " have value
number = number * number * number; at: "<<*p << endl;
}
p--; // Moves the pointer to the second element of the array
int main() { cout << "Address of p: "<< &p << " pointing to: "<< p << " have value
double num = 4; at: "<<*p << endl;
cube(num); p--; // Moves the pointer to the first element of the array
// Output: 64 cout << "Address of p: "<< &p << " pointing to: "<< p << " have value
std::cout << "The cube of 4 is:" << num << std::endl; at: "<<*p << endl;
return 0; return 0;
} }
Example 3: Function calls with arrays Pointer arithmetic with integral value
When we pass an array to a function, what’s actually passed is the base address or the memory We can perform arithmetic operations with integral values. Adding an integer value to a
address of the first element of the array. pointer adjusts its position based on the size of the data type it points to. Here’s an example
that demonstrates pointer arithmetic with an integral value:
#include <iostream>
using namespace std; #include <iostream>
using namespace std;
void funWithArrays(int A[], int size) {
// Function to print elements of the array int main() {
cout << "Array elements: "; int numbers[] = {1, 2, 3, 4};
for(int i = 0; i < size; ++i) { int* p = numbers; // Pointer to the first element of the array
cout << A[i] << " ";
} p = p + 2; // Moves the pointer to the third element of the array
cout << endl; cout << "Address of p: "<< &p << " pointing to: "<< p << " have value
} at: "<<*p << endl;
type * pointer_name; cout << "Offset difference: " << n << endl; // should display 3
Here, type is the type of memory the pointer points to, and pointer_name is the name of the return 0;
pointer variable. }
#include <iostream>
Syntax to declare a structure variable
A structure can either be declared with a structure declaration or as a separate declaration
similar to basic types as follows:
int main() {
int* ptr = new int; // Structure variable declaration with structure declaration
*ptr = 42; struct Person {
int* ptr2 = ptr; int age;
string name;
// Deallocate memory, but the pointer still points to the same address } person1; // The variable person1 is declared with 'Person'
delete ptr;
std::cout << *ptr2 << std::endl; // Dangling pointer dereferencing // Structure variable declaration similar to basic data types
} struct Person {
int age;
string name;
}
Stack Heap int main() {
Person person1; // The variable person1 is declared like a normal
ptr
variable in the main function
D A V I D }
d
d is a dangling pointer
as it points to the Structs initialization
deleted array
Structure variables can be initialized at the time of declaration or later using assignment
statements. There are two methods that we can use to initialize them.
Direct initialization
Direct initialization is done via the curly bracket ({}) notation, which contains the initialized
Dangling pointer values.
#include <iostream>
#include <string.h>
Separate initialization
Separate initialization means assigning values to the structure variable members individually
after the structure variable is declared using the . (dot) operator.
int main()
{
char * ptr = new char[6] {'D', 'A','V', 'I', 'D'}; Person person;
std::cout << "ptr: " << ptr <<'\n';
person.age = 25;
ptr = new char[10]{'H', 'E','L', 'L', 'O',' ', 'C', '+', '+', '\0'}; person.name = "Educative";
std::cout << "ptr: " << ptr <<'\n';
}
return 0; person
age 25
Memory is allocated on the heap for the character array 'DAVID' using new, but the memory is
not deallocated before assigning a new memory block to the same pointer, ptr. name “Educative”
}
std::cout << "This should not be executed.";
Built-in math functions
Several math functions are present in C++. Some of them are as follows:
return 0; max:Returns the larger value among two values
} min:Returns the smaller value among two values
sqrt:Returns the square root of a number
ceil:Returns the value of the number rounded up to its nearest integer
Structs floor:Returns the value of the number rounded down to its nearest integer
Structs are user-defined data types that can be used to group items of possibly different types pow:Returns the value of num1 to the power of num2
into a single type.
Basics of Structs
Debugging: Identifying & Resolving Errors
Errors in programming are unexpected issues that disrupt the proper execution of a program.
The struct keyword creates a structure, and each of its members is declared inside curly
braces. The general syntax to create a structure is as follows: Syntax
These are also called compile-time errors. For example, in the code below, we are missing a
semicolon at the end of the cout statement, resulting in a syntax error.
struct structureName {
type1 myIntVar; // Member 1
type2 myStringVar; // Member 2 #include <iostream>
}
int main() {
// missing semicolon
A real example of a structure is as follows:
std::cout << "Geeks for geeks!"
Here a structure Person is defined which has two members: age and name.
C++ FOR ABSOLUTE BEGINNERS
Runtime
These are errors that occur during execution. An example can be dividing a number by 0.
#include <iostream>
int main() {
int x = 10;
int y = 0;
return 0;
}
Logical
Logical errors run without crashing but produce incorrect results even though syntax and other
factors are correct. For example, we perform integer division in the code below, and the result
will be an integer. Even though we store it in a float variable, the output will be 1 instead of
1.8.
#include <iostream>
int main() {
int num1 = 2, num2 = 3, num3 = 4;
float avg = (num1+num2+num3)/5; // this will store 1 in the avg variable
return 0;
}
Linker
Linker errors occur when the program is successfully compiled and attempts to link the
different object files with the main object file. These are generated when the executable of a
program cannot be generated. For example, if main() is written as Main(), a linked error will
be generated.
#include <iostream>
// main() is written as Main()
int Main() {
std::cout << "Educative";
return 0;
}
Semantic
Semantic errors occur when a statement is syntactically correct but has no meaning for the
compiler. For example, if an expression is entered on the left side of the assignment operator, a
semantic error may occur.
#include <iostream>
int main() {
int a = 10;
int b = 20;
int c;
return 0;
}