0% found this document useful (0 votes)
3 views

Cplusplus Abs Beginer

This document serves as a comprehensive introduction to C++ for absolute beginners, covering fundamental concepts such as variables, data types, operators, control structures, loops, arrays, and functions. It provides code examples for each topic, illustrating how to implement basic C++ syntax and operations. Additionally, it explains the importance of header files and comments in organizing and documenting code.

Uploaded by

vb_pol@yahoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Cplusplus Abs Beginer

This document serves as a comprehensive introduction to C++ for absolute beginners, covering fundamental concepts such as variables, data types, operators, control structures, loops, arrays, and functions. It provides code examples for each topic, illustrating how to implement basic C++ syntax and operations. Additionally, it explains the importance of header files and comments in organizing and documenting code.

Uploaded by

vb_pol@yahoo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

C++ FOR ABSOLUTE BEGINNERS

C++ Hello World Comparison operators


Example
Name Operator Output
#include <iostream> (x = 6, y = 2)

Equal to == x == y Evaluates to 0 (false)


because 6 is not equal to 2
int main() {
std::cout << "Hello World!"; Evaluates to 1 (true)
Not equal to != x != y because 6 is not equal to 2
return 0;
} Evaluates to 1 (true)
Greater than > x>y because 6 greater than 2

Getting Started with C++


Evaluates to 0 (false)
Less than < x<y because 6 is not less
than 2

Header Types Greater than or


equal to
>= x >= y
Evaluates to 1 (true)
because 6 is greater than
or equal to 2
Introduction to headers in C++ Less than or Evaluates to 0 (false)
<= x <= y because 6 is neither less
In C++, header files are crucial in organizing code, facilitating modularity, and promoting code equal to than or equal to 2
reusability. They typically contain declarations of functions, classes, and other constructs
without providing the full implementation. Logical operators
Common header files Example
Name Operator Output
Here are some commonly used header files: (x = 6)
Evaluates to 1 (true)
// Input and output operations Logical AND && x > 3 && x < 10 because 6 is greater than
3 AND 6 is less than 10
#include <iostream>
// Mathematical functions Evaluates to 1 (true)
because one of the
#include <cmath> Logical OR || x > 3 || x < 4 conditions are true (6 is
greater than 3, but 6 is
// String manipulation not less than 4)

#include <string>
// Dynamic array implementation Evaluates to 0 (false)
Logical NOT ! !(x > 3 && x < 10) because ! is used to
#include <vector> reverse the result

// File input and output


Assignment operators
#include <fstream>
Example
Name Operator (x = 6, y = 2) Output
Comments in C++
Add and assign += x += y 8
Single-line comment Subtract and
To indicate a single-line comment, use two forward slashes //. -= x -= y 4
assign
Multiply and
// This is a single-line comment *= x *= y 12
assign
std::cout << "Educative";
Divide and assign /= x /= y 3

Multiline comment Modulo and


assign
%= x %= y 0
To indicate a multiline comment, use /* to start a multiline comment and */ to end it. Exponent and
&= x &= y 2
assign
/* This is a multiline comment. Bitwise OR and
|= x |= y 6
The cout statement below will print Educative.*/ assign
Bitwise XOR and
std::cout << "Educative"; ^= x ^= y 4
assign
Right shift and
>>= x >>= y 1
Variables, Data Types, and Operators
assign
Left shift and
<<= x <<= y 24
assign
Understanding Variables
A variable is a named container that holds data. Conditional Statements
Based on certain conditions, users can control the flow of the program using conditional
int count = 10; // 'count' is a variable holding the value 10 statements.

Data Types The if statement


The if statement instructs the compiler to execute the block of code only if the condition
C++ supports various data types. holds true.

int integerVar = 5; // integer int num = 10;


float floatVar = 2.5; // float
if (num >= 8) {
char charVar = 'a'; // character std::cout << "The number is greater than 8." << std::endl;
double doubleVar = 1.2345; // double }

bool boolVar = false; // bool


The if-else statement
The if-else statement instructs the compiler to execute the if block only if the specified con-
Operators in C++ dition is true. Otherwise, it executes the else block.
Operators are symbols or keywords that perform operations on values or variables.
int num = 10;
Example
Name Operator Output
(x = 6, y = 2) if (num % 2 == 0) {
std::cout << "Even number." << std::endl;
Addition + x+y 8
}
else {
Subtraction - x-y 4 std::cout << "Odd number." << std::endl;
}
Multiplication * x*y 12

Division / x/y 3 Nested if statement


Nested if statements refer to an if statement inside another if statement.
Modulo % x%y 0
int x = 5, y = 3;
Increment ++ ++x 7 if (x > y) {
if (x > 0) {
Decrement -- --x 5 std::cout << "x is positive." << std::endl;
}
}

The else-if statement


The else-if statement allows us to check for multiple conditions sequentially.

int score = 60;

if (score >= 90) {


std::cout << "A grade" << std::endl;
}
else if (score >= 80) {
std::cout << "B grade" << std::endl;
}
else {
std::cout << "C grade" << std::endl;
}
C++ FOR ABSOLUTE BEGINNERS
Switch statement Arrays
A switch statement allows us to check an expression against multiple cases. If a match is found,
the code within that case is executed. A case can be ended with the break keyword. When no An array is a data structure that stores a fixed number of elements (which must be known at
case matches, the default case is executed. compile-time) of the same data type in contiguous memory locations.

int marks = 88; Basics of arrays


switch (marks/10) { Creation
case 10:
case 9: // Range of marks 90 - 100 // Declaring an array to store up to 5 integers
std::cout << "Perfect Grade!" << std::endl; int nums[5];
break;
case 8: // Declaring and initializing an array with values 1, 2, 3, 4, and 5
std::cout << "Good work!" << std::endl; int nums1[5]= {1, 2, 3, 4, 5};
break;
default: // Initializing an array with the values 1 and 2, and the remaining
std::cout << "Try working hard!" << std::endl; elements are set to 0
} int nums2[5] = {1,2};

Loops // Initializing an array with all elements set to 0


int nums3[5] = {0};
Loops are used to repeatedly execute a block of code multiple times.

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.

While loop #include <iostream>


The while loop repeatedly executes a block of code till a given condition is true. using namespace std;

int counter = 3; const int capacity = 100; // Maximum capacity of the array

while (counter > 0) { int main() {


std::cout << counter << std::endl; int Array[capacity] = {}; // Initialize array with all elements set to 0
counter--; int size; // To hold the size of the array, to be input by the user
}
cout << "Enter the size of the array (up to " << capacity << "): ";
cin >> size; // Input the size of the array
Do-while loop
The do-while loop is similar to the while loop. In the do-while loop, the condition is checked for(int i = 0; i < size; i++) {
after certain tasks have been performed, whereas in the while loop, the condition is checked Array[i] += 1;
first. }

int num; cout << "Array elements are:\n";


for(int i = 0; i < size; i++) {
do { cout << Array[i] << " "; // Output each element of the array
std::cout << "Enter a positive number: "; }
std::cin >> num; cout << endl;
} while (num <= 0);
// The output in the console is 1,1,1,1,1

Input and Output in C++


return 0;
}

Input using cin Access


We take input from the user using cin
int firstElement = nums[0]; // accessing the first element in the array
int age;
cin >> age; // Take input using cin
Iterations
Output using cout Example 1
We can print output to the console using cout
int sum = 0;
std::cout << "The age you entered is: " << age << std::endl; // Print
output to the console // loop over every element to calculate the sum of elements in an array
for (int i = 0; i < 5; i++) {
sum += nums[i];
Buffering }
Buffering refers to the storage and manipulation of data in a temporary location (buffer) before
it is processed or displayed. Buffers are used to efficiently handle input and output operations Example 2
by storing data in memory. In the example below, we read input characters one by one and
count the number of uppercase letters (‘A' to ‘Z') encountered until a period ('.'). The program #include <iostream>
aims to count the number of uppercase letters in the given input string.
int main() {
#include <iostream> int A[] = {1, 2, 3};
using namespace std;
// Iterate over each element 'r' of array 'A'
int main() // Using a range-based loop, increment each element by 1
{ for(int &r : A) {
int countCapAlphas = 0; r++; // Incrementing each element by 1
char sym; }

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}};

// Declaring a 2D array with 3 rows and 4 columns, and initializing it with


zero values for all elements
int 2dArray[3][4] = {};

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

Function syntax & structure Pointer Arithmetic


Pointer arithmetic refers to the mathematical operations performed on pointers. It allows us to
return_type function_name( parameter list ) { navigate through memory efficiently. Here’s an in-depth explanation of pointer arithmetic:
// Function body
// ...
// Translates to
// return statement (if applicable)
p++; // p = p + sizeof(Type);
}
p--; // p = p - sizeof(Type);
p+=2; // p = p + n*sizeof(Type);
return_type: The type of value being returned by the function int numbers[] = {1,2,3,4};
function_name: The name of the function int n = &numbers[3] - numbers[1]; // translates to (&(numbers[3] - &(num-
parameter: The input values to the function bers[1]))) / sizeof(Type)

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;

int main() { return 0;


int A[] = {1,2,3}; }
int sizeA = 3;
funWithArrays(A, sizeA); // 1,2,3

int B[] = {1,2,3,4};


Pointer subtraction
We can also subtract two pointers of the same type to determine the number of elements
int sizeB = 4;
between them. The result of the subtraction is divided by the size of the data type.
funWithArrays(B, sizeB); 1,2,3,4
}
#include <iostream>
using namespace std;
Pointers int main()
A pointer is a variable that stores the memory address of another variable. To create a pointer,
{
we use the type keyword followed by an asterisk (*) symbol followed by the name of the pointer
int numbers[] = {1, 2, 3, 4, 5};
variable.
int* p1 = &numbers[1]; // Pointer to the second element of the array
Basics of pointers int* p2 = &numbers[4]; // Pointer to the fifth element of the array

General syntax int n = p2 - p1;

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. }

Initialize memory address of a variable to a pointer


type *pointer_name = &variable_name;
// OR
pointer_name = &variable_name; // if pointer_name is already declared
C++ FOR ABSOLUTE BEGINNERS
Common Errors Declaring and Initializing a Structure Variable
A structure is simply a new data type that is user-defined. We must declare a variable of this
Dangling pointers data type to initialize its members and access them.
A dangling pointer is a pointer that points to a memory location that has been deallocated.

#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.

Memory leaks Person person = { 25, "Educative" };


Memory leaks occur when allocated memory is not properly deallocated.

#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”

Null pointer/illegal address dereferencing


A null pointer is a pointer that doesn’t point to a valid memory location. Dereferencing it or
attempting to access memory using an illegal address can lead to runtime errors and program
Accessing structure members
Structure members are accessed using the dot (.) operator.
crashes. Similarly, if a pointer is not initialized or explicitly set to a valid memory address,
dereferencing it can lead to undefined behavior.
#include <iostream>

#include <iostream> struct Person {


using namespace std; int age;
string name;
int main() { }
int* ptr;
int main() {
// Dereferencing a pointer with a garbage address will lead to undefined Person person1 = { 25, "Educative" };
behavior
*ptr = 10; // The program will crash // Accessing Struct Members
std::cout << "Age = " << person1.age << ", Name = " << person1.name;
ptr = nullptr;
return 0;
// Dereferencing a null pointer should lead to undefined behavior }
*ptr = 10; // The program will crash

ptr = new int;


C++ Built-In Toolbox
// Check if memory allocation was successful C++ provides a variety of built-in functions for common tasks such as mathematical operations,
if (ptr != nullptr) { string manipulation, etc.
*ptr = 42;
std::cout << "Dynamically allocated value: " << *ptr << std::endl; Built-in functions for strings
} Several string functions are present in C++ that are used to perform operations on strings.
Some of them are as follows:
// Deallocate the memory append:Appends a string at the end of the given string
delete ptr; length:Returns the length of a string
ptr = nullptr; empty:Used to check if a string is empty
substr:Extracts a substring from a given string
// Accessing the memory after deallocation compare:Compares two strings lexicographically
if (ptr != nullptr) {

}
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!"

struct Person { return 0;


int age; }
string name;
}

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;

int result = x / y; // Division by zero

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

std::cout<< avg << std::endl;

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;

// Semantic error here


a + b = c;

return 0;
}

You might also like