leaf leftleaf right

Getting Started

Before building your site, better take a look at this section.

Theme Installation

Extract the zipped package downloaded from ThemeForest to your desktop, in the extracted package you will find the gullu.zip file which is the WordPress theme.

You can install the theme in two ways:

FTP: Extract gullu.zip file and upload the extracted folder to /wp-content/themes/ folder on your server.

WordPress: Navigate to Appearance -> Add New Themes -> Upload page. Select gullu.zip file. Press the Install Now button to upload and install the theme.

After uploading the theme, you have to activate it. Navigate to Appearance -> Themes page to activate the theme.

Demo Import

If you want your site to look like exactly the ‘Gullu’ demos then you have to import the demo content successfully.

We integrated the One Click Demo installation feature to ‘Gullu’ WordPress theme. You can import all demo content just by a click only.

OneClick Demo Installation Process

  • Install the theme and activate it. Then install all the required plugins. Make sure all the required plugins are activated.
  • After activating all the required plugins navigate to Appearance > ‘One Click Demo Import’ menu from the WordPress dashboard.

Note: If the option data do not import then you have to import it manually. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

The recommended method to import the demo content.

If you failed to import the demo content by one click then you have to follow the below steps to import the demo content manually.  You will get all demo content data with the theme package. You will find the demos in ‘gullu>inc/demo{disired-demo-number} this path.

  • Navigate to Tools > Import then install the WordPress plugin and click on the ‘Run Importer’. Upload here the ‘theme_content.xml’ file.
  • Install the Widget Importer & Exporter plugin to import the demo widgets. Then navigate to Tools > Widget Importer & Exporter and upload here the ‘widget_data.wie’ file.
  • Now you have to import the Dental Options as like the demo. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

How to update premium plugins?

We have integrated some premium plugins with the theme and bundled those plugins with the theme. You don’t have to input your Themeforest product ID to unlock any theme features. We are not providing the third party plugin’s license along with the theme.

We are providing the plugins file only and we are continuously updating the bundled plugins with the theme updates. You can install/get those plugins on Appearance > Instal Plugins. Or you can get the plugin files in the rogan/inc/tgm/plugins folder.

Required Plugins

After installing the theme you most have to install the ‘Gullu Core’, ‘Visual composer’ and ‘Codestar Framework’ plugins to import the demo content as well and work the theme correctly.

You will find all required and recommended plugins at Appearance > Install Plugins.

Control blank space between rows

You can control the space between rows from the visual composer’s shortcode section settings.
Select the shortcode section from the Visual composer page edit screen (backend or frontend editor) that you want to control. Check the Styling tab from the visual composer’s element settings. Take a look at the below screenshot of it-
 
 
Note:  Input the padding (spaces around the section) as clockwise (Top Right Bottom Left)

Courses & Tutorials

Adel Nasim Youtube’s Courses

C++

Welcome to the World of C++ Programming!

Hello, I’m Adel Nasim, the creator of Adel Nasim YouTube Channel, and I’m excited to guide you through the essentials of C++ programming. Whether you’re a novice or looking to deepen your skills, this written course, alongside my YouTube tutorials, is your comprehensive resource for mastering C++. We’ll cover everything from the basics to advanced concepts, ensuring you gain both theoretical knowledge and practical coding skills.

Get ready for a journey that blends theory with hands-on examples, equipping you with the confidence to tackle real-world challenges. Whether you’re building your programming foundation or enhancing existing skills, let’s dive into the world of C++ together. Happy coding!

Introduction

C++ is a cross-platform programming language that can be used to create high-performance applications. It is a general-purpose language, which means it can be used to develop a wide variety of software, including operating systems, games, embedded systems, and more.

C++ is a popular choice for developing high-performance applications because it gives programmers a high level of control over system resources and memory. It is also a very efficient language, which means that C++ programs typically run faster than programs written in other languages.

C++ is a relatively complex language to learn, but it is also a very powerful language. Once you have mastered the basics of C++, you will be able to develop almost any type of software you can imagine.

Why is C++?

C++ is one of the most popular programming languages in the world for a reason. It is a powerful, versatile, and efficient language that can be used to create a wide variety of software.

Here are just a few of the reasons why C++ is so popular:

  • Performance: C++ programs are typically very fast and efficient. This is because C++ gives programmers a high level of control over system resources and memory.
  • Versatility: C++ can be used to develop a wide variety of software, from operating systems to games to embedded systems.
  • Portability: C++ programs can be compiled and run on a variety of platforms, including Windows, macOS, Linux, and more.
  • Community: C++ has a large and active community of developers. This means that there is a wealth of resources available to help you learn and use C++.

Difference between C and C++

C++ was developed as an extension of the C programming language. Both languages have a similar syntax, but C++ adds a number of new features, including:

  • Classes and objects: C++ supports classes and objects, which provide a way to encapsulate data and code into reusable units.
  • Templates: C++ templates allow you to create generic functions and classes that can be used with different data types.
  • Exception handling: C++ provides exception handling features that allow you to deal with errors in a structured way.

Get Started

If you are interested in learning C++, there are a number of resources available to help you get started. There are many good books and tutorials available online, and there are also a number of C++ communities where you can ask for help and advice.

Once you have learned the basics of C++, you can start developing your own applications. There are a number of different C++ compilers and development environments available, so you can choose the one that best suits your needs.

Conclusion

C++ is a powerful and versatile programming language that can be used to create a wide variety of software. It is a popular choice for developing high-performance applications, and it is also a good choice for beginners because it is relatively easy to learn.

Getting Started

What is C++?

C++ is a general-purpose programming language that is used to create a wide range of applications, including operating systems, games, embedded systems, and web applications. C++ is known for its speed, efficiency, and flexibility.

Getting started with C++

To get started with C++, you will need to install a C++ compiler and IDE. A compiler is a program that converts C++ code into machine code that can be executed by a computer. An IDE is an integrated development environment that provides a variety of tools for writing, editing, compiling, and debugging C++ code.

Installing a C++ compiler and IDE

There are many different C++ compilers and IDEs available. For this tutorial, we will use Visual Studio for C++. Visual Studio is a free and powerful IDE that provides comprehensive support for C++ development.

To install Visual Studio for C++, visit the Visual Studio website and download the latest version.

Writing your first C++ program

Once you have installed Visual Studio for C++, you can start writing your first C++ program. To do this, create a new project and select the “C++ Console App” template.

Once you have created a new project, you can start writing C++ code in the main source file. The main source file is typically named main.cpp.

Here is a simple example of a C++ program:

C++
#include <iostream>
int main() {
  std::cout << "Hello, world!" << std::endl;
  return 0;
}

This program prints the message “Hello, world!” to the console.

Once you have written your C++ program, you can compile and run it by pressing F5.

Learning more about C++

Now that you have written your first C++ program, you can start learning more about the language. There are many resources available online and in libraries.

Here are a few tips for learning C++:

  • Start with the basics. Learn about variables, data types, operators, functions, and control flow statements.
  • Find a good tutorial or book. There are many resources available that can teach you the basics of C++.
  • Practice regularly. The best way to learn C++ is by writing code. Try to write simple programs at first, and gradually work your way up to more complex programs.
  • Use an IDE. An IDE can make it easier to write, edit, compile, and debug C++ code.

Conclusion

Getting started with C++ can be daunting, but it is also rewarding. C++ is a powerful and versatile language that can be used to create a wide range of applications.

By following the tips in this guide, you can start learning C++ today and start creating your own applications.

First Project in C++

 

Example:

C++

#include <iostream>
int main()
{ 
    std::cout << "Welcome to C++";
    return 0;
}


This is a simple C++ program that prints the message “Welcome to C++” to the console.

  • #include <iostream>: This line tells the compiler to include the header file iostream. This header file contains declarations for the standard input/output library.
  • int main(): This line defines the main function. The main function is the entry point for all C++ programs.
  • std::cout << “Welcome to C++”;: This line prints the message “Welcome to C++” to the console using the std::cout object.
  • return 0;: This line returns the value 0 from the main function. This indicates that the program terminated successfully.

When you compile and run this program, the following output will be printed to the console:

Welcome to C++

This is a very simple example of a C++ program, but it illustrates some of the basic concepts of the language, such as header files, functions, and input/output.

Escape Sequence

Escape sequences are special characters that are used to represent non-printing characters or to control the behavior of output streams. They are prefixed with a backslash (\).

Types of Escape Sequences

There are three types of escape sequences in C++:

  • Character escape sequences: These escape sequences represent non-printing characters, such as newline, tab, and backspace.
  • Hexadecimal escape sequences: These escape sequences represent characters using their hexadecimal values.
  • Octal escape sequences: These escape sequences represent characters using their octal values.

Common Escape Sequences

Here are some of the most common escape sequences in C++:

Escape Sequence Description
\n Newline
\t Tab
\\ Backslash
\" Double quote
\' Single quote
\? Question mark
\a Alert
\b Backspace
\f Form feed
\r Carriage return
\v Vertical tab
\x Hexadecimal escape sequence
\NNN Octal escape sequence

Using Escape Sequences

Escape sequences can be used in string and character literals. For example, the following code prints the string “Hello, world!” followed by a newline character:

C++
std::cout << "Hello, world!" << std::endl;

The std::endl object represents the newline character. It is equivalent to the escape sequence \n.

Escape sequences can also be used to represent non-printing characters, such as the tab character. For example, the following code prints the string “Hello, world!” followed by a tab character:

C++
std::cout << "Hello, world!" << '\t';

Example

Here are some more examples of how to use escape sequences in C++:

C++
// Print the string "This is a quote \" inside a string." 
std::cout << "This is a quote \" inside a string."; 

// Print the character 'a' with a backspace before it. 
std::cout << '\b' << 'a';

// Print the string "Hello, world!" followed by a newline character and a tab character. 
std::cout << "Hello, world!" << std::endl << '\t';
Conclusion

Escape sequences are a powerful tool that can be used to control the behavior of output streams and to represent non-printing characters in C++.

Variables vs Data type

Variables vs Data types in C++

Variables

Variables are named memory locations that can store data. They are declared using the var_name : data_type syntax. For example, the following code declares a variable named my_integer that can store an integer value:

C++
int my_integer;

Once a variable is declared, it can be used to store and retrieve data. For example, the following code assigns the value 10 to the my_integer variable:

C++
my_integer = 10;

The following code prints the value of the my_integer variable to the console:

C++
std::cout << my_integer << std::endl;

Output:

10

Data types

Data types define the type of data that a variable can store. C++ has a variety of data types, including integers, floating-point numbers, characters, strings, and Boolean values.

Here are some examples of data types in C++:

  • int: Stores integer values
  • float: Stores floating-point numbers
  • char: Stores a single character
  • string: Stores a sequence of characters
  • bool: Stores a Boolean value (true or false)

When a variable is declared, it must be assigned a data type. This tells the compiler how much memory to allocate for the variable and what type of data it can store.

For example, the following code declares a variable named my_string that can store a string value:

C++
string my_string;

The string data type is a special data type that is used to store sequences of characters.

Example

Here is an example of how to use variables and data types in C++:

C++
int my_integer = 10;
float my_floating_point_number = 3.14159;
char my_character = 'a';
string my_string = "Hello, world!";
bool my_boolean_value = true;

// Print the values of the variables.
std::cout << my_integer << std::endl;
std::cout << my_floating_point_number << std::endl;
std::cout << my_character << std::endl;
std::cout << my_string << std::endl;
std::cout << my_boolean_value << std::endl;

Output:

10
3.14159
a
Hello, world!
true

Variables and data types are essential concepts in C++. By understanding how they work, you can write more efficient and effective code.

Priorities & Calculations in C++

C++ has a set of operator precedence rules that determine the order in which expressions are evaluated. Operators with higher precedence are evaluated before operators with lower precedence.

Here is a table of the operator precedence rules in C++:

Operator Group Operators
Parentheses ()[]{}
Unary operators +-!~*&++--sizeofcasttype-name
Multiplication, division, and modulus */%
Addition and subtraction +-
Bitwise AND &
Bitwise OR |
Bitwise XOR ^
Equality and inequality ==!=
Less than, less than or equal to, greater than, greater than or equal to <<=>>=
Logical AND &&
Logical OR ||
Assignment =+=-=*=/=%=&=, `
Conditional operator ? :
Comma ,

When evaluating an expression, operators with the highest precedence are evaluated first, followed by operators with lower precedence.

Here are some examples of how operator precedence works in C++:

// Evaluates to 13.
int x = 5 * 2 + 3;

// Evaluates to 11.
int y = 5 + 2 * 3;

// Evaluates to true.
bool z = 5 < 10 && 10 > 5;

// Evaluates to false.
bool w = 5 > 10 || 10 < 5;

It is important to be aware of operator precedence when writing C++ code. Otherwise, you may get unexpected results.

Here is another example of how operator precedence can be used to control the order of evaluation:

// Evaluates to 16.
int a = (5 + 3) * 2;

// Evaluates to 11.
int b = 5 + (3 * 2);

In the first expression, the addition operator (+) has higher precedence than the multiplication operator (*). Therefore, the addition operation is evaluated first, and then the multiplication operation is evaluated.

In the second expression, the multiplication operation has higher precedence than the addition operation. Therefore, the multiplication operation is evaluated first, and then the addition operation is evaluated.

By understanding operator precedence, you can write more concise and efficient C++ code.

Basic Arithmetic & Casting

Basic Arithmetic in C++

C++ provides a number of operators for performing basic arithmetic operations. These operators include:

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Modulo (remainder)

These operators can be used to perform arithmetic operations on variables of different data types. For example, the following code performs arithmetic operations on variables of type int and float:

int a = 10;
float b = 3.14159;

// Add two integers.
int c = a + 5;

// Multiply two floats.
float d = b * 2;

// Divide two integers.
float e = a / 2;

// Calculate the remainder of a division operation.
int f = a % 2;

The results of these operations are stored in the corresponding variables.

Casting in C++

Casting is a way to convert a value from one data type to another. This can be useful when you need to perform arithmetic operations on values of different data types.

There are two types of casting in C++:

  • Implicit casting: Implicit casting occurs when the compiler automatically converts a value from one data type to another. For example, the following code implicitly converts the value of the variable a from type int to type float before performing the multiplication operation:

 

int a = 10;
float b = 3.14159;

// Multiply an int and a float.
float c = a * b;
  • Explicit casting: Explicit casting is when the programmer explicitly converts a value from one data type to another. This can be done using the cast operators (static_castreinterpret_castconst_cast, and dynamic_cast). For example, the following code explicitly converts the value of the variable b from type float to type int before performing the division operation:

 

int a = 10;
float b = 3.14159;

// Divide a float by an int.
int c = static_cast<int>(b) / a;

Explicit casting is often used to prevent errors that can occur when implicitly casting values.

Example

Here is an example of how to use casting in C++:

// Convert a string to an integer.
int a = static_cast<int>("10");

// Convert a floating-point number to a character.
char b = static_cast<char>(3.14159);

// Convert a pointer to an integer to a pointer to a float.
float *c = reinterpret_cast<float*>(pInt);

// Convert a const object to a non-const object.
int *d = const_cast<int*>(pInt);

Casting can be a powerful tool for converting values between different data types. However, it is important to use it carefully to avoid errors.

Prefix and Postfix & Compound assignment

Prefix and postfix operators in C++

Prefix and postfix operators are used to modify the value of a variable. The prefix operator is used before the variable, while the postfix operator is used after the variable.

The following table shows some of the most common prefix and postfix operators in C++:

Operator Prefix Postfix
++ Increments the value of the variable by 1. Increments the value of the variable by 1, and returns the original value.
Decrements the value of the variable by 1. Decrements the value of the variable by 1, and returns the original value.

Example

The following code shows how to use the prefix and postfix operators to increment the value of a variable:

int a = 10;

// Increment the value of a by 1 using the prefix operator.
a++;

// Increment the value of a by 1 using the postfix operator.
int b = a++

// Print the values of a and b.
std::cout << a << " " << b << std::endl;

Output:

12 11

Compound assignment operators in C++

Compound assignment operators combine arithmetic operations with assignment operations. This makes it possible to modify the value of a variable in a single statement.

The following table shows some of the most common compound assignment operators in C++:

Operator Description Example
+= Adds the operand to the left operand x += 5; is equivalent to x = x + 5;
-= Subtracts the operand from the left operand y -= 3; is equivalent to y = y - 3;
*= Multiplies the operand with the left operand z *= 2; is equivalent to z = z * 2;
/= Divides the left operand by the operand a /= 4; is equivalent to a = a / 4;
%= Computes the modulo of the left operand and the operand b %= 7; is equivalent to b = b % 7;
&= Performs a bitwise AND operation on the left operand and the operand c &= 6; is equivalent to c = c & 6;
^= Performs a bitwise XOR operation on the left operand and the operand e ^= 8; is equivalent to e = e ^ 8;
<<= Shifts the left operand left by the number of bits specified by the operand f <<= 3; is equivalent to f = f << 3;
>>= Shifts the left operand right by the number of bits specified by the operand g >>= 2; is equivalent to g = g >> 2;

Example

The following code shows how to use compound assignment operators to modify the value of a variable:

int a = 10;

// Increment the value of a by 1 using the compound assignment operator.
a += 1;

// Print the value of a.
std::cout << a << std::endl;

Output:

11

Compound assignment operators can be a powerful tool for writing concise and efficient C++ code.

Variable Scope (Local vs Global)

Variable scope is a concept in programming that determines where a variable can be accessed from in a program. There are two types of variable scope in C++: local and global.

  • Local variables: Local variables are declared within a function or block of code. They can only be accessed from within the function or block of code in which they are declared.
  • Global variables: Global variables are declared outside of any function or block of code. They can be accessed from anywhere in the program.

Example of local variable scope:

int main() {
  int local_variable = 10;

  // local_variable can only be accessed from within this function.
  std::cout << local_variable << std::endl;

  // This code will cause an error because local_variable is not accessible here.
  std::cout << global_variable << std::endl;

  return 0;
}

Example of global variable scope:

int global_variable = 20;

int main() {
  // global_variable can be accessed from anywhere in the program.
  std::cout << global_variable << std::endl;

  // This code is also valid.
  int local_variable = global_variable;

  return 0;
}

It is important to be aware of variable scope when writing C++ code. Otherwise, you may accidentally access a variable that is not defined or that you are not supposed to access.

Here are some general rules for variable scope in C++:

  • Local variables are scoped to the function or block of code in which they are declared.
  • Global variables are scoped to the entire program.
  • Variables declared in a function can shadow variables declared in the global scope.
  • Variables declared in a block of code can shadow variables declared in the function scope.

By understanding variable scope, you can write more efficient and reliable C++ code.

Selection Statement - if Statement

Selection statements in C++ are used to control the flow of a program. They allow you to execute different blocks of code based on different conditions.

The two main selection statements in C++ are:

  • if statement: The if statement allows you to execute a block of code if a condition is true.
  • switch statement: The switch statement allows you to select one of multiple blocks of code based on the value of an expression.

In this section will know more about if statement.

Logical Operators

Logical operators in C++ are used to combine or modify Boolean expressions. They allow you to create more complex conditional statements.

The three logical operators in C++ are:

  • And (&&): Returns true if both of its operands are true. Otherwise, it returns false.
  • Or (||): Returns true if either of its operands is true. Otherwise, it returns false.
  • Not (!): Negates the value of its operand. If the operand is true, it returns false. Otherwise, it returns true.

Logical operators can be used to create more complex conditional statements. For example, the following code uses the && operator to check if a digit is in a specific range of numbers or not:

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    cout << "Enter a number";
    cin >> x;
    if (x >= 1 && x <= 100)
        cout << "Ok" << endl;
    else
        cout << "Out of range" << endl;

    return 0;
}

Another Example:

#include <iostream>

using namespace std;

int main()
{
    int a = 0;
    cout << "Enter your age";
    cin >> a;
    char g = '\0';
    cout << "Enter your gender";
    cin >> g;
    
    if (a < 18 && g == 'm')
        cout << "male, " << "young boy" << endl;
    else if (a >= 18 && g == 'm')
        cout << "male," << "grown up man" << endl;
    else if (a < 18 && g == 'f')
        cout << "female," << "young girl" << endl;
    else
        cout << "female," << "grown up girl" << endl;
    
    return 0;
}

Note : \0 in C++ is a null character. It is a character with all bits set to zero. It is used to mark the end of a string in C++.

The following code uses the || operator to check if a number is greater than 10 or less than 5:

#include <iostream>

using namespace std;

int main()
{
    int number = 3;

    if (number > 10 || number < 5) 
        cout << "The number is greater than 10 or less than 5." << endl;
    
    return 0;
}

The following code uses the ! operator to negate the value of the Boolean expression number > 10:

#include <iostream>

using namespace std;

int main()
{
    int number = 3;

    if (! (number > 10)) 
        cout << "The number is not greater than 10." << endl;
    
    return 0;
}

Logical operators can be used to create very complex conditional statements. However, it is important to use them carefully to avoid making your code difficult to read and maintain.

Here are some general rules for using logical operators:

  • Logical operators can be used to combine Boolean expressions to create more complex conditional statements.
  • The && operator returns true if both of its operands are true. Otherwise, it returns false.
  • The || operator returns true if either of its operands is true. Otherwise, it returns false.
  • The ! operator negates the value of its operand. If the operand is true, it returns false. Otherwise, it returns true.
  • Logical operators can be used in nested expressions.

By understanding how to use logical operators, you can write more efficient and reliable C++ code.

Selection Statement – Switch Statement

Selection statements in C++ are used to control the flow of a program. They allow you to execute different blocks of code based on different conditions.

The two main selection statements in C++ are:

  • if statement: The if statement allows you to execute a block of code if a condition is true.
  • switch statement: The switch statement allows you to select one of multiple blocks of code based on the value of an expression.

We explained “if statement” in “Selection Statement – if Statement” section, and now we are going to explain more about “switch statement”.

The switch statement in C++ is a control statement that allows you to execute different blocks of code based on the value of an expression. The general syntax of a switch statement is as follows:

switch (expression) {
  case value1:
    // code to execute if expression equals value1
  case value2:
    // code to execute if expression equals value2
  ...
  default:
    // code to execute if expression does not equal any of the values in the case statements
}

The expression can be any integer expression. The switch statement evaluates the expression and compares it to the values of the case statements. If the expression equals one of the values in the case statements, the code block inside that case statement is executed. If the expression does not equal any of the values in the case statements, the code block inside the default statement is executed.

Here is an example of a switch statement:

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    cin >> x;
    
    switch (x)
    {
        case 1: cout << "case #1" << endl;
            break;
        case 2: cout << "case #2" << endl;
            break;
        case 3: cout << "case #3" << endl;
            break;
        default:
            cout << "Out of range" << endl;
            break;
    }
    
    return 0;
}

You can also use characters instead of numbers in switch statement. For Example:

#include <iostream>

using namespace std;

int main()
{
    char c = 'a';
    
    switch (c)
    {
        case 'a': cout << "case #a" << endl;
            break;
        case 'b': cout << "case #b" << endl;
            break;
        default:
            cout << "Out of range" << endl;
            break;
    }
    
    return 0;
}

Output will be:

case #a

Remember!
Using a capital letter like ‘A’ in the previous example is not like using a small letter like ‘a’. They are not the same!

Benefits of using switch statements

Switch statements can be more efficient than using a series of if statements, especially when there are many different cases. Switch statements can also make your code more readable and maintainable.

Conclusion

Switch statements are a powerful tool for controlling the flow of your C++ program. By understanding how to use them, you can write more efficient and reliable code.

Repetition Statement

A repetition statement in C++ is a control statement that allows you to execute a block of code repeatedly until a certain condition is met. There are three types of repetition statements in C++:

  • while loop: The while loop executes a block of code repeatedly while a condition is true.
  • do-while loop: The do-while loop executes a block of code at least once, and then it evaluates a condition. If the condition is true, the code block is executed again.
  • for loop: The for loop executes a block of code a fixed number of times.

Repetition statements are a powerful tool for controlling the flow of your C++ program. They can be used to solve a variety of problems, such as:

  • Iterating over a collection of data
  • Performing a task a certain number of times
  • Waiting for a certain event to occur

Examples of loop break vs continue

break and continue are two flow control statements in C++ that can be used to alter the normal flow of a loop.

break terminates the loop immediately and unconditionally.

continue skips the rest of the current iteration of the loop and causes the loop to continue with the next iteration.

Here is an example of how to use continue in C++:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 0; i < 10; i++)
    {
        if (i == 5)
            continue;
        cout << "i = " << i << endl;
    }
    
    return 0;
}

This code is a for loop that prints the values of the variable i to the console, from 0 to 9, inclusive, except for the number 5. The if statement inside the loop checks if i is equal to 5. If it is, the continue statement skips the rest of the current iteration of the loop and causes the loop to continue with the next iteration.

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares a variable i and initializes it to 0.
  2. The program starts a for loop that iterates 10 times.
  3. Inside the for loop, the program checks if i is equal to 5.
  4. If i is equal to 5, the program skips the rest of the current iteration of the loop using the continue statement.
  5. Otherwise, the program prints the value of i to the console.
  6. The program then increments i by 1.
  7. The for loop repeats steps 3-6 until it has iterated 10 times.

Here is the output of this code:

i = 0
i = 1
i = 2
i = 3
i = 4
i = 6
i = 7
i = 8
i = 9

Here is an example of how to use break in C++:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 0; i < 10; i++)
    {
        if (i == 4)
            break;
        cout << "i = " << i << endl;
    }
    
    return 0;
}

This code is a for loop that prints the values of the variable i to the console, from 0 to 3, inclusive. The if statement inside the loop checks if i is equal to 4. If it is, the break statement terminates the loop immediately and unconditionally.

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares a variable i and initializes it to 0.
  2. The program starts a for loop that iterates 10 times.
  3. Inside the for loop, the program checks if i is equal to 4.
  4. If i is equal to 4, the break statement terminates the loop immediately and unconditionally.
  5. Otherwise, the program prints the value of i to the console.
  6. The program then increments i by 1.
  7. The for loop repeats steps 3-6 until it has iterated 10 times or until the loop is terminated by the break statement.

In this case, the loop will be terminated by the break statement when i is equal to 4. Therefore, the output of the code will be:

i = 0
i = 1
i = 2
i = 3

Which one to use?

Which one to use depends on what you want to achieve. If you want to terminate the loop immediately, use break. If you want to skip the rest of the current iteration of the loop and continue with the next iteration, use continue.

Here are some general tips for using break and continue:

  • Use break sparingly. Terminating a loop early can make your code more difficult to read and understand.
  • Use continue to avoid writing duplicate code. If you find yourself writing the same code inside a loop multiple times, consider using continue.
  • Use break and continue to make your code more efficient. For example, you can use break to terminate a loop early if you have already found what you are looking for.

Nested Loop

A nested loop is a loop that is contained within another loop. This means that the inner loop will iterate for each iteration of the outer loop.

Here is an example of a nested loop in C++:

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 1; i <= 5; i++)
    {
        for ( size_t j = 1; j <= 6; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

This code is a nested for loop that prints a rectangle of asterisks to the console. The outer loop iterates 5 times, and the inner loop iterates 6 times. This means that the code inside the inner loop will be executed 30 times.

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares two variables i and j, and initializes them to 1.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is less than or equal to 5. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is less than or equal to 6. If it is, the program prints an asterisk to the console.
  5. The inner for loop then increments j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is greater than 6.
  7. After the inner for loop has terminated, the program prints a newline character to the console.
  8. The outer for loop then increments i by 1.
  9. The outer for loop repeats steps 3-8 until i is greater than 5.

Here is the output of the code:

******
******
******
******
******

Nested loops can be used to solve a variety of problems. For example, you could use nested loops to iterate over all the elements of a two-dimensional array, or to generate all the possible combinations of two sets of values.

Here are some tips for using nested loops:

  • Use nested loops sparingly. Nested loops can make your code more difficult to read and understand.
  • Use nested loops to avoid writing duplicate code. If you find yourself writing the same code inside a loop multiple times, consider using nested loops.
  • Use nested loops to make your code more efficient. For example, you can use nested loops to avoid searching for an element in an array multiple times.

Draw shapes (Triangle)

You can use the logic of nested loops to create different shapes, for example a triangle.

This code is a nested for loop that prints a triangle of asterisks to the console. The outer loop iterates 5 times, and the inner loop iterates for each iteration of the outer loop.

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 1; i <= 5; i++)
    {
        for ( size_t j = 1; j <= i; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares two variables i and j, and initializes them to 1.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is less than or equal to 5. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is less than or equal to i. If it is, the program prints an asterisk to the console.
  5. The inner for loop then increments j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is greater than i.
  7. After the inner for loop has terminated, the program prints a newline character to the console.
  8. The outer for loop then increments i by 1.
  9. The outer for loop repeats steps 3-8 until i is greater than 5.

Here is the output of the code:

*
**
***
****
*****

What if we want to draw this triangle upside down?

We change the condition in our outer for loop.

This code is a nested for loop that prints an inverted triangle of asterisks to the console. The outer loop iterates from 5 to 1, inclusive, and the inner loop iterates for each iteration of the outer loop.

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 5; i >= 1; i--)
    {
        for ( size_t j = 1; j <= i; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares two variables i and j, and initializes them to 5 and 1, respectively.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is greater than or equal to 1. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is less than or equal to i. If it is, the program prints an asterisk to the console.
  5. The inner for loop then increments j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is greater than i.
  7. After the inner for loop has terminated, the program prints a newline character to the console.
  8. The outer for loop then decrements i by 1.
  9. The outer for loop repeats steps 3-8 until i is less than 1.

Here is the output of the code:

*****
****
***
**
*

Can we make it harder?

This code prints a right triangle of asterisks to the console. The outer loop iterates from 1 to 5, inclusive, and the inner loop iterates from 4 to i, inclusive, where i is the current iteration of the outer loop.

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 1; i <= 5; i++)
    {
        for ( size_t j = 4; j >= i; j--)
        {
            cout << " ";
        }
        for (size_t k = 1; k <= i; k++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares three variables ij, and k, and initializes them to 1, 4, and 1, respectively.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is less than or equal to 5. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is greater than or equal to i. If it is, the program prints a space to the console.
  5. The inner for loop then decrements j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is less than i.
  7. After the inner for loop has terminated, the program prints an asterisk to the console for each iteration of the inner for loop.
  8. The program then prints a newline character to the console.
  9. The outer for loop then increments i by 1.
  10. The outer for loop repeats steps 3-9 until i is greater than 5.

Here is the output of the code:

    *
   **
  ***
 ****
*****

Let’s print it upside down!

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 5; i >= 1; i--)
    {
        for ( size_t j = 4; j >= i; j--)
        {
            cout << " ";
        }
        for (size_t k = 1; k <= i; k++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Look what we have here as an output!

*****
 ****
  ***
   **
    *

Let’s draw a different triangle

#include <iostream>

using namespace std;

int main()
{
    int e = 1;
    for (int a = 1; a <= 5; a++)
    {
        for (int b = 4; b >= a; b--)
        {
            cout << " ";
        }
        for (int c = 0; c < e; c++)
        {
            cout << "*";
        }
        cout << endl;
        e = e + 2;
    }

    return 0;
}

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares four variables ea, c, and b, and initializes them to 1, 1, 0 and 4, respectively.
  2. The program starts the outer for loop.
  3. The outer for loop checks if a is less than or equal to 5. If it is, the inner for loop is executed.
  4. The inner for loop checks if b is greater than or equal to a. If it is, the program prints a space to the console.
  5. The inner for loop then decrements b by 1.
  6. The inner for loop repeats steps 4 and 5 until b is less than a.
  7. After the inner for loop has terminated, the program prints an asterisk to the console for each iteration of the inner for loop.
  8. The program then prints a newline character to the console.
  9. The outer for loop then increments a by 1.
  10. The outer for loop repeats steps 3-9 until a is greater than 5.

Here is the output of the code:

    *
   ***
  *****
 *******
*********

Let’s make it upside down:

#include <iostream>

using namespace std;

int main()
{
    int e = 9;
    for (int r = 1; r <= 5; r++)
    {
        for (int c = 0; c < e; c++)
        {
            cout << "*";
        }
        cout << endl;
        e = e - 2;
        for (int s = 0; s < r; s++)
        {
            cout << " ";
        }
    }

    return 0;
}

Output:

*********
 *******
  *****
   ***
    *

You can also use nested loops to draw other shapes, such as squares, rectangles, and diamonds.

Draw shapes (square), Draw any Letter Ex:( X,Z,N,E,F)

Nested loops in C++ are a powerful tool for drawing different shapes to the console. By using nested loops, we can iterate over multiple dimensions and print different characters to create different patterns.

Example 1:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 1; i <= 10; i++)
    {
        for (size_t j = 1; j <= 10; j++)
        {
            if (i == 1 || i == 10)
                cout << "*";
            else if (j == 1 || j == 10)
                cout << "*";
            else
                cout << " ";
        }
        cout << endl;
    }

    return 0;
}

This code prints a hollow square of asterisks to the console. The outer for loop iterates from 1 to 10, inclusive, and the inner for loop iterates from 1 to 10, inclusive.

The if statement inside the inner for loop checks if i is equal to 1 or 10, or if j is equal to 1 or 10. If any of these conditions are met, the program prints an asterisk to the console. Otherwise, the program prints a space to the console.

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares two variables i and j, and initializes them to 1.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is less than or equal to 10. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is less than or equal to 10. If it is, the program prints an asterisk to the console if i is equal to 1 or 10, or if j is equal to 1 or 10. Otherwise, the program prints a space to the console.
  5. The inner for loop then increments j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is greater than 10.
  7. After the inner for loop has terminated, the program prints a newline character to the console.
  8. The outer for loop then increments i by 1.
  9. The outer for loop repeats steps 3-8 until i is greater than 10.

Here is the output of the code:

**********
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
**********

Example 2:

If we want to print a letter like X to the console, expecting an output like this:

*   *
 * * 
  *  
 * * 
*   *

We need to set our logic.
To understand how we can put the asterisks in the previous shape, let’s present them this way:

/*
 1 2 3 4 5
1* * * * *
2* * * * *
3* * * * *
4* * * * *
5* * * * *
*/

Now let’s think about it looking at this shape, when the column meets the row we get a star, so we need a loop that goes through all the meeting points between every row and column and we need an if condition to specify our exact locations to make two diagonal lines cross forming our X letter shape.

all of this is represented in the following code:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 1; i <= 5; i++)
    {
        for (size_t j = 1; j <= 5; j++)
        {
            if (i == j || j == 6-i)
                cout << "*";
            else
                cout << " ";
        }
        cout << endl;
    }

    return 0;
}

Example 3:

By understanding how we asterisks are lined here:

/*
 1 2 3 4 5 
1* * * * * 
2* * * * * 
3* * * * * 
4* * * * * 
5* * * * * 
*/

We can think of multiple ways to manipulate our code producing different letters and shapes..

Look at this code:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 1; i <= 5; i++)
    {
        for (size_t j = 1; j <= 5; j++)
        {
            if (j == (6) - i || i == 1 || i == 5)
                cout << "*";
            else
                cout << " ";
        }
        cout << endl;
    }

    return 0;
}

Guess what this shape is?!

Output:

*****
   *
  *  
 *   
*****

Example 4:

Now let’s make our shape more complicated

**********
**      **
* *    * *
*  *  *  *
*   **   *
*   **   *
*  *  *  *
* *    * *
**      **
**********

Applying this code which is no different than previous examples

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 1; i <= 10; i++)
    {
        for (size_t j = 1; j <= 10; j++)
        {
            if (i == j || j == 11 - i || i == 1 || i == 10 || j == 1 || j == 10)
                cout << "*";
            else
                cout << " ";
        }
        cout << endl;
    }

    return 0;
}

 

Function Part 1

A function in C++ is a block of code that performs a specific task. Functions can be used to encapsulate common operations, making your code more reusable and easier to understand. Functions can also be used to improve the performance of your code by avoiding duplicate code.

To create a function in C++, you use the following syntax:

return_type function_name(parameter_list) {
  // Function body
}

The return_type specifies the type of data that the function will return. The function_name is the name of the function. The parameter_list is a list of parameters that the function will accept. The function_body is the code that the function will execute.

Here is an example of a simple function in C++:

int sum(int x, int y)
{
    int s = 0;
    s = x + y;
    return s;
}

This function takes two integer parameters, x and y, and returns the sum of those two parameters.

To call a function, you simply use its name followed by a pair of parentheses. For example, to call the sum() function, you would write:

int s = sum(10, 20);

This would assign the value 30 to the variable s.

The code could be written this way:

#include <iostream>

using namespace std;

int sum(int x, int y)
{
    int s = 0;
    s = x + y;
    return s;
}
int main()
{
    int s = 0;
    s = sum(10, 20);
    cout << "sum = " << s << endl;
    
    return 0;
}

The following example takes two float parameters and return the sum of them:

#include <iostream>

using namespace std;

float sum(float x, float y)
{
    float s = 0;
    s = x + y;
    return s;
}
int main()
{
    float s = 0;
    s = sum(20.5, 30.6);
    cout << "sum = " << s << endl;
    
    return 0;
}

Output:

sum = 51.1

The importance of using return:

We need to write a return in a function in C++ to specify the value that the function will return to the calling function. This is important because it allows us to use the function to perform calculations and then use the result of those calculations in our code.

Without the return statement, the function would not be able to return any value to the calling function. This would mean that we would not be able to use the function to perform calculations and then use the result of those calculations in our code.

By using the return statement, we can terminate the execution of the function early and avoid the error. This makes our code more robust and reliable.

Overall, the return statement is an important part of C++ programming. It allows us to return values from functions and to terminate the execution of functions early. This makes our code more reusable, efficient, and reliable.

But can we write a function without using return?

See this example:

#include <iostream>

using namespace std;

void print()
{
    cout << "myName" << endl;
}

int main()
{
    print();
    
    return 0;
}

This code defines a function called print() and a main function. The print() function simply prints the string “myName” to the console. The main function calls the print() function and then returns 0.

The print() function is declared with the void return type. This means that the function does not return any value. We use the void return type when we want a function to perform an action but not return any value.

When you run this code, the following output will be printed to the console:

myName

We use the void return type for the print() function because we only want it to print the string “myName” to the console. We do not need the function to return any value.

 

Functions can also be nested, meaning that one function can call another function. This can be useful for breaking down complex tasks into smaller, more manageable functions.

Functions are a powerful tool in C++ and can be used to improve the quality and performance of your code.

Here are some tips for using functions in C++:

  • Give your functions meaningful names. This will make your code more readable and easier to maintain.
  • Use functions to encapsulate common operations. This will make your code more reusable and easier to understand.
  • Use functions to improve the performance of your code by avoiding duplicate code.
  • Use functions to break down complex tasks into smaller, more manageable functions.

Function Part 2

Example 1:

#include <iostream>

using namespace std;

double avg(int m1, int m2, int m3) 
{
    return double(m1 + m2 + m3) / 3;
}

int main()
{
    int mm1, mm2, mm3;
    cout << "Enter your marks" << endl;
    cin >> mm1 >> mm2 >> mm3;
    cout << "avg = " << avg(mm1, mm2, mm3) << endl;
    
    return 0;
}

This code defines a function called avg(), which takes three integer parameters (m1, m2, and m3) and returns the average of those three parameters as a double value.

The function works by first converting the integer parameters to double values using the double() function. This is necessary because the average of three integers is a fractional number, and we want the function to return a double value.

Next, the function calculates the sum of the three parameters and divides that sum by 3. This gives us the average of the three parameters.

Finally, the function returns the average value.

The program works as follows:

  1. The program declares three integer variables mm1mm2, and mm3 to store the marks entered by the user.
  2. The program prompts the user to enter their marks and reads the marks into the three variables.
  3. The program calls the avg() function to calculate the average of the three marks.
  4. The program prints the average to the console.

Example 2:

#include <iostream>

using namespace std;

int max(int n1, int n2, int n3) 
{
    int mx = n1;
    if (mx < n2)
        mx = n2;
    if (mx < n3)
        mx = n3;
    return mx;
}

int min(int n1, int n2, int n3) 
{
    int mn = n1;
    if (mn > n2)
        mn = n2;
    if (mn > n3)
        mn = n3;
    return mn;
}

int main()
{
    cout << "max = " << max(100, 200, 300) << endl;
    cout << "min = " << min(100, 200, 300) << endl;
    
    return 0;
}

This code defines two functions called max() and min()which both take three integer parameters (n1, n2, and n3) and returns the largest and the smallest of those three parameters.

The first function works by first initializing a variable called mx to the value of the first parameter, n1. Then, the function checks if mx is less than the second parameter, n2. If it is, the function assigns the value of n2 to mx. Next, the function checks if mx is less than the third parameter, n3. If it is, the function assigns the value of n3 to mx. Finally, the function returns the value of mx, which is the largest of the three parameters.

The second function works by first initializing a variable called mn to the value of the first parameter, n1. Then, the function checks if mn is greater than the second parameter, n2. If it is, the function assigns the value of n2 to mn. Next, the function checks if mn is greater than the third parameter, n3. If it is, the function assigns the value of n3 to mn. Finally, the function returns the value of mn, which is the smallest of the three parameters.

Here is the output of the program:

min = 100
max = 300

There are two ways to define a function in a C++ program:

  1. Function declaration: This is a prototype of the function that tells the compiler about the function’s name, return type, and parameters. The function declaration must be placed before the first call to the function.
  2. Function definition: This is the actual code that implements the function. The function definition can be placed anywhere in the program, but it is generally placed at the end of the program.

For example, here is a function declaration and definition:

// Function declaration
int add(int a, int b);

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

The function declaration tells the compiler that there is a function called add() that takes two integer parameters and returns an integer value. The function definition provides the actual code that implements the function.

You can also arrange function declarations and definitions in different ways in your code. For example, you can:

  • Declare all of your functions at the beginning of your program and then define them at the end of your program.
  • Declare and define your functions in the order that they are called in your program.
  • Declare your functions in a header file and define them in a source file.

The best arrangement for your code will depend on the specific needs of your program.

Here is an example of how to use function declarations and definitions in a C++ program:

// Function declaration
int add(int a, int b);

int main() {
  // Function call
  int sum = add(1, 2);

  // Print the sum
  cout << "The sum is: " << sum << endl;

  return 0;
}

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

Of course you should pay a massive attention to the sequential arrangement of your program.

The sequential arrangement of functions in a C++ program is important for two main reasons:

  • Readability: A well-organized program is easier to read and understand. By arranging functions in a logical order, you can make it easier for other programmers to follow the flow of your code.
  • Maintainability: A well-maintained program is easier to update and fix bugs in. By arranging functions in a logical order, you can make it easier to find and fix problems in your code.

Note !

The main function is the entry point for all C++ programs. It is the first function that is called when the program is executed. The main function is responsible for initializing the program, calling other functions, and returning a value to the operating system.

The main function is important for several reasons:

  • It is the starting point for the program execution.
  • It is responsible for initializing the program.
  • It controls the flow of the program by calling other functions.
  • It returns a value to the operating system when the program terminates.

Without the main function, the program would not be able to start executing.

Here is an example of a simple main function in C++:

int main() {
  // Initialize the program
  // ...

  // Call other functions
  // ...

  // Return a value to the operating system
  return 0;
}

This main function initializes the program, calls other functions, and returns a value of 0 to the operating system.

You can use the main function to control the flow of your program by calling other functions. For example, you could write a function to calculate the sum of two numbers and then call that function from the main function.

You can also use the main function to return a value to the operating system. This value is used to indicate whether the program terminated successfully or not.

The main function is a very important part of any C++ program. It is the starting point for the program execution, and it controls the flow of the program.

Example 3:

#include <iostream>

using namespace std;

int avg(int x, int y, int z)
{
    return (x + y + z) / 3;
}

void print()
{
    cout << "Hello" << endl;
}

void xy()
{
    cout << 5 * 10 << endl;
}

int main()
{
    cout << "Nothing" << endl;
    return 0;
}

int f2()
{
    return 5;
}

This code defines four functions: avg(), print(), xy(), and f2(). The avg() function takes three integer parameters and returns the average of those three parameters. The print() function prints the string “Hello” to the console. The xy() function prints the product of 5 and 10 to the console. The f2() function returns the integer 5.

The main function in the code simply prints the string “Nothing” to the console and then returns 0.

When you run this code, the following output will be printed to the console:

Nothing

This is because the only function that is called from the main function is the cout << "Nothing" << endl; statement.

You can use the other functions in the code by calling them from the main function or from other functions.

Function part 3 (built in functions)

Built-in functions in C++ are functions that are provided by the compiler and are available to use in any C++ program. These functions are typically used for common tasks such as input/output, mathematical operations, and string manipulation.

ere are some of the most common built-in functions in C++:

  • Mathematical functions:
    • abs(): Returns the absolute value of a number.
    • sqrt(): Calculates the square root of a number.
    • pow(): Raises a number to a power.
    • sin(): Calculates the sine of an angle in radians.
    • cos(): Calculates the cosine of an angle in radians.
    • tan(): Calculates the tangent of an angle in radians.
    • floor(): Returns the greatest integer less than or equal to a number.
    • ceil(): Returns the smallest integer greater than or equal to a number.
  • String manipulation functions:
    • strlen(): Returns the length of a string.
    • strcpy(): Copies one string to another string.
    • strcat(): Concatenates two strings.
    • strcmp(): Compares two strings and returns an integer value indicating whether they are equal, less than, or greater than each other.
  • Input/output functions:
    • cin: Reads data from the standard input stream.
    • cout: Writes data to the standard output stream.
    • cerr: Writes data to the standard error stream.
    • fopen(): Opens a file for reading or writing.
    • fclose(): Closes a file.

Example 1:

cout << sqrt(18) << endl;

Output:

4.24264

Example 2:

cout << abs(-18) << endl;

Output:

18

Example 3:

cout << mod(10.5,2) << endl;

Output:

0.5

Example 4:

cout << floor(10.2) << endl;

Output:

10

Example 5:

cout << floor(-10.2) << endl;

Output:

-11

Example 6:

cout << ceil(10.2) << endl;

Output:

11

Example 6:

#include <iostream>

using namespace std;

int main()
{
    cout << sqrt(abs(pow(-3,2))) << endl;

    return 0;
}

To use a built-in function, you simply need to include the appropriate header file. So you might have a problem executing this program. you would need to include the <cmath> header file.

The <cmath> header file contains declarations for a number of mathematical functions, such as sqrt(), pow(), sin(), cos(), and tan(). These functions are useful for performing common mathematical operations, such as calculating the square root of a number, raising a number to a power

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    cout << sqrt(abs(pow(-3,2))) << endl;

    return 0;
}

Output:

3

Example 7:

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

int main()
{
    cout << max(10,5) << endl;

    return 0;
}

You would need to include the <algorithm> header file to use any of the algorithms provided by the C++ standard library. These algorithms include sorting, searching, merging, and many more.

Output:

10

Example 8:

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

int main()
{
    cout << max(15,max(10,5)) << endl;

    return 0;
}

Output:

15

Example 9:

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

int main()
{
    
    int x = 0, y = 10;
    swap(x,y);
    cout << "x= " << x << "y= " << y << endl;

    return 0;
}

Output:

x= 10y= 0

Built-in functions can be a very useful tool for C++ programmers. By using built-in functions, you can avoid having to write your own code for common tasks.

 

 

Function part 4 (Random functions)

Random functions in C++ are used to generate random numbers. There are two built-in random functions in C++: rand() and srand().

The rand() function generates a random integer between 0 and RAND_MAX, where RAND_MAX is a macro that is defined in the cstdlib header file. The srand() function is used to seed the random number generator. If you don’t call srand(), the random number generator will be seeded with a default value.

Example 1:

#include <iostream>
#include <cstdlib>

using namespace std;
int main()
{
    
    cout << rand() << endl;
    
    return 0;
}

This code prints a random integer to the console.

Example 2:

#include <iostream>
#include <cstdlib>

using namespace std;
int main()
{
    for (size_t i = 0; i < 10; i++)
    {
        cout << rand() << endl;
    }
    
    return 0;
}

This code is a for loop that prints 10 random integers to the console.

Example 3:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    for (size_t i = 0; i < 10; i++)
    {
        cout << rand()%10 << endl;
    }
    
    return 0;
}

This code generates a random number between 0 and 9 and prints it to the console. The modulus operator (%) returns the remainder of a division operation. So, the expression rand()%10 will return the remainder of the operation rand() / 10. This will give us a number between 0 and 9.

Example 4:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    for (size_t i = 1; i <= 10; i++)
    {
        cout << rand()%(30 - 20 + 1) + 20 << endl;
    }
    
    return 0;
}

This code generates a random number between 20 and 30 and prints it to the console.

Example 5:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(0));
    for (size_t i = 1; i <= 10; i++)
    {
        cout << rand()%(30 - 20 + 1) + 20 << endl;
    }
    
    return 0;
}

The srand(time(0)); function seeds the random number generator with the current time. This ensures that the random numbers are different each time the program is run.

The srand() function takes an integer seed as its argument and initializes the random number generator with that seed. The time(0) function returns the current time as a time_t value, which is an integer.

By seeding the random number generator with the current time, we are using a value that is constantly changing, which ensures that the random numbers are different each time the program is run.

It is important to seed the random number generator before using the rand() function. If you do not seed the random number generator, it will be seeded with a default value, which will result in the same sequence of random numbers being generated each time the program is run.

Example 6:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int x, y;
    x = time(0);
    for (size_t i = 0; i < 10000; i++)
    {
        cout << time(NULL) << endl;
        y = time (0);
    }
    cout << "The token time:" << y - x << endl;
    return 0;
}

This code prints the current time 10000 times to the console and then prints the total time it took to do so.

The program works as follows:

  1. The int x, y; declaration creates two integer variables, x and y.
  2. The x = time(0); statement assigns the current time to the variable x.
  3. The for (size_t i = 0; i < 10000; i++) loop iterates 10000 times.
  4. On each iteration of the for loop, the following code is executed:
    • The current time is printed to the console using the cout << time(NULL) << endl; statement.
  5. The y = time(0); statement assigns the current time to the variable y.
  6. The cout << "The token time:" << y - x << endl; statement prints the total time it took to print the current time 10000 times to the console.

The time(NULL) function is a synonym for the time(0) function.

You can use this code to measure the performance of your code or to calculate the elapsed time between two events.

Function part 5 (Call By Reference vs Call By Value)

Call by value and call by reference are two different ways to pass arguments to functions in C++.

Call by value is the default passing mechanism in C++. When a function is called by value, a copy of the actual argument is passed to the function. The function then operates on this copy, and any changes made to the copy inside the function will not be reflected in the actual argument outside the function.

Call by reference allows you to pass the reference of the actual argument to the function. This means that the function operates directly on the actual argument outside the function. Any changes made to the argument inside the function will be reflected in the actual argument outside the function.

To pass an argument by reference, you need to use the & operator before the argument name

For example, the following code shows how to call a function by value:

#include <iostream>
using namespace std;

void swap(int x, int y)
{
    int z = x;
        x = y;
        y = z;
}

int main()
{
    int x = 10, y = 20;
    swap(x, y);
    cout << "x= " << x << " y= " << y << endl;
    
    return 0;
}

//x= 10 y= 20

The following code shows how to call the same function by reference:

#include <iostream>
using namespace std;

void swap(int&x, int&y)
{
    int z = x;
        x = y;
        y = z;
}

int main()
{
    int x = 10, y = 20;
    swap(x, y);
    cout << "x= " << x << " y= " << y << endl;
    
    return 0;
}

//x= 20 y= 10

As you can see, the result of calling the swap() function is different depending on whether it is called by value or by reference.

Call by reference is often used to modify the values of the arguments outside the function. For example, the swap() function could be used to swap the values of two variables.

Call by reference can also be used to pass large objects to functions without having to copy them. This can improve the performance of your program.

However, it is important to use call by reference carefully, as it can lead to unexpected results if not used correctly. For example, if you pass a reference to a local variable to a function, and the function returns, the local variable will go out of scope, but the reference to it will still be valid. This can lead to a program crash if you try to access the local variable through the reference.

In general, it is best to use call by value unless you have a specific reason to use call by reference.

For example, the following code shows how to call a function by value:

#include <iostream>
using namespace std;

void fun(int x, int y)
{
    x += 1;
    y += 2;
}
int main()
{
    int k = 50, r = 10;
    fun(k, r);
    cout << "K= " << k << " R= " << r << endl;
    
    return 0;
}

//K= 50 R= 10

The following code shows how to call the same function by reference:

#include <iostream>
using namespace std;

void fun(int&x, int&y)
{
    x += 1;
    y += 2;
}
int main()
{
    int k = 50, r = 10;
    fun(k, r);
    cout << "K= " << k << " R= " << r << endl;
    
    return 0;
}

//K= 51 R= 12

As you can see, the result of calling the fun() function is different depending on whether it is called by value or by reference.

Function part 6 (Recursion 1)

Recursion is a programming technique where a function calls itself directly or indirectly. This can be used to solve problems that can be broken down into smaller, simpler problems of the same type.

Recursion can be a bit difficult to understand at first, but it is a powerful tool that can be used to solve a wide variety of problems.

Here is a simple example of a recursive function in C++:

#include <iostream>
using namespace std;
void f(int n)
{
    if (n < 1)
        return;
    else
        cout << "round:" << n << endl;
    f(n - 1);
}

int main()
{
    f(5);
    return 0;
}

The function f(int n) is a recursive function that prints the string “round:” followed by the integer n to the console n times.

The function works by recursively calling itself to print the string “round:” followed by the integer n - 1 to the console. This process continues until n is equal to 1, at which point the function returns.

Output:

round: 5
round: 4
round: 3
round: 2
round: 1

Recursive functions can be a bit difficult to understand at first, but they are a powerful tool that can be used to solve a wide variety of problems.

You should pay attention to these 3 contents of a recursive function (base case, logic and subproblem), which are marked in the following function:

void f(int n)
{
    if (n < 1)
        return; //base case
    else
        cout << "round:" << n << endl; //logic
    f(n - 1); //subproblem
}

The three contents of a recursive function are:

  • Base case: The base case is a special case that is handled directly in the function without making any recursive calls. The base case is usually a simple case that can be solved directly.
  • Logic: The logic of a recursive function is the code that is executed to break down the problem into smaller, simpler problems of the same type. The logic usually involves making recursive calls to the function with smaller input values.
  • Subproblem: A subproblem is a smaller, simpler problem of the same type as the original problem. Recursive functions work by breaking down the original problem into subproblems and then solving the subproblems using the same recursive function.

Here is an example of a recursive function in C++ that calculates the factorial of a number:

#include <iostream>
using namespace std;
int fact(int n)
{
    if (n == 0 || n == 1)
        return 1;
    else
        return n*fact(n - 1);
}

int main()
{
    cout << fact(5) << endl;
    return 0;
}

The function fact(int n) is a recursive function that calculates the factorial of a number. The factorial of a number is the product of all the positive integers less than or equal to that number. For example, the factorial of 5 is 120, because 120 is the product of 1, 2, 3, 4, and 5. So, the  output of our program will be 120.

The function fact(int n) works by recursively calling itself to calculate the factorial of the number one less than the input number. For example, to calculate the factorial of 5, the function would first call itself to calculate the factorial of 4. This would then call itself to calculate the factorial of 3, and so on. Eventually, the function would reach the base case, where the input number is 0 or 1. The base case is a special case that is handled directly in the function without making any recursive calls. The factorial of 0 is 1 and the factorial of 1 is also 1, so the function simply returns 1 in these cases.

Fibonacci Series

The Fibonacci sequence is a series of numbers where each number is the sum of the two previous numbers. The first two numbers in the sequence are 0 and 1, and each subsequent number is the sum of the previous two numbers.

Here is the Fibonacci sequence up to the first 10 numbers:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The Fibonacci sequence can be generated using the following recurrence relation:

F(n) = F(n - 1) + F(n - 2)

where F(n) is the nth number in the Fibonacci sequence.

The Fibonacci sequence has a number of interesting properties. For example, the ratio of successive Fibonacci numbers approaches the golden ratio as the numbers get larger. The golden ratio is an irrational number that is approximately equal to 1.618.

The Fibonacci sequence appears in many different areas of mathematics and nature. For example, it can be used to model the growth of a population of rabbits, the spiral pattern of a seashell, and the branching pattern of a tree.

Here are some examples of how the Fibonacci sequence is used in the real world:

  • Finance: The Fibonacci sequence can be used to identify potential support and resistance levels for stock prices.
  • Music: The Fibonacci sequence can be used to create musical compositions with a pleasing rhythm and structure.
  • Art: The Fibonacci sequence can be used to create works of art with a balanced and harmonious composition.
  • Architecture: The Fibonacci sequence can be used to design buildings and other structures that are aesthetically pleasing and structurally sound.

The Fibonacci sequence is a fascinating and versatile mathematical sequence that has many applications in the real world.

Example:

#include <iostream>
using namespace std;
int fib(int n)
{
    if (n == 0 || n == 1)
        return n;
    else
        return fib(n - 1) + fib(n - 2);
}

int main()
{
    cout << fib(3) << endl;
    return 0;
}

The function fib(int n) works by recursively calling itself to calculate the Fibonacci numbers of the previous two numbers. If the input number n is 0 or 1, the function simply returns the number, because the first two Fibonacci numbers are 0 and 1. Otherwise, the function returns the sum of the Fibonacci numbers of the previous two numbers.

Output:

2

 

Function part 7 (Recursion 2)

Example 1:

#include <iostream>
using namespace std;
int sum(int n)
{
    if (n == 1)
        return 1;
    else
        return n + sum(n - 1);
}

int main()
{
    cout << sum(5) << endl;
    return 0;
}

This function calculates the sum of the first n natural numbers. The first n natural numbers are the numbers from 1 to n.

The function works by recursively calling itself to calculate the sum of the first n - 1 natural numbers. If the input number n is 1, the function simply returns the number 1, because the sum of the first natural number is 1. Otherwise, the function returns the sum of the input number n and the sum of the first n - 1 natural numbers.

Output:

15

Example 2:

#include <iostream>
using namespace std;
int sum(int x, int y)
{
    if (x == y)
        return x;
    else
        return y + sum(x, y - 1);
}

int main()
{
    cout << sum(4, 6) << endl;
    return 0;
}

This is a recursive function sum. It takes two integer parameters, x and y, which represent the range of numbers to sum. Here’s how the function works:

  • The base case: If x is equal to y, it means we have reached the end of the range, so it returns x. This is the terminating condition for the recursion.
  • The recursive case: If x is not equal to y, it adds the current value of y to the result of calling the sum function again with the same x and y-1. This effectively breaks down the sum of the range into smaller subproblems by reducing the upper bound (y) by 1 in each recursive call.

n the main function, it calls the sum function with the arguments 4 and 6 and then outputs the result to the console using cout. In this case, it will calculate the sum of integers from 4 to 6 (inclusive) and print the result.

When you run this code, it will output the sum of integers from 4 to 6, which is 4 + 5 + 6 = 15. So, the output of this code will be:

15

Function part 8 (Overloading Function)

Function overloading is a feature of C++ that allows you to have two or more functions with the same name, as long as they have different parameters. This can be useful when you want to have a single function that can perform different tasks, depending on the type of data that is passed to it as an argument.

For example, this code is a set of three C++ functions that print different types of data to the console.

#include <iostream>
using namespace std;

void print(int a)
{
    cout << "Integer = " << a << endl;
}
void print(float a)
{
    cout << "Float = " << a << endl;
}
void print(char c)
{
    cout << "Character = " << c << endl;
}

int main()
{
    print(1);
    print('a');
    return 0;
}

The first function, print(int a), takes an integer as an argument and prints it to the console with the prefix “Integer = “.

The second function, print(float a), takes a floating-point number as an argument and prints it to the console with the prefix “Float = “.

The third function, print(char c), takes a character as an argument and prints it to the console with the prefix “Character = “.

Output:

Integer = 1
Character = a

 

Function part 9 (Default arguments)

Default arguments are a feature of C++ that allows you to specify a default value for a function parameter. This means that if a caller of the function does not provide a value for a particular parameter, the default value will be used instead.

Default arguments can be useful for simplifying the code that calls a function, and for making the function more flexible. For example, you could have a function that takes two parameters, but where the second parameter is optional. You could then specify a default value for the second parameter, so that callers of the function do not have to provide a value for it if they do not want to.

Here is an example of how to use default arguments in C++:

#include <iostream>
using namespace std;

int sum(int a = 5, int b = 5, int c = 5)
{
    return a + b + c;
}

int main()
{
    cout << sum(10, 55) << endl;
    return 0;
}

The code you provided is a C++ program that calculates the sum of three integers. The program uses default arguments to provide default values for the three integers. This means that if the caller of the sum() function does not provide values for all three integers, the default values will be used instead.

The main() function calls the sum() function with the arguments 10 and 55. The sum() function will then return the sum of the three integers, which is 70. The main() function will then print the result to the console.

Output:

70

Here are some tips for using default arguments:

  • Do not write your default argument in the middle of two arguments like this (int a, int b = 5, int c), it will produce an error to the compiler.
  • Be careful not to overwrite default parameters with values that are not valid for the function.
  • Use default parameters to provide default values for parameters that are not essential to the function’s functionality.

Function part 10 (Inline Function)

An inline function in C++ is a function whose code is substituted at the point of call. This means that the compiler copies the code of the inline function into the calling function, instead of generating a call instruction.

Inline functions are typically used for small functions that are frequently called. This can improve the performance of the program, as it eliminates the overhead of function calls.

To declare an inline function in C++, you use the inline keyword before the function declaration. For example:

#include <iostream>
using namespace std;

inline void p()
{
    cout << "hello" << endl;
}

int main()
{
    p();
    p();
    p();
    return 0;
}

inline void p(), defines an inline function called p(). The function takes no arguments and simply prints the word “hello” to the console, followed by a newline character.

The three lines, p();, p();, and p();, call the p() function three times.

When the program is executed, the following output will be printed to the console:

hello
hello
hello

It is important to note that the compiler is not obligated to inline a function, even if it is declared as inline. The compiler may choose not to inline a function if it is too large or if it is called indirectly.

Here are some of the benefits of using inline functions:

  • Improved performance: Inline functions can improve the performance of a program by eliminating the overhead of function calls.
  • Reduced code size: Inline functions can reduce the code size of a program by removing the need to generate separate code for each function call.
  • Increased readability: Inline functions can make code more readable by eliminating the need to jump back and forth between different functions.

However, there are also some potential drawbacks to using inline functions:

  • Increased compile time: Inlining functions can increase the compile time of a program, as the compiler needs to copy the code of the inline function into each calling function.
  • Increased code size: If an inline function is called frequently, it can increase the code size of the program.
  • Reduced maintainability: Inline functions can make code more difficult to maintain, as the code for the inline function is scattered throughout the program.

Overall, inline functions can be a useful tool for improving the performance and readability of code. However, it is important to use them carefully, as they can also increase the compile time and code size of a program.

Here are some tips for using inline functions effectively:

  • Only inline small functions that are frequently called.
  • Avoid inlining functions that are too large or that are called indirectly.
  • Use the inline keyword consistently, so that the compiler can make informed decisions about whether or not to inline a function.
  • Document your code clearly, so that other developers understand how and why inline functions are being used.

Static variable

A static variable in C++ is a variable that is allocated once and remains in memory throughout the execution of the program. Static variables can be declared at global scope, namespace scope, class scope, or function scope.

Static variables at global scope are initialized when the program starts and are destroyed when the program ends. Static variables at namespace scope are initialized when the namespace is loaded and are destroyed when the namespace is unloaded. Static variables in classes are initialized when the class is first used and are destroyed when the program ends. Static variables in functions are initialized when the function is first called and are destroyed when the function returns.

Static variables can be useful for a variety of purposes, such as:

  • Storing global state information: Static variables can be used to store global state information that needs to be accessed by multiple functions in a program.
  • Implementing singletons: Static variables can be used to implement singletons, which are classes that can only have one instance.
  • Implementing lazy initialization: Static variables can be used to implement lazy initialization, which is a technique for delaying the initialization of a variable until it is first used.

Here is an example of a static variable declared in a function:

#include <iostream>
using namespace std;

void fun()
{
    static int x = 0;
    x++;
    cout << x << endl;
}

int main()
{
    fun();
    fun();
    return 0;
}

This code is a C++ program that defines a function called fun() and then calls it twice from the main() function. The fun() function declares a static variable called x and increments it each time it is called. The function then prints the value of x to the console.

Because x is a static variable, its value is preserved between function calls. This means that when the fun() function is called the second time, the value of x will be 1, not 0. Therefore, the output of the program will be as follows:

1
2

This code demonstrates how static variables can be used to store state information that needs to be accessed by multiple function calls.

Aliasing & Constant Variable

Aliasing

Aliasing in C++ is when two or more different names refer to the same memory location. This can happen when you use pointers or references, or when you declare two variables of the same type and initialize them to the same value.

For example, the following code creates an alias to the variable x:

int x = 1;
int &y = x;

Now, both the variables x and y refer to the same memory location. If you change the value of x, the value of y will also change.

Example:

#include <iostream>
using namespace std;

int main()
{
    int x = 1;
    int &y = x;
    x = 5;
    int &z = y;
    cout << "x = " << x << " " << "y = " << y << " " << "z = " << z << endl;
    y = 7;
    cout << "x = " << x << " " << "y = " << y << " " << "z = " << z << endl;
    y = x + z - 3;
    cout << "x = " << x << " " << "y = " << y << " " << "z = " << z << endl;

    return 0;
}

The code begins by declaring an integer variable named x and initializing it to 1. Then, it declares an integer reference named y and binds it to the variable x. This means that y is now an alias for x.

Next, the code assigns the value 5 to the variable x. This also changes the value of the variable y, since it is an alias for x.

Then, the code declares another integer reference named z and binds it to the variable y. This means that z is also an alias for x.

Now, all three variables x, y, and z refer to the same memory location. This means that changing the value of any one of these variables will also change the value of the other two variables.

The code then prints the values of the variables x, y, and z to the console. The output will be:

x = 5 y = 5 z = 5

Next, the code assigns the value 7 to the variable y. This also changes the values of the variables x and z, since they are all aliases for the same memory location.

The code then prints the values of the variables x, y, and z to the console. The output will be:

x = 7 y = 7 z = 7

Finally, the code calculates the value of x + z - 3 and assigns it to the variable y. This also changes the values of the variables x and z, since they are all aliases for the same memory location.

The code then prints the values of the variables x, y, and z to the console. The output will be:

x = 11 y = 11 z = 11

This code demonstrates how aliasing can be used to change the values of multiple variables at once. It also demonstrates how aliasing can be used to create aliases for complex expressions.

It is important to note that aliasing can be a powerful tool, but it can also lead to confusion and errors if used incorrectly. It is important to carefully consider the implications of aliasing before using it in your code.

Constant Variable

A constant variable in C++ is a variable whose value cannot be changed after it is initialized. To declare a constant variable, you use the const keyword before the variable type. For example:

const double Pi = 3.14;

Once you have declared a constant variable, you cannot assign a new value to it. If you try to do so, the compiler will generate an error.

Example:

#include <iostream>
using namespace std;

int main()
{
    const double Pi = 3.14;
    int r;
    cout << "please enter r: ";
    cin >> r;
    double a = Pi * r * r;
    cout << "Area of circle = " << a << endl;

    return 0;
}

This code calculates the area of a circle. The program begins by declaring a constant double variable named Pi and initializing it to the value 3.14. Then, it declares an integer variable named r and prompts the user to enter a value for it.

Next, the program calculates the area of the circle using the following formula:

  • Area = πr²

The program then prints the area of the circle to the console.

Here is a breakdown of the code:

int main()
{
  // Declare a constant double variable named Pi and initialize it to the value 3.14.
  const double Pi = 3.14;

  // Declare an integer variable named r.
  int r;

  // Prompt the user to enter a value for r.
  cout << "please enter r: ";
  cin >> r;

  // Calculate the area of the circle.
  double a = Pi * r * r;

  // Print the area of the circle to the console.
  cout << "Area of circle = " << a << endl;

  return 0;
}

Output:

please enter r: 5
Area of circle = 78.5

Aliasing and constant variables can interact in a few interesting ways:

  • If you have a constant variable and you create an alias to it, the alias is also constant. This is because the alias is just another name for the same variable, and the value of the variable cannot be changed.
  • If you have a constant variable and you pass it to a function as a parameter, the function cannot change the value of the variable. This is because the function is only allowed to modify the local copy of the variable.
  • If you have a pointer to a constant variable, you can still use the pointer to dereference the variable and read its value. However, you cannot use the pointer to change the value of the variable.

Here is an example of aliasing and constant variables in C++:

#include <iostream>
using namespace std;

int main()
{
    int i = 1;
    int &j = i;
    cout << "j = " << j << endl;
    const int &k = j;
    cout << "k = " << k << endl;

    return 0;
}

Output:

j = 1
k = 1

 

One Dimensional Array (part 1)

An array is a data structure that stores a collection of elements of the same data type. These elements are stored in contiguous memory locations, and they can be accessed using an index. Arrays provide a way to manage and manipulate a large set of data efficiently.

In C++, you can declare an array by specifying its data type and the number of elements it will hold. Here’s a basic syntax:

data_type array_name[array_size];

Arrays in C++ are zero-indexed, meaning the first element is accessed using the index 0, the second element with index 1, and so on. You can access and modify array elements using square brackets:

array_name[index] = new_value;

Here is an example:

#include <iostream>
using namespace std;

int main()
{
    int x[5];
    x[0] = 10;
    x[1] = 20;
    cout << x[0] << endl;
    x[2];
    x[3];
    x[4];

    return 0;
}

1. int x[5];

This line declares an integer array named x with a size of 5. It means that x can store five integer values. However, at this point, the values in the array are uninitialized, which means they contain random data.
2. x[0] = 10;

Here, we assign the value 10 to the first element of the array x. In C++, arrays are zero-indexed, so x[0] refers to the first element.
3. x[1] = 20;

Similarly, we assign the value 20 to the second element of the array x, which is x[1].
4. cout << x[0] << endl;

This line prints the value of the first element of the array x, which is 10, to the console. It uses the cout object from the C++ Standard Library to output the value, followed by an end-of-line character (endl) for formatting.
5. x[2];

These lines appear to be accessing the third element of the array x, but they don’t do anything. It’s essentially a “noop” operation, and the value in x[2] remains uninitialized or unchanged.
6. x[3]; and x[4];

Similar to the previous line, these lines access the fourth and fifth elements of the array x, but they also don’t perform any meaningful operation.

Output:

10

Here is another example:

#include <iostream>

using namespace std;

int main()
{
    int x[5];
    x[0] = 10;
    x[1] = 5;
    x[4] = x[0] + x[1];
    cout<< x[4] << endl;

    return 0;
}

Output:

15

Arrays only accept constant array size, Example:

#include <iostream>

using namespace std;

int main()
{
    const int t = 5;
    int x[t];

    return 0;
}

This code declares an integer array `x` with a size of 5, and the size is determined by the constant `t`, which is set to 5. The `const` keyword ensures that `t` cannot be changed later in the program. This code doesn’t perform any further operations on the array; it simply demonstrates how to declare an array with a size determined by a constant.

You can also declare the size of your array, and declare the initial values of your array:

#include <iostream>

using namespace std;

int main()
{
    int x[5] = { 1,4,8,7,2 };
    cout << x[0] << endl;

    return 0;
}

This code declares an integer array x with a size of 5 and initializes it with the values 1, 4, 8, 7, and 2. It then prints the first element of the array, which is 1, to the console. This code demonstrates how to create an array and access its elements in C++.

But what if you declared no initial values into your array?

#include <iostream>

using namespace std;

int main()
{
    int x[5];
    cout << x[3] << endl;

    return 0;
}

This code declares an integer array x with a size of 5 but does not initialize its elements. Therefore, when you attempt to print the value of the fourth element, it will display a random or garbage value. It’s important to initialize array elements before using them to avoid unpredictable behavior in your programs.

What if you declared only one initial value that equals to 0?

#include <iostream>

using namespace std;

int main()
{
    int x[5] = {0};
    cout << x[3] << endl;

    return 0;
}

This code declares an integer array x with a size of 5 and initializes all its elements to 0. It then prints the value of the fourth element of the array, which is 0, to the console. This code demonstrates how to create an array with specific initial values in C++.

You can also declare a size of array and declare some of the first initial values, for example:

#include <iostream>

using namespace std;

int main()
{
    int x[5] = {1,2,3};
    cout << x[3] << endl;

    return 0;
}

This code declares an integer array x with a size of 5 and initializes the first three elements with values, while the remaining two elements are automatically initialized to 0. It then prints the value of the fourth element, which is 0, to the console.

Or, you can declare no size of your array and only declare the initial values of your array:

#include <iostream>

using namespace std;

int main()
{
    int x[] = {1,2,3,4,5};
    cout << x[3] << endl;

    return 0;
}

This code declares an integer array x and initializes it with values using an array initialization list. It then prints the value of the fourth element of the array, which is 4, to the console. This code demonstrates how to create an array and access its elements in C++.

How does the compiler store the values on an array?

The compiler stores the values of an array in contiguous memory locations. This means that the values of the array elements are stored next to each other in memory. The compiler allocates a block of memory that is large enough to store all of the array elements, and then it stores the values of the elements in this block of memory.

The compiler keeps track of the address of the first element in the array, and then it uses this address to access the other elements in the array. For example, to access the element at index i, the compiler adds i to the address of the first element.

The specific way that the compiler stores the values of an array depends on the data type of the array elements. For example, if the array elements are integers, the compiler will store each integer in a single memory location. However, if the array elements are structs, the compiler will store each struct in a contiguous block of memory locations.

This code shows you how to read and store user input in an array in C++, it allows the user to input an integer value for the first element of an array, arr[0], and then it displays the value that was entered.

#include <iostream>

using namespace std;

int main()
{
    int arr[50];
    cout << "Enter arr[0]: " << endl;
    cin >> arr[0];
    cout << arr[0] << endl;

    return 0;
}

 

To traverse the elements of an array, you can use loops like for or while. Looping through an array allows you to perform operations on each element systematically.

Example:

#include <iostream>

using namespace std;

int main()
{
    int arr[10];
    for (size_t i = 0; i < 10; i++)
    {
        cout << "Enter arr[" << i << "]: ";
        cin >> arr[i];
    }
    for (size_t i = 0; i < 10; i++)
    {
        cout << "arr[" << i << "] = " << arr[i] << endl;
    }

    return 0;
}

This code allows the user to input 10 integer values, one for each element of the array, and then it displays the values along with their indices. It demonstrates how to read and store multiple user inputs in an array and subsequently print the contents of the array in C++.

One Dimensional Array (part 2)

Arrays are incredibly versatile, and you can perform various operations on them, such as copying the initial values of an existing array into another one.

Of course we cannot use the following command:

arr2 = arr1;

Because we aren’t assigning a single value. Each array has a collection of values, so if we need to assign a single value in an array we have to specify its index:

arr2[0] = arr1[0];

But what if we need to assign all the values of an array into another array?

Example 1:

#include <iostream>

using namespace std;

int main()
{
    const int s = 4;
    int arr1[s] = { 10,20,30,40 };
    int arr2[s];

    for (size_t i = 0; i <= s-1; i++)
    {
        arr2[i] = arr1[i];
    }

    for (size_t i = 0; i < s; i++)
    {
        cout << arr2[i] << " ";
    }
    cout << endl;

    return 0;
}

This code initializes an array arr1 with values, then copies the contents of arr1 into another array arr2. Finally, it prints the elements of arr2. This demonstrates how to copy the contents of one array into another in C++.

Output:

10 20 30 40

Example 2:

#include <iostream>

using namespace std;

int main()
{
    const int s = 5;
    int arr[s] = { 100,200,200,500,0 };
    int sum = 0;
    
    for (size_t i = 0; i < s; i++)
    {
        //sum += arr[i];
        sum = sum + arr[i];
    }
    cout << "sum = " << sum << endl;

    return 0;
}

This code calculates the sum of the elements in the integer array arr and then prints the result to the console. It demonstrates how to use a loop to iterate through an array and accumulate values.

Output:

sum = 1000

Example 3:

#include <iostream>

using namespace std;

int main()
{
    const int s = 5;
    int arr[s] = { 100,200,200,500,100 };
    long long d = 1;
    
    for (size_t i = 0; i < s; i++)
    {
        d *= arr[i];
    }
    cout << "multi = " << d << endl;

    return 0;
}
  • long long d = 1; :This line initializes a long long integer variable d to 1. This variable will be used to accumulate the product of the elements in the array.
  • long long is a data type in C++ that represents a 64-bit integer. It’s designed to store very large integer values. It can hold a wider range of values compared to regular int or long integers.
  • So, the statement long long d = 1; declares a variable named d with a data type of long long and initializes it with the value 1. This variable can then be used to store and manipulate large integer values in your program.

In summary, this code calculates the product of the elements in the integer array arr and then prints the result to the console. It demonstrates how to use a loop to iterate through an array and accumulate the product of its elements.

Output:

multi = 200000000000

Example 4:

#include <iostream>

using namespace std;

int main()
{
    const int s = 5;
    int arr[s] = { 100,200,200,501,101 };
    int sumEven, sumOdd = 0;
    
    for (size_t i = 0; i < s; i++)
    {
        if (arr[i] % 2 == 0)
            sumEven += arr[i];
        else
            sumOdd += arr[i];
    }
    cout << "Sum of even numbers = " << sumEven << endl;
    cout << "Sum of odd numbers = " << sumOdd << endl;

    return 0;
}

This code calculates the sum of even and odd numbers separately in the integer array arr and then prints the results to the console.

Output:

Sum of even numbers = 500
Sum of odd numbers = 602

Example 5:

#include <iostream>

using namespace std;

int main()
{
    const int s = 6;
    int marks[s] = { 100,99,98,88,70,90 };
    int sum = 0;
    for (size_t i = 0; i < s; i++)
    {
        sum += marks[i];
    }
    cout << "Average = " << sum / s << endl;

    return 0;
}

This code calculates the average of the marks stored in the integer array marks and then prints the average to the console.

Output:

Average = 90

Example 6:

#include <iostream>

using namespace std;

int main()
{
    const int s = 6;
    int arr[s] = { 22,100,95,101,200,90 };
    int max = 0;
    for (size_t i = 0; i < s; i++)
    {
        if (arr[i] > max)
            max = arr[i];
    }
    cout << "Maximum number = " << max << endl;

    return 0;
}

This code finds the maximum value among the numbers stored in the integer array arr and then prints the maximum value to the console.

Output:

Maximum number = 200

Example 7:

#include <iostream>

using namespace std;

int main()
{
    int vector[5];
    cout << "Enter 5 numbers: ";
    for (int i = 0; i < 5; i++)
        cin >> vector[i];
    cout << endl;
    
    int Element;
    cout << "What is the element you are looking for? ";
    cin >> Element;
    
    bool Found = false;
    int i;
    for (i = 0; i < 5; i++)
        if (Element == vector[i])
        {
            Found = true;
            break;
        }
    cout << endl;
    if (Found)
        cout << Element << " found at position " << i << endl;
    else
        cout << Element << " is not in this array!" << endl;

    return 0;
}

In this C++ code, you’re taking user input to populate an integer array `vector` of size 5 and then searching for a specific element within the array. Let’s break down the code step by step:

  1. int vector[5];
    – This line declares an integer array `vector` with a size of 5, which can store up to five integer values.
  2. Input Loop to Populate the Array:
    – The code prompts the user to enter five numbers and stores them in the `vector` array using a `for` loop that iterates five times. Each input is assigned to a different element of the array.
  3. int Element;
    – This line declares an integer variable `Element`, which will store the value the user is searching for.
  4. Prompt for the Element to Search:
    – The code asks the user to input the element they want to search for.
  5. Search Loop:
    – The `for` loop is used to search for the element within the array. If the element is found, the loop breaks, and the `Found` flag is set to `true`. The variable `i` keeps track of the position where the element was found.
  6. Output the Result:
    – The code then checks if the element was found (i.e., `Found` is `true`). If found, it displays the element and its position in the array. If not found, it informs the user that the element is not in the array.

In summary, this code allows the user to enter five numbers into an array and then search for a specific element within the array. It provides feedback on whether the element was found and its position in the array.

One Dimensional Array part 3 (Passing Array To Function)

In C++, you can pass an array to a function, and this is a fundamental concept when working with arrays. When you pass an array to a function, you’re essentially allowing that function to operate on the array’s elements or modify the array if needed.

Here’s an explanation of how to pass an array to a function in C++:

Array Declaration in a Function

Array Parameters: To pass an array to a function, you need to declare the function parameter as an array. You can declare it in two ways:

  • Using a Fixed Size: If you know the size of the array in advance, you can specify the size in the function parameter, like this:
void functionName(int arr[5]) {
    // Code to work with the array
}
  • Using a Pointer: You can also declare the function parameter as a pointer to the array’s elements without specifying the size, like this:
void functionName(int *arr, int size) {
    // Code to work with the array
}

In this case, you pass the size of the array as a separate argument.

Passing the Array to the Function

Calling the Function: When you call the function, you provide the array as an argument. If you declared the function parameter with a fixed size, you pass the array directly. If you used a pointer, you pass the array and its size as arguments.

Example with a fixed-size array parameter:

int myArray[5] = {1, 2, 3, 4, 5};
functionName(myArray);

Example with a pointer parameter:

int myArray[5] = {1, 2, 3, 4, 5};
functionName(myArray, 5);

Using the Array in the Function

Working with the Array: Inside the function, you can access and manipulate the elements of the array as needed. You can use array indices (e.g., arr[0], arr[1]) to access individual elements, and you can use loops to iterate through the elements.

Example of accessing array elements:

void functionName(int arr[5]) {
    for (int i = 0; i < 5; i++) {
        // Access and manipulate arr[i]
    }
}

Here is a demonstration of passing an array to functions for setting values in the array and then printing those values:

#include <iostream>
using namespace std;

void set(int arr[], int s)
{
    for (size_t i = 0; i < s; i++)
    {
        cout << "Enter array value: ";
        cin >> arr[i];
    }
}

void print(int arr[], int s)
{
    for (size_t i = 0; i < s; i++)
    {
        cout << arr[i] << " ";
    }
}

int main()
{
    int a[5];
    set(a, 5);
    print(a, 5);

    return 0;
}

The set function allows the user to set values in the array, and the print function prints the values stored in the array. It’s a practical example of how to work with arrays and functions in C++.

Modifying the Array

Example 1:

This code shows an implementation of the “Bubble Sort” algorithm. Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, indicating that the list is sorted. Here’s a breakdown of the code:

#include <iostream>
using namespace std;

int main()
{
    int vector[] = {6,5,4,1,2};
    int t = 0;
    
    // Bubble Sort algorithm
    for (size_t i = 0; i < 5 - 1; i++)
    {
        for (size_t j = 0; j < 5 - i - 1; j++)
        {
            if (vector[j] > vector[j + 1])
            {
                t = vector[j];
                vector[j] = vector[j + 1];
                vector[j + 1] = t;   
            }
        }
    }
    
    for (size_t i = 0; i < 5; i++)
    {
        cout << vector[i] << endl;
    }

    return 0;
}
  1. int vector[] = {6, 5, 4, 1, 2};:
    An integer array vector is initialized with unsorted values.
  2. int t = 0;:
    An integer variable t is declared to be used for swapping elements during the sorting process.
  3. Bubble Sort Algorithm:
    The nested for loops are used to implement the Bubble Sort algorithm. The outer loop (i) controls the number of passes, and the inner loop (j) compares adjacent elements and swaps them if they are out of order.
  4. If the element at index j is greater than the element at index j + 1, a swap is performed to put them in ascending order.
  5. Printing the Sorted Array:
    After sorting is complete, the code uses a for loop to print the sorted elements in ascending order.

The output of this code will be the sorted array in ascending order, which is the result of applying the Bubble Sort algorithm to the initial unsorted array. Bubble Sort is not the most efficient sorting algorithm for large data sets, but it’s easy to understand and implement.

Example 2:

This code performs the sorting of an integer array using the Bubble Sort algorithm. It sorts the array in ascending order and then prints the sorted values. Let’s break down the code step by step:

#include <iostream>
using namespace std;

const int s = 5;
void sort(int arr[])
{
    int t = 0;
    for (size_t i = 0; i < 5 - 1; i++)
    {
        for (size_t j = 0; j < 5 - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                t = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = t;   
            }
        }
    }
}

void print(int vector[])
{
    for (size_t i = 0; i < 5; i++)
    {
        cout << vector[i] << endl;
    }
}

int main()
{
    int vector[] = {0,-1,55,-5,-100};
    sort(vector);
    print(vector);
    return 0;
}

The output of this code will be the sorted array in ascending order, which is the result of applying the Bubble Sort algorithm to the initial unsorted array.

Example 3:

This code demonstrates how to reverse the elements of an integer array using a reversArray function. It reverses the array in-place and then prints the reversed array:

#include <iostream>
using namespace std;

void reversArray(int arr[], int s)
{
    for (size_t i = 0; i < s / 2; i++)
    {
        swap(arr[i], arr[s - i - 1]);
    }
}

int main()
{
    int vector[] = {3,2,4,5,6};
    reversArray(vector, 5);
    for (size_t i = 0; i < 5; i++)
    {
        cout << vector[i] << " ";
    }

    return 0;
}

The output of this code will be the reversed array, where the elements are reversed in place. This is achieved by swapping the first element with the last element, the second element with the second-to-last element, and so on. It’s a simple and efficient way to reverse the order of elements in an array.

 

Note:

If you don’t want to modify your array you can initial its value as a constant in the function. Example:

void print(const int arr[], int s)
{
    //body of the function
}

This way any try to modify the array will produce an error.

One Dimensional Array part4 (Array Of Character)

An array of characters in C++ is often referred to as a “string.” It is a fundamental data structure used to store sequences of characters, such as words, sentences, or even individual characters. In C++, strings are represented as arrays of characters, terminated by a special null character, ‘\0’, which indicates the end of the string.

to initiate a character we use a single quotation like this ‘L’.

Example 1:

char ch[5] = { 'a','b','c','d','e','\0' };

The null character (‘\0’), NULL or 0, is used to indicate the end of the string. This character is automatically added to the end of string literals and is crucial for various string manipulation functions.

If you add characters after the null character they won’t be read by the program.

Example 2:

#include <iostream>
using namespace std;
int main()
{
    char ch[5];
    cin >> ch;
    cout << ch << endl;
    return 0;
}

This code reads a sequence of characters into a char array and then prints the array. However, there are a few things to note about potential issues and improvements in the code:

  1. Array Size:
    The char array ch has a size of 5. If you enter more than 4 characters, it will result in a buffer overflow, causing undefined behavior. It’s essential to ensure that the input doesn’t exceed the array size.
  2. Input Method:
    When using cin >> ch, it reads characters until it encounters whitespace. If you want to read an entire line (including spaces), you should use cin.getline(ch, size) or cin.get(ch, size).

Example 3:

#include <iostream>
using namespace std;

int main() {
    char ch[10];

    // Read up to 9 characters into the char array
    cin.get(ch, 10);

    // Output the char array
    cout << ch << endl;

    return 0;
}

This code reads up to 9 characters (plus the null terminator) into a char array using cin.get() and then prints the array.
Here are a few points to note:

  1. Array Size:
    The char array ch has a size of 10. Since cin.get() reads up to one less than the specified size (leaving space for the null terminator), it effectively reads up to 9 characters.
  2. Input Method:
    cin.get(ch, 10) reads characters until either 9 characters are read, the newline character is encountered, or the end of file is reached. It stops reading after reaching the specified number of characters or encountering one of these conditions.
  3. Null Terminator:
    The array is not explicitly null-terminated by cin.get(); however, C++ streams automatically append a null terminator at the end of the string when reading into a character array. Therefore, the array ch is effectively treated as a C-style string.

Output:

The cout << ch << endl; statement prints the contents of the char array, treating it as a null-terminated string. If fewer than 9 characters were entered, it prints the characters entered. If 9 characters were entered, it prints those 9 characters followed by the null terminator.

Input Limitation:

Keep in mind that the user input is limited to 9 characters, and exceeding this limit may lead to unexpected behavior. It’s essential to handle potential input overflows based on the specific requirements of your program.

Example 4:

#include <iostream>
using namespace std;
int main()
{
    char ch1[10], ch2[10];
    cin.getline(ch1, 10);
    cin.getline(ch2, 10);
    cout << ch1 << endl;
    cout << ch2 << endl;
    return 0;
}

This code reads two lines of input into separate char arrays and then prints each array on a new line.

Here are some points to note:

  1. Array Size:
    Both ch1 and ch2 are char arrays with a size of 10. The cin.getline() function reads characters until it encounters a newline character or reaches the specified size (leaving space for the null terminator).
  2. Input Limitation:
    The user input for each line is limited to 9 characters, and the null terminator is automatically added by cin.getline().
  3. Handling Spaces:
    Unlike cin >>, cin.getline() reads the entire line, including spaces. This allows you to input strings with spaces.

Output:

The cout << ch1 << endl; statement prints the contents of the first char array, treating it as a null-terminated string.
Similarly, cout << ch2 << endl; prints the contents of the second char array.
Newline Character:

Each call to cin.getline() reads until it encounters a newline character or reaches the specified size. The newline character is consumed but not stored in the arrays.
This code allows you to input two lines of text (up to 9 characters each) and then prints each line on a new line. It’s suitable for reading and displaying multiple lines of text, handling spaces, and avoiding buffer overflow issues.

 

There are some functions that are part of the C Standard Library and are used for manipulating C-style strings, which are arrays of characters. Here’s an explanation of each function:

  • strcpy (String Copy):

Description: The strcpy function is used to copy the contents of one C-style string to another.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    char ch1[] = "AAA";
    char ch2[4];
    strcpy_s(ch2, ch1);
    cout << ch2 << endl;
    return 0;
}
  1. strcpy_s Function:
    The strcpy_s function is part of the C Standard Library and is designed to provide safer string copying by including a size check.
  2. Buffer Size:
    The size of ch2 is explicitly specified as 4, which includes three characters for the content of ch1 (“AAA”) and one additional space for the null terminator (‘\0’).
  3. Safe String Copy:
    Unlike the standard strcpy function, strcpy_s requires you to provide the size of the destination array (destsz). It checks if there is enough space in the destination array to accommodate the source string and the null terminator. If there isn’t enough space, the function does not perform the copy and returns an error code.

Output:

The cout << ch2 << endl; statement outputs the contents of ch2, which should be “AAA” in this case.

By using strcpy_s, you are taking steps to prevent buffer overflow issues that could occur if the destination array is not large enough to hold the contents of the source string. This is a good practice for enhancing the safety and robustness of your code.

  • strcat (String Concatenate):

Description: The strcat function is used to concatenate (append) the contents of one C-style string to another.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    char ch1[] = "AAA";
    char ch2[4] = "HH";
    strcat(ch2, ch1);
    cout << ch2 << endl;
    return 0;
}
  1. strcat Function:
    The strcat function is part of the C Standard Library and is used to concatenate the contents of one C-style string to another.
  2. Buffer Size:
    The size of ch2 is explicitly specified as 4, which includes two characters (“HH”) and one additional space for the null terminator (‘\0’).
  3. Concatenation:
    The strcat(ch2, ch1); line appends the contents of ch1 to the end of ch2. It starts copying characters from the null terminator of ch2 to the end of ch1 until it encounters the null terminator of ch1. The null terminator of ch2 is updated accordingly.

Output:

The cout << ch2 << endl; statement outputs the contents of ch2 after the concatenation. Since the size of ch2 is limited to 4, it can hold “HH” and the null terminator, but only one additional character from ch1 (“A”) can be accommodated.
Result:

The output of this code is “HHA”, which is the result of concatenating “AAA” to the end of the existing content in ch2.
It’s important to ensure that the destination array has enough space to accommodate the concatenated string, and using functions like strcat requires careful management of buffer sizes to prevent buffer overflows.

  • strcmp (String Compare):

Description: The strcmp function is used to compare two C-style strings lexicographically.

The strcmp function returns an integer value indicating the lexicographic relationship between the two strings. It returns:
– 0 if the strings are equal,
– a negative value if str1 is lexicographically less than str2,
– a positive value if str1 is lexicographically greater than str2.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    cout << strcmp("abc", "abc") << endl;
    return 0;
}

Output:

The cout statement outputs the result of the comparison using strcmp. In this case, since the strings are equal, the output will be 0.

The strcmp function is commonly used for sorting strings, dictionary operations, and other scenarios where you need to determine the lexicographic order of strings. It’s important to handle the result appropriately based on your specific requirements in the program.

  • strlen (String Length):

Description: The strlen function is used to determine the length of a C-style string.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    char ch[] = "jjjjjjjjjjjjjjjjjjjjj";
    cout << strlen(ch) << endl;
    return 0;
}

Output:

The cout statement outputs the result of strlen(ch), which is the length of the string “jjjjjjjjjjjjjjjjjjjjj”. Since there are 21 characters in the string, the output will be 21.

The strlen function is useful for obtaining the length of strings, and it’s important to note that the length does not include the null terminator. Make sure that the string is properly null-terminated to get accurate results with strlen.

 

 

 

 

 

Two Dimensional Array

A two-dimensional array in C++ is a structure that allows you to store elements in a tabular form, organized in rows and columns. It is essentially an array of arrays.

Here’s an explanation of a two-dimensional array in C++:

  • Declaration and Initialization:
// Declaration of a 2D array
int matrix[3][4];

// Initialization of a 2D array
int anotherMatrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
  • Structure:

In a 2D array, elements are arranged in rows and columns. The first index represents the row, and the second index represents the column.

  • Memory Representation:

In memory, a 2D array is stored in a contiguous block of memory. The elements of each row are stored together, and rows are stored one after the other.

  • Accessing Elements:
int value = matrix[1][2];  // Accessing the element in the second row and third column
  • Initialization with Nested Loops:

Common Operations:

– Iterating through elements using nested loops.
– Performing operations on each element.
– Passing a 2D array to functions.

Example 1:

#include <iostream>
using namespace std;
int main()
{
    int a[3][4];
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 4; j++)
        {
            cin >> a[i][j];
        }
    }
    for (size_t r = 0; r < 3; r++)
    {
        for (size_t c = 0; c < 4; c++)
        {
            cout << a[r][c] << " ";
        }
        cout << endl;
    }
    return 0;
}

This code allows the user to input values into a 2D array a[3][4] and then prints the array in a tabular form.

Here are the key points:

  1. 2D Array Input:
    The nested loops (for loops) are used to iterate over each element of the 2D array and input values using cin.
  2. 2D Array Output:
    Another set of nested loops is used to iterate over each element of the 2D array and output the values using cout.
    The inner loop prints each row, and the outer loop moves to the next row, creating a tabular form.
  3. Tabular Output:
    The cout << a[r][c] << ” “; statement prints each element of the 2D array followed by a space.
    The cout << endl; statement is used to move to the next line after printing each row.
  4. User Interaction:
    The user is prompted to input values for each element of the 2D array. The input is expected to be provided in a row-wise fashion.
  5. Array Size:
    The array a is declared with 3 rows and 4 columns, creating a 3×4 matrix.

This code allows the user to interactively input values into a 3×4 2D array and then displays the array in a tabular format.

Example 2:

#include <iostream>
using namespace std;

int main() {
    // Initialization of a 2D array with predefined values
    int arr[2][4] = {{1, 1, 1, 1}, {2, 2, 2, 2}};
    
    // Variable to store the sum of array elements
    int sum = 0;

    // Nested loops to iterate over each element of the 2D array
    for (size_t r = 0; r < 2; r++) {
        for (size_t c = 0; c < 4; c++) {
            // Accumulate the values to calculate the sum
            sum += arr[r][c];
        }
    }

    // Output the sum of array elements
    cout << "sum = " << sum << endl;

    return 0;
}

Output:

In this specific example, the sum is calculated as follows: 1 + 1 + 1 + 1 + 2 + 2 + 2 + 2 = 12.
The output will be sum = 12.

This code is a simple illustration of how to iterate over elements in a 2D array and perform a basic operation, in this case, calculating the sum of all elements.

Example 3:

#include <iostream>
using namespace std;
int main()
{
    int marks[10][5];
    for (size_t r = 0; r < 10; r++)
    {
        for (size_t c = 0; c < 5; c++)
        {
            cout << "Enter mark " << c + 1 << " " << "for student " << r + 1 << ": " << endl;
            cin >> marks[r][c];
        }
    }
    double s = 0;
    float avg[10];
    for (size_t r = 0; r < 10; r++)
    {
        s = 0;
        for (size_t c = 0; c < 5; c++)
        {
            s += marks[r][c];
        }
        avg[r] = s / 5;
        cout << "Average for student #" << r + 1 << " = "<< avg[r] << endl;
    }
    return 0;
}

This code collects marks for 10 students in 5 subjects, calculates the average mark for each student, and then outputs the average for each student.

Example 4:

#include <iostream>
using namespace std;
int main()
{
    char MTXchar[5][5] = {{'*','$','$','$','$'},
                          {'$','*','$','$','$'},
                          {'$','$','*','$','$'},
                          {'$','$','$','*','$'},
                          {'$','$','$','$','*'}};
                          
    for (size_t r = 0; r < 5; r++)
    {
        for (size_t c = 0; c < 5; c++)
        {
            
            if (c == r)
                cout << MTXchar[r][c];
            else
                cout << " ";
        }
        cout << endl;
    }
    return 0;
}

This code defines a 5×5 matrix (MTXchar) containing ” characters on the main diagonal and ‘$’ characters elsewhere. It then prints only the characters on the main diagonal, resulting in a diagonal line of ” characters.

Output:

The code outputs a diagonal line of ‘*’ characters on the console.

*    
 *   
  *  
   * 
    *

 

Passing a two-dimensional array to a function in C++ involves specifying the array as a parameter in the function declaration. Since a 2D array is essentially an array of arrays, you need to specify the size of the columns (since the rows are implicitly known based on the number of arrays).

  • Function Declaration:

When declaring a function that accepts a 2D array, you need to specify the array parameter along with the size of the columns. The size of the rows is not explicitly specified.

void functionName(int arr[][COLS], size_t rows, size_t cols) {
    // Function logic using arr
}

– int arr[][COLS]: This syntax indicates that the function takes a 2D array of integers with a specified number of columns (COLS).
– size_t rows: This parameter can be used to pass the number of rows in the array.
– size_t cols: This parameter can be used to pass the number of columns in the array

  • Function Call:

When calling the function, you need to provide the actual 2D array along with the number of rows and columns.

int myArray[ROWS][COLS];
functionName(myArray, ROWS, COLS);

– myArray: The name of the 2D array you want to pass.
– ROWS: The number of rows in the array.
– COLS: The number of columns in the array.

Example 5:

#include <iostream>
using namespace std;
void f(int arr[][5], int r)
{
    for (size_t i = 0; i < r; i++)
    {
        for (size_t j = 0; j < 5; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}
int main()
{
    int a[2][5] = {1,2,3,4,5,
                   10,20,30,40,50};
    f(a, 2);
    return 0;
}

The function f takes a 2D array (arr) and its number of rows (r) as parameters.
It uses nested loops to iterate over each element of the array and prints the elements in a tabular form.

The main function calls the function f with the 2D array a and the number of rows (2) as arguments.

Output:

The output of this code would be the elements of the 2D array a printed in a tabular form.

The printed output would look like:

1 2 3 4 5 
10 20 30 40 50 
  • Transpose matrix

The transpose of a matrix is an operation that flips the matrix over its diagonal, switching the row and column indices of the matrix. In other words, if the original matrix has elements at position (i, j), the transposed matrix will have the element at position (j, i).

Example 6:

#include <iostream>
using namespace std;
int main()
{
    int arr[3][3];
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 3; j++)
        {
            cin >> arr[i][j];
        }
    }
    cout << "Matrix is: \n";
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 3; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    cout << "Transpose matrix is:\n";
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 3; j++)
        {
            cout << arr[j][i] << " ";
        }
        cout << endl;
    }

    return 0;
}

This code takes user input for a 3×3 matrix, prints the original matrix, and then prints its transpose.

Here are the key points:

  1. Input:
    The nested loops take user input for a 3×3 matrix.
  2. Original Matrix Output:
    After taking input, the code outputs the original matrix.
  3. Transpose Matrix Output:
    Another set of nested loops outputs the transpose of the matrix. It switches the row and column indices.

Example Output:

If the user enters:

1 2 3
1 2 3
1 2 3

The output would be:

Matrix is: 
1 2 3 
1 2 3 
1 2 3 
Transpose matrix is:
1 1 1 
2 2 2 
3 3 3

 

Pointer

In C++, a pointer is a variable that stores the memory address of another variable. Pointers provide a powerful mechanism for working with memory and data structures. They allow direct manipulation of memory addresses and enable efficient memory management.

Declaring Pointers

To declare a pointer, you use the data type followed by an asterisk (*) and the pointer name. For example:

int *ptr; // Declares a pointer to an integer
double *dblPtr; // Declares a pointer to a double

Initializing Pointers

Pointers should be initialized before use. You can initialize a pointer by assigning the address of a variable to it. The address-of operator (&) is used to obtain the memory address of a variable.

int num = 10;
int *ptr = &num; // Initializes ptr with the address of num

Dereferencing Pointers

Dereferencing a pointer means accessing the value stored at the memory address it points to. The dereference operator (*) is used for this purpose.

int num = 10;
int *ptr = &num;

cout << *ptr; // Prints the value stored at the address pointed by ptr

Example 1:

#include <iostream>
using namespace std;

int main() {
    // Declaration of a pointer to an integer
    int *ptr;

    // Declaration and initialization of an integer variable
    int val = 5;

    // Assigning the address of 'val' to the pointer 'ptr'
    ptr = &val;

    // Printing the address stored in the pointer
    cout << ptr << endl;

    // Printing the value stored at the address pointed by 'ptr'
    cout << *ptr << endl;

    // Return 0 to indicate successful execution
    return 0;
}

This code declares a pointer, initializes an integer variable, assigns the address of that variable to the pointer, and then prints both the pointer’s value (memory address) and the value it points to.

Here are the key points:

  1. Pointer Declaration:
    int *ptr;: Declares a pointer to an integer. This pointer is currently uninitialized.
  2. Variable Declaration and Initialization:
    int val = 5;: Declares an integer variable named val and initializes it with the value 5.
  3. Assigning Address to Pointer:
    ptr = &val;: Assigns the memory address of the variable val to the pointer ptr. Now ptr “points” to the memory location of val.
  4. Printing Pointer’s Value (Memory Address):
    cout << ptr << endl;: Prints the memory address stored in the pointer ptr. The address is typically represented in hexadecimal format.
  5. Printing Value at the Address Pointed by Pointer:
    cout << *ptr << endl;: Uses the dereference operator (*) to access the value stored at the memory address pointed by ptr. Prints the value stored in the variable val.

Output:
If you run this program, the output will be something like:

0x7ffee3c86a4c   // The memory address (this will vary on each run)
5                // The value stored at the memory address

Example 2:

#include <iostream>
using namespace std;
int main()
{
    int *p;
    int v = 9;
    p = &v;
    cout << *p << endl;
    return 0;
}

This code prints the address of the value pointed to by the pointer p using the expressions &*p.

cout << &*p << endl;: Uses the dereference operator (*) to access the value stored at the memory address pointed by p. The & operator then takes the address of this value. Essentially, &*p is equivalent to just p, so this line prints the memory address stored in the pointer p.

 

Pointer part 2 (Array vs Pointer & Passing Pointer To Function)

Arrays in C++

An array is a collection of elements of the same type stored in contiguous memory locations. In C++, arrays can be of primitive types (int, float, etc.) or user-defined types (structures, classes). Arrays have a fixed size, and the elements are accessed using an index.

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

Pointers in C++

A pointer is a variable that stores the memory address of another variable. Pointers allow for dynamic memory allocation and manipulation. They are often used for efficient memory management and for accessing elements in arrays.

int x = 10;
int *ptr = &x; // ptr now holds the address of x

Array vs. Pointer

In many contexts, arrays and pointers in C++ exhibit similar behavior. When an array name is used in an expression, it decays into a pointer to its first element. For example:

int arr[3] = {1, 2, 3};
int *ptr = arr; // Equivalent to &arr[0]

However, there are differences:

  • An array variable cannot be reassigned to point to a different memory location, whereas a pointer can.
  • Arrays carry information about their size, while pointers do not inherently know the size of the memory they point to.
  • Arrays can be used with the sizeof operator to determine their size, but pointers alone cannot.

Pointer Arithmetic

Pointers can be incremented or decremented to navigate through an array or block of memory.

int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;

cout << *ptr; // Prints the first element (1)
ptr++;        // Moves to the next element
cout << *ptr; // Prints the second element (2)

 

Example 1:

#include <iostream>
using namespace std;
int main()
{
    int arr[7] = {11,22,33,44,55,66,77};
    for (size_t i = 0; i < 7; i++)
    {
        cout << *(arr + i) << endl;
    }
    return 0;
}

code prints the elements of an array using pointer arithmetic.

cout << *(arr + i) << endl;: Utilizes pointer arithmetic to access each element of the array. The expression arr + i calculates the memory address of the i-th element, and *(arr + i) dereferences the pointer to access the value stored at that address.

Output:
If you run this program, the output will be:

11
22
33
44
55
66
77

 

Example 2:

#include <iostream>
using namespace std;
int main()
{
    int arr[7] = {11,22,33,44,55,66,77};
    int *ptr;
    ptr = arr;
    for (size_t i = 0; i < 7; i++)
    {
        cout << *ptr << " ";
        ptr++;
    }
    return 0;
}

This code accomplishes the same goal as the previous example but uses a pointer (ptr) and pointer arithmetic to iterate through the array.

Output:
If you run this program, the output will be:

11 22 33 44 55 66 77

Passing Pointers to Functions

When passing an array to a function, you are actually passing a pointer to the first element of the array. This is due to the array decaying into a pointer in function arguments.

Example 3:

This code demonstrates the usage of pointers and a function that modifies the value it points to.

#include <iostream>
using namespace std;
int fun(int *p)
{
    *p = *p + 1;
    return *p;
}
int main()
{
    int x = 1;
    int *ptr = &x;
    cout << fun(ptr) << endl;
    cout << x << endl;
    cout << fun(&x) << endl;
    cout << x << endl;
    return 0;
}

Key points:

  1. Function fun:
    int fun(int *p): Takes a pointer to an integer as a parameter.
    *p = *p + 1;: Increments the value pointed to by the pointer.
    return *p;: Returns the updated value.
  2. Main Function:
    int x = 1;: Declares and initializes an integer variable x.
    int *ptr = &x;: Declares a pointer ptr and assigns the address of x to it.
    cout << fun(ptr) << endl;: Calls the function fun with the pointer ptr and prints the result. The value of x is now 2.
    cout << x << endl;: Prints the current value of x after the function call. It is now 2.
    cout << fun(&x) << endl;: Calls the function fun with the address of x directly and prints the result.
    The value of x is now 3.cout << x << endl;: Prints the final value of x. It is now 3.

Output:
If you run this program, the output will be:

2
2
3
3

 

Data Structures (struct)

In the world of programming, data structures play a pivotal role in how we organize and manipulate data efficiently. They act as the building blocks that enable us to create well-structured and organized programs. In this explanation, we will delve into one fundamental data structure in C++ known as struct.

What is a Data Structure?

Before we explore struct, let’s define what a data structure is. A data structure is a way of organizing and storing data in a computer’s memory to perform operations on that data more efficiently. It provides a blueprint for the storage and retrieval of information.

Introduction to struct in C++

struct in C++ is a user-defined data type that allows you to group together variables of different data types under a single name. Think of it as creating a custom data type tailored to the specific needs of your program. This makes your code more modular, organized, and easier to understand.

Syntax of struct:

The syntax for defining a struct is straightforward:

struct MyStruct

struct MyStruct

Example 1:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
int main()
{
    car x;
    x.name = "Rolls-Royce";
    x.color = "Red";
    x.model = 2019;
    x.maxSpeed = 270;
    
    cout << x.name << endl;
    return 0;
}

code defines a struct named car that represents information about a car, and it creates an instance of this struct called x to store details about a specific car.

Key points:

  • Struct Definition (car):
    The struct named car has four member variables: name, color, maxSpeed, and model. These variables store information about a car.
  • Instance Creation (x):
    An instance of the car struct named x is created in the main function. This instance can store information about a specific car.
  • Assigning Values:
    Values are assigned to the member variables of the x instance using the dot (.) notation. For example, x.name = “Rolls-Royce” assigns the name “Rolls-Royce” to the name member variable.
  • Printing Information:
    The program prints the name of the car using cout << x.name << endl;. In this case, it will output “Rolls-Royce” to the console.

Output:
If you run this program, the output will be:

Rolls-Royce

Example 2:

Here is another way of initialization the values based on the previous example:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
int main()
{
    car x = {"BMW","Blue",250,2016};
    cout << x.maxSpeed << endl;
    return 0;
}

Output:

250

Example 3:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
int main()
{
    car x = {"BMW","Blue",250,2016};
    car y = x;
    cout << y.name << endl;
    return 0;
}

Instance Creation and Initialization (x and y):

  • An instance of the car struct named x is created with initial values.
  • Another instance named y is created and initialized with the values of x. This is a memberwise copy, and each member of y gets the value of the corresponding member in x.

Example 4:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
}y;
int main()
{
    car x = {"BMW","Blue",250,2016};
    car y = {"Mercedes","Red",300,2016};
    if (x.maxSpeed > y.maxSpeed)
        cout << "car x is faster than car y";
    else
        cout << "car y is faster than car x";
    return 0;
}
  • Global Instance Declaration (y):
    An instance of the car struct named y is declared at the global scope. This means it can be accessed throughout the program.
  • Instance Creation and Initialization (x and Local y):
    – A local instance of the car struct named x is created with initial values.
    – Another local instance named y is created with different values. This y is local to the main function and shadows the global y within this scope.
  • Comparison and Output:
    The program compares the maximum speeds of cars x and y and prints a message indicating which car is faster.

Output:
If you run this program, the output will depend on the values assigned to maxSpeed in x and y. For the provided values, it will output:

car y is faster than car x

Pass ‘struct’ into function:

Example 5:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
void f(car f)
{
    cout << "Name = " << f.name << endl;
    cout << "Color = " << f.color << endl;
}
int main()
{
    car v = {"No name","Red",160,2000};
    f(v);
    return 0;
}

Key points:

  • Function Definition (f):
    The function f takes a car as a parameter and prints information about the car, specifically the name and color.
  • Instance Creation and Initialization (v):
    An instance of the car struct named v is created with initial values.
  • Function Call (f(v)):
    The program calls the function f with the v instance as an argument.

Output:
If you run this program, the output will be:

Name = No name
Color = Red

Example 6:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
car read_return(car&s)
{
    cout << "Enter car name:\n";
    cin >> s.name;
    cout << "Enter car color:\n";
    cin >> s.color;
    cout << "Enter car maximum speed:\n";
    cin >> s.maxSpeed;
    cout << "Enter car model:\n";
    cin >> s.model;
    return s;
}
int main()
{
    car v;
    read_return(v);
    car h;
    h = v;
    cout << h.name << endl;
    return 0;
}

Key points:

  • Function Definition (read_return):
    The function read_return takes a car reference as a parameter, reads input to populate its fields, and returns the modified car struct.
  • Function Call (read_return(v)):
    The program calls the function read_return with the v instance as a reference, allowing the function to modify the values of v.
  • Assignment and Printing:
    – The values of v are assigned to h.
    – The program prints the name of h.

Output:
If you run this program and enter values when prompted, the output will depend on the input provided. For example:

Enter car name:
BMW
Enter car color:
Blue
Enter car maximum speed:
250
Enter car model:
2022
BMW

Example 7:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
    void fun(car n)
    {
        cout << n.name << endl;
    }
};

int main()
{
    car v = {"Kia"};
    v.fun(v);
    return 0;
}

Key points:

  • Member Function Definition (fun):
    The member function fun is defined inside the car struct.
    It takes a car as a parameter and prints its name.

Output:
If you run this program, the output will be:

Kia

Example 8:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
    void fun(car n)
    {
        cout << n.name << endl;
    }
};

int main()
{
    car*h;
    car b = {"Toyota","Red",170,2008};
    h = &b;
    cout << h->color << endl;
    return 0;
}

Key points:

  • Pointer Declaration and Initialization (h):
    A pointer to a car named h is declared.
  • Instance Creation and Initialization (b):
    An instance of the car struct named b is created and initialized with specific values.
  • Pointer Assignment (h = &b):
    The address of b is assigned to the pointer h.
  • Pointer Dereferencing (h->color):
    The program prints the color of the car pointed to by h using the arrow operator (->).

Output:
If you run this program, the output will be:

Red

 

String

In C++, a string is a sequence of characters represented using the string class. Unlike C-style strings, which are arrays of characters, C++ strings are dynamic and provide a higher level of abstraction. The string class is part of the C++ Standard Template Library (STL), making it convenient and powerful for handling strings.

Declaring and Initializing Strings:

You can declare a string using the string keyword and initialize it in various ways:

// Declare and initialize strings
string str1 = "Hello, ";  // Initialization using a string literal
string str2("world!");    // Initialization using a constructor

// Concatenate strings
string result = str1 + str2;

When you use a string in C++, you must include its library this way:

#include <string>

Example:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string x = "Ahmad", y;
    y.assign(x);
    cout << "y = " << y << endl;

    return 0;
}

String Assignment:

  • string y;: Declares another string variable y.
  • y.assign(x);: Uses the assign method to copy the contents of string x to string y.

Output:

y = Ahmad

String Methods in C++:

Below is an explanation of various string methods in C++, along with their parameters and examples:

  1. at Method:
    Description: Returns the character at a specified position in the string.
    Parameters: Takes an index as a parameter.
    Example:

    string x = "Ahmad";
    cout << x.at(0) << endl;
    
    // A
  2. length Method:
    Description: Returns the number of characters in the string.
    Parameters: No parameters.
    Example:

     string x = "Ahmad";
     cout << x.length() << endl;
    
     // 5
  3. size Method:
    Description: Same as length, returns the number of characters in the string.
    Parameters: No parameters.
    Example:

    string x = "Ahmad";
    cout << x.size() << endl;
    
    // 5
  4. substr Method:
    Description: Returns a substring of the original string.
    Parameters: Takes starting index and length as parameters.
    Example:

    string x = "Ahmad";
    cout << x.substr(1,3) << endl;
    
    // hma
  5. swap Method:
    Description: Swaps the content of two strings.
    Parameters: Takes another string as a parameter.
    Example:

    string x = "Ahmad", y = "Ali";
    cout << x.swap(y) << endl;
    
    // Swaps the content of x and y
  6. find Method:
    Description: Finds the first occurrence of a substring in the string.
    Parameters: Takes a substring as a parameter.
    Example:

    string x = "Ahmad";
    cout << x.find('a') << endl;
    
    // 3
  7. rfind Method:
    Description: Finds the last occurrence of a substring in the string.
    Parameters: Takes a substring as a parameter.
    Example:

    string x = "Ahmad";
    cout << x.rfind('a') << endl;
    
    // 3
  8. erase Method:
    Description: Erases characters from the string.
    Parameters: Takes starting index and count as parameters.
    Example:

    string x = "Ahmad";
    cout << x.erase(0,3) << endl;
    
    // ad
  9. replace Method:
    Description: Replaces a portion of the string with another string.
    Parameters: Takes starting index, length, and replacement string as parameters.
    Example:

    string x = "Ahmad";
    cout << x.replace(1,4,"li") << endl;
    
    // Ali
  10. insert Method:
    Description: Inserts characters into the string.
    Parameters: Takes starting index and string to insert as parameters.
    Example:

    string x = "Ahmad";
    cout << x.insert(5," Ali") << endl;
    
    // Ahmad Ali

These are some commonly used string methods in C++. Remember to include the <string> header for using these methods.

OOP in C++

Object-Oriented Programming (OOP) is an acronym that stands for the following concepts:

In procedural programming, the emphasis lies in writing procedures or functions designed to perform operations on data. In contrast, object-oriented programming revolves around the creation of objects that encapsulate both data and functions.

Object-oriented programming offers numerous advantages over procedural programming:

  1. OOP execution is typically faster and more straightforward.
  2. OOP provides a well-defined structure for organizing programs.
  3. OOP promotes the “Don’t Repeat Yourself” (DRY) principle in C++, reducing code duplication and enhancing code maintainability, modification, and debugging.
  4. OOP facilitates the development of highly reusable applications with reduced code volume and shorter development timelines.

As a helpful tip, adhering to the “Don’t Repeat Yourself” (DRY) principle involves identifying and extracting common code segments within an application, centralizing them for reuse rather than duplicating them throughout the codebase.

Review Function

The Structure of C++ program

#include <iostream>
using namespace std;

int main()
{
    cout << "Welcome to OOP in C++" << endl;

    return 0;
}

Let’s break down the structure and purpose of each command line in the provided C++ code:

#include <iostream>

Structure: This line begins with the #include preprocessor directive, followed by the <iostream> header file enclosed in angle brackets.

Purpose: This line includes the Input/Output Stream Library (iostream), which is essential for performing input and output operations in C++. It provides functionalities like cin for input and cout for output.

using namespace std;

Structure: The using namespace std; line declares that the code will be using the std namespace.

Purpose: The std namespace contains the standard C++ library components, including the cout and endl used in the code. By including this line, you can use these components without explicitly specifying the namespace each time you use them.

int main()
{

Structure: This line marks the beginning of the main function, which is the entry point of every C++ program.

Purpose: The main function is where the program execution starts. It is required in every C++ program, and the code within the curly braces {} defines the body of the main function.

cout << "Welcome to OOP in C++" << endl;

Structure: This line uses the cout object to output the text “Welcome to OOP in C++” to the console. The << operator is used for streaming the text to the output.

Purpose: This line is responsible for displaying a welcome message on the console, indicating that the program is focused on Object-Oriented Programming (OOP) in C++.

    return 0;
}

Structure: The return 0; line signifies the end of the main function. The 0 is returned to the operating system, indicating that the program executed successfully.

Purpose: The return 0; line is a common way to indicate a successful termination of the program. The value 0 is typically returned to the operating system to signify that the program executed without errors.

Libraries in C++

In C++, a library is a collection of pre-compiled functions, classes, and procedures that can be used by a program. These libraries provide a set of functionalities that can be utilized to perform common tasks, ranging from basic input/output operations to complex mathematical computations. Libraries offer a way to modularize code, promote code reuse, and streamline development by providing ready-made solutions for various tasks.

Here are some key aspects of libraries in C++:

  1. Standard Template Library (STL):
    The C++ Standard Library, often referred to as the Standard Template Library (STL), is a core part of C++. It includes a wide range of generic algorithms (e.g., sorting, searching) and data structures (e.g., vectors, lists, maps) that are implemented using templates. The STL simplifies programming by providing efficient and generic solutions to common problems.
  2. Header Files:
    C++ libraries are typically distributed as header files (with the extension .h or .hpp) and implementation files (with the extension .cpp). Header files contain declarations of functions, classes, and other entities that can be used in your program, while the implementation files contain the actual code.
  3. IOStream Library:
    The iostream library is a fundamental part of the C++ Standard Library and provides functionality for input and output operations. It includes cin (for input) and cout (for output), among other stream classes. Here’s an example of using the iostream library:

    #include <iostream>
    
    int main() {
        std::cout << "Hello, C++!" << std::endl;
        return 0;
    }
    
  4. Math Library:
    The cmath library provides a set of mathematical functions, such as trigonometric, logarithmic, and exponential functions.
  5. User-Defined Libraries:
    Apart from the standard libraries, you can create your own libraries to encapsulate and organize your code. This involves creating header files that declare the functions and classes, and implementation files that define their behavior. You can then include your custom library in other C++ programs.

Function in C++

In the realm of programming, functions play a pivotal role in organizing code, enhancing reusability, and promoting a structured approach to problem-solving. In C++, a function is a self-contained unit of code designed to perform a specific task or achieve a particular objective. It encapsulates a set of instructions, allowing you to break down a complex program into smaller, more manageable pieces.

Key Concepts
1. Modularity:
Functions enable the decomposition of a program into smaller, more manageable modules. Each function handles a specific aspect of the overall functionality, promoting a modular and organized code structure.

2. Reusability:
Once a function is defined, it can be reused in different parts of the program or even in other programs. This promotes the “Don’t Repeat Yourself” (DRY) principle, saving both time and effort.

3. Abstraction:
Functions provide a level of abstraction, allowing you to focus on high-level functionality without getting bogged down by the implementation details. This abstraction enhances code readability and simplifies the debugging process.

4. Parameters and Return Values:
Functions can accept input parameters and return values, allowing for dynamic and interactive code. Parameters provide a way to pass information into a function, while return values allow functions to communicate results back to the calling code.

Basic Syntax
A typical C++ function follows this basic syntax:

returnType functionName(parameterType1 parameterName1, parameterType2 parameterName2, ...) {
    // Function body: Code to perform the desired task
    // Optionally, a return statement to provide a result back to the caller
}

Let’s break down the components:

returnType: Specifies the type of data the function will return (if any).
functionName: The unique identifier for the function.
parameters: Input values that the function receives.
functionBody: The set of instructions defining the function’s behavior.

Example:

#include <iostream>
using namespace std;
int sum(int x, int y)
{
    return x + y;
}

int main()
{
    cout << sum(10,20) << endl;
    return 0;
}

This C++ code is a simple program that calculates and displays the sum of two numbers.

  • Define a Sum Function:
int sum(int x, int y)
{
    return x + y;
}

This block of code creates a function called sum. It takes in two numbers (x and y) and gives back their sum.

  • Use the Sum Function in the Main Part:
int main()
{
    cout << sum(10, 20) << endl;
    return 0;
}

Here, the main part is like the director of the program. It says, “Hey, calculate the sum of 10 and 20 using the sum function, and show me the result on the screen.” The endl is like pressing Enter on the keyboard; it moves to the next line.

  • Run the Program:

When you run this program, it does the calculation (10 + 20) inside the sum function, then displays the result (30) on the screen. The return 0; part tells the computer that everything went well.

 

Review Arrays

Classes

Constructors

Unordered list items

The HTML  element represents an unordered list of items, typically rendered as a bulleted list. An unordered list starts with the <ul> tag. Each list item starts with the <li> tag. The list items will be marked with bullets (small black circles) by default:

  • List Item [direction] Docly Settings > Header > Logo [/direction]
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

The HTML  element represents an ordered list of items — typically rendered as a numbered list. An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list items will be marked with numbers by default:

  1. List Item [direction] Docly Settings > Header > Logo [/direction]
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

STL C++

The Standard Template Library (STL) encompasses a collection of C++ template classes designed to furnish essential programming data structures and functionalities, including lists, stacks, arrays, and more. This library comprises container classes, algorithms, and iterators, making it a versatile toolset. STL’s components are parameterized, contributing to its generality. Proficiency in working with template classes is a prerequisite for effectively utilizing STL.

Introduction to Standard Template Library

vector

Deque

List

Data Structures

A data structure serves as a repository designed for the storage and structured organization of data, enabling efficient access and updates when utilized on a computer.

Introduction

Complexity

Introduction to Stack

JAVA

Java is a high-level, versatile, and widely-used programming language known for its portability and flexibility. Originally developed by Sun Microsystems and now maintained by Oracle Corporation, Java has a vast ecosystem of libraries and tools that make it a popular choice for various software applications, from web development to mobile apps and enterprise-level systems. Java is appreciated for its ability to run on multiple platforms, its strong security features, and its support for object-oriented programming. It’s a key technology for building dynamic websites, interactive web applications, and mobile apps, making it a vital tool in the world of software development.

Introduction

Installing the Java Development Tools

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header Menu Element . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

Tooltip text  mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. Tooltip Content  off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Escape Sequences and Comments

table is a collection of related data held in a table format within a database. It consists of columns and rows.

In relational databases, and flat file databases, a table is a set of data elements (values) using a model of vertical columns (identifiable by name) and horizontal rows, the cell being the unit where a row and column intersect.[

Configuration Options

Since Docly is based on Bootstrap 4, so you can safley use Bootstrap’s table classes to style your table. We also added more table styles and functionality to our template.

Name
background Color
The background color for the main area of the chart. Can be either a simple HTML color string, for example: 'red' or '#00cc00', or an object with the following properties.
background Color.stroke
The color of the chart border, as an HTML color string.

Type: string
Default: '#666'
background Color.stroke Width

The border width, in pixels.

Type: number
Default: 0

background Color.fill

The chart fill color, as an HTML color string.

Type: string
Default: 'white'

chartArea

An object with members to configure the placement and size of the chart area (where the chart itself is drawn, excluding axis and legends). Two formats are supported: a number, or a number followed by %. A simple number is a value in pixels; a number followed by % is a percentage. Example: chartArea:{left:20,top:0,width:'50%',height:'75%'}

Type: object
Default: null
chartArea.backgroundColor
Chart area background color. When a string is used, it can be either a hex string (e.g., '#fdc') or an English color name. When an object is used, the following properties can be provided:
  • stroke: the color, provided as a hex string or English color name.
  • strokeWidth: if provided, draws a border around the chart area of the given width (and with the color of stroke).
Type: string or object
Default: 'white'
chartArea.left

How far to draw the chart from the left border.

Type: number or string
Default: auto
chartArea.top
How far to draw the chart from the top border.

Type: number or string
Default: auto

Default Tables

Since Docly is based on Bootstrap 4, so you can safley use Bootstrap’s table classes to style your table. We also added more table styles and functionality to our template.

Sample ID Reading #1 Reading #2 Reading #3 Reading #4
Manually
555
475
756
155
Shortcuts
478
754
124
688
Content
987
10
745
4187
Pomodoro timer
4187
688
478
756
Keyboard
4455
654
784
657
Manually
784
784
621
157
Timeline
884
254
105
356
Pomodoro
356
884
465
644

Basic Tables

Since Docly is based on Bootstrap 4, so you can safley use Bootstrap’s table classes to style your table. We also added more table styles and functionality to our template.

# First Name Last Name Username Email
Manually
555
475
756
155
Shortcuts
478
754
124
688
Content
987
10
745
4187
Pomodoro timer
4187
688
478
756
Keyboard
4455
654
784
657
Manually
784
784
621
157
Timeline
884
254
105
356
Pomodoro
356
884
465
644

Dark Mode Table

Since Docly is based on Bootstrap 4, so you can safley use Bootstrap’s table classes to style your table. We also added more table styles and functionality to our template.

# First Name Last Name Username Email
Manually
555
475
756
155
Shortcuts
478
754
124
688
Content
987
10
745
4187
Pomodoro timer
4187
688
478
756
Keyboard
4455
654
784
657
Manually
784
784
621
157
Timeline
884
254
105
356
Pomodoro
356
884
465
644

Data Types

Arithmetic Operators

OOP in JAVA

Object-Oriented Programming (OOP) is a fundamental programming paradigm used extensively in Java. In OOP, the core concept is organizing code into “objects,” which are instances of classes representing real-world entities, concepts, or data structures. Here’s how OOP works in Java:

Introduction

Classes and Objects

Constructor (No-Arg, Parameterized, Default)

Constructor (Copy Constructor) / Finalizers vs Destructor

Static keyword (Static Variable and Methods)

Static keyword (Static Block - Static Class)

Passing Objects to Methods (by Value vs by Reference / Passing Objects as Arguments)

Inheritance (Types of Inheritance / Access Modifiers and inheritance)

Inheritance (Super Keyword / Object Class / Package-Private vs Protected)

Polymorphism (Method Overloading and Method Overriding)

Polymorphism(Explanation of Examples, Static Methods)

Polymorphism(Late binding "Dynamic Polymorphism", Early binding "Static Polymorphism")

Types of Relationships (Association, Aggregation "has-a", Composition "part-of")

Problem Solving

Problem-solving in programming using C++ involves the process of addressing complex challenges by leveraging the features and capabilities of the C++ programming language. Here are key elements of problem-solving in C++:

Introduction

Coding Challenge Websites (Codeforces, Beecrowd)

What is ACM ICPC?

The ACM International Collegiate Programming Contest (ICPC) is an annual multi-tiered competitive programming competition among the universities of the world. It is the world’s oldest, largest, and most prestigious programming contest.

The ICPC is organized by the Association for Computing Machinery (ACM) and is sponsored by IBM. The contest is open to all undergraduate students who are enrolled in a full-time degree program at an accredited university.

The ICPC consists of three rounds:

  • Regional Contests: Regional contests are held around the world in the fall and winter months. The top teams from each regional contest advance to the World Finals.
  • World Finals: The World Finals are held each spring and bring together the top teams from around the world to compete for the championship title.
  • Online Contests: Online contests are held throughout the year and provide students with an opportunity to practice their competitive programming skills.

ACM ICPC Format

The ICPC is a team competition. Each team consists of three students and one coach. The teams are given five hours to solve 10-12 programming problems. The problems are typically challenging and require the teams to use a variety of programming techniques.

The teams submit their solutions to the contest judges. The judges then test the solutions on a set of secret test cases. The teams are awarded points for each problem that they solve correctly. The team with the most points at the end of the contest wins.

ACM ICPC Prizes

The ACM ICPC prizes are awarded to the top teams at the World Finals. The first-place team receives a gold medal and a cash prize of $15,000. The second-place team receives a silver medal and a cash prize of $10,000. The third-place team receives a bronze medal and a cash prize of $5,000.

ACM ICPC Benefits

Participating in the ACM ICPC has many benefits for students. It is a great way to improve your programming skills, meet other talented programmers, and compete on a global stage. The ICPC is also a great way to impress potential employers.

ACM ICPC Statistics

  • The ACM ICPC was first held in 1970.
  • Over 500,000 students from over 3,000 universities compete in the ICPC each year.
  • The ICPC is held in over 100 countries.
  • The ICPC World Finals have been held in over 20 different cities around the world.

ACM ICPC Notable Alumni

Some notable alumni of the ACM ICPC include:

  • Sergey Brin and Larry Page, co-founders of Google
  • Reid Hoffman, co-founder of LinkedIn
  • Max Levchin, co-founder of PayPal
  • Eric Schmidt, former CEO of Google
  • Jeff Dean, Google AI researcher

ACM ICPC Tables and Charts

The following tables and charts provide additional information about the ACM ICPC:

Table 1: ACM ICPC World Finals Winners

Year Winner
2023 Moscow Institute of Physics and Technology
2022 Saint Petersburg State University
2021 Moscow Institute of Physics and Technology
2020 Saint Petersburg State University
2019 Moscow Institute of Physics and Technology

Table 2: ACM ICPC Regional Contests

| Region | Number of Contests | |—|—|—| | Africa | 1 | | Asia | 18 | | Europe | 13 | | Latin America | 6 | | North America | 10 |

Chart 1: ACM ICPC Participation by Country

[Chart showing the top 10 countries by number of ACM ICPC participants]

Chart 2: ACM ICPC World Finals Participation by Region

[Chart showing the number of teams from each region that participated in the ACM ICPC World Finals in 2023]

Conclusion

The ACM ICPC is a challenging and rewarding competition for students who are interested in competitive programming. It is a great way to improve your programming skills, meet other talented programmers, and compete on a global stage.

atcoder

Find frequency using Array & Map

Count distinct elements using Array & Set, CSES Distinct Numbers

React

React empowers you to construct user interfaces by assembling discrete elements known as components. Craft your custom React components, such as Thumbnail, LikeButton, and Video, and seamlessly integrate them to create complete screens, pages, and applications.

What is Babel

HTML vs JSX

Introduction

Virtual DOM

Environment Setup

What is JSX,

Components

Android

Android development refers to the process of creating applications (apps) for mobile devices that run on the Android operating system. Android is the most widely used mobile operating system globally, making it a significant platform for developers.

Inroduction

Install Android Studio on Windows

Install Android Studio on Mac

Activity Layout Editor Change Font Size

.java vs .xml

Header Settings

In the Header settings section, you will get a lot of header customization options. In this section, you can change the logo and set the menu button, navigation bar settings etc.

Theme updating issue

Sometimes, your website may break when you update the new version of the theme.

You have to delete the Gullu core plugin before installing the updated theme in this case. Then install the plugin again from Appearance > Install plugins after installing the new version.

Theme Installation

Extract the zipped package downloaded from ThemeForest to your desktop, in the extracted package you will find the gullu.zip file which is the WordPress theme.

You can install the theme in two ways:

FTP: Extract gullu.zip file and upload the extracted folder to /wp-content/themes/ folder on your server.

WordPress: Navigate to Appearance -> Add New Themes -> Upload page. Select gullu.zip file. Press the Install Now button to upload and install the theme.

After uploading the theme, you have to activate it. Navigate to Appearance -> Themes page to activate the theme.

Optimize Images

Optimizing your images will helps your WordPress site load faster.

Download and activate WP Smush.it This plugin will optimize every image you upload and you can use the Bulk Smush.it feature to smush all of your uploaded images.

Alternatives to WP Smush.it include EWWW Image Optimizer, CW Image Optimizer, Imsanity and Hammy. Many WordPress users prefer using these plugins as they do not rely on an external server to process your images.

Getting Started

Before building your site, better take a look at this section.

Theme Installation

Extract the zipped package downloaded from ThemeForest to your desktop, in the extracted package you will find the charles.zip file which is the WordPress theme.

You can install the theme in two ways:

FTP: Extract charles.zip file and upload the extracted folder to /wp-content/themes/ folder on your server.

WordPress: Navigate to Appearance -> Add New Themes -> Upload page. Select charles.zip file. Press the Install Now button to upload and install the theme.

After uploading the theme, you have to activate it. Navigate to Appearance -> Themes page to activate the theme.

Demo Import

If you want your site to look like exactly the ‘Charles’ demos then you have to import the demo content successfully.

We integrated the One Click Demo installation feature to ‘Charles’ WordPress theme. You can import all demo content just by a click only.

OneClick Demo Installation Process

  • Install the theme and active it. Then install all required plugins. Make sure all the required plugins are activated.
  • After activating all the required plugins navigate to Appearance > ‘One Click Demo Import’ menu from the WordPress dashboard.

Note: If the option data do not import then you have to import it manually. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

The recommended method to import the demo content.

If you failed to import the demo content by one click then you have to follow the below steps to import the demo content manually.  You will get all demo content data with the theme package. You will find the demos in ‘charles>inc/demo{disired-demo-number} this path.

  • Navigate to Tools > Import then install the WordPress plugin and click on the ‘Run Importer’. Upload here the ‘theme_content.xml’ file.
  • Install the Widget Importer & Exporter plugin to import the demo widgets. Then navigate to Tools > Widget Importer & Exporter and upload here the ‘widget_data.wie’ file.
  • Now you have to import the Dental Options as like the demo. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

Required Plugins

After installing the theme you most have to install the ‘Charles Core’, ‘Elementor’ and ‘Piklist’ plugins to import the demo content as well and work the theme correctly.

You will find all required and recommended plugins at Appearance > Install Plugins.

System Requirements

To use Charles you need to have a WordPress 4.0 (or higher version) site with PHP 5.4 or more running on your hosting server. If you’ve already installed WordPress on your server and your site is up, that’s great. For help regarding WordPress installation, please see this WordPress Codex link.

Some more resources from WordPress Codex:

Theme Installation

Extract the zipped package downloaded from ThemeForest to your desktop, in the extracted package you will find the charles.zip file which is the WordPress theme.

You can install the theme in two ways:

FTP: Extract charles.zip file and upload the extracted folder to /wp-content/themes/ folder on your server.

WordPress: Navigate to Appearance -> Add New Themes -> Upload page. Select charles.zip file. Press the Install Now button to upload and install the theme.

After uploading the theme, you have to activate it. Navigate to Appearance -> Themes page to activate the theme.

Getting Started

Before building your site, better take a look at this section.

Theme Installation

Extract the zipped package downloaded from ThemeForest to your desktop, in the extracted package you will find the aprimo.zip file which is the WordPress theme.

You can install the theme in two ways:

FTP: Extract aprimo.zip file and upload the extracted folder to /wp-content/themes/ folder on your server.

WordPress: Navigate to Appearance -> Add New Themes -> Upload page. Select aprimo.zip file. Press the Install Now button to upload and install the theme.

After uploading the theme, you have to activate it. Navigate to Appearance -> Themes page to activate the theme.

Contact Page

You can create and configure the Contact page by following the below steps-

Creating the Contact page

Navigate from your WordPress dashboard to Pages > Add New. Then Select the page template as “Contact Page” and click on the Publish button to create the Contact page.

Configuring the Contact page

Go to Theme Settings > Contact Page Settings from your WordPress dashboard to configure the Contact page settings. Here you will get everything you need to change the Contact page template.

Demo Import

You have to import the demo content successfully if you want your site look exactly like the ‘Aprimo’ demo.

We integrated the One Click Demo installation feature to ‘Aprimo‘ WordPress theme. You can import all demo contents just by a click only.

OneClick Demo Installation Process

  • Install the theme and active it. Then install all required plugins. Make sure all the required plugins are activated.
  • After activating all the required plugins navigate to Appearance > ‘One Click Demo Import’ menu from the WordPress dashboard.

Note: If the Theme Settings data do not import then you have to import it manually. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file. You will find the options.txt in this path- inc/demo{disired-demo-number}/txt

Find your page:

Every demo has 3 pages including the  Default homepage, Gradient homepage, and the Particle background homepage. Navigate to Pages from your WordPress dashboard menu to see all pages. Take a look the below screenshot-
Navigate to Settings > Reading to set your specific page as the front page (homepage).

The recommended method to import the demo content.

If you failed to import the demo content by one click then you have to follow the below steps to import the demo content manually. You will get all demo content data with the theme package. You will find the demos in ‘aprimo>inc/demo{disired-demo-number}’ this path.

  • Navigate to Tools > Import then install the WordPress plugin and click on the ‘Run Importer’. Upload here the ‘contents.xml’ file.
  • Install the Widget Importer & Exporter plugin to import the demo widgets. Then navigate to Tools > Widget Importer & Exporter and upload here the ‘widgets.wie’ file.
  • Now you have to import the Dental Options as like the demo. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

 

Required plugins

After installing the theme you most have to install the ‘Faster Core’, ‘Visual composer’ and ‘Codestar Framework’ plugins to import the demo content as well and work the theme correctly.

You will find all required and recommended plugins at there Appearance > Install Plugins.

Adipisci quaerat quia?

Cras tenetur aute doloribus quibusdam interdum fugit, diam hac mollis? Mollis fames veritatis phasellus facilis nascetur nonummy, eleifend placerat nisl enim eveniet corrupti imperdiet. Incidunt duis sequi mollit, hendrerit quod! Nostra tempus cum, lacus, ut, sapien error sagittis ornare blandit fugit turpis? Facere qui reprehenderit dolorum accusantium adipisci! Quo taciti, nascetur leo velit ultricies? Vulputate cupiditate! Luctus magni lobortis ducimus, autem arcu, illum aliquam facilisi suspendisse, vivamus at. Adipisci vestibulum, egestas dictum? Quas placeat impedit nesciunt nascetur justo tempora accumsan? Torquent! Viverra pariatur mi? Per itaque curae! Class, wisi condimentum exercitationem ad sequi voluptatum expedita. Veniam vero magnis sapien feugiat.

Convallis suscipit? Auctor distinctio erat interdum. Fringilla doloribus phasellus nostrud? Asperiores diam, quam animi irure mi diam eiusmod! Ridiculus! Excepturi sociis ipsa mattis. Sapiente laoreet massa, ultricies maxime, veritatis mollitia qui maecenas tempus aenean, inventore fugit, molestias iaculis rerum totam senectus lacus tellus wisi blanditiis irure volutpat habitasse, sem dignissim a minima, voluptatem aspernatur beatae volutpat, ratione sodales omnis ipsum beatae sollicitudin taciti accusamus volutpat ex? Elementum officiis saepe purus! Dicta placerat. Iusto massa porttitor! Anim doloribus eu varius ridiculus risus sem lacinia eleifend laboriosam tristique aspernatur commodi ex primis! Excepteur, occaecati corrupti praesentium, iaculis dui, curae at? Blanditiis rutrum.

Blanditiis, aute suspendisse eget! Dis vulputate fermentum pellentesque nec, dapibus? Do eligendi, voluptatibus mollis nobis cras. Aptent aut. Sed rem, exercitationem nullam, eleifend risus? Porttitor, nam, pulvinar est, quos tincidunt, voluptatibus qui iaculis pharetra tincidunt, ridiculus! Sociosqu harum culpa eum ab ullam, hac possimus. Fugit, laoreet fermentum occaecati. Mus nam? Risus pulvinar, voluptas gravida porttitor magna molestias! Suspendisse, ipsam laborum. Sociosqu inceptos! Laudantium pariatur. Dui, numquam? Exercitationem cupidatat adipiscing at voluptatem accusantium occaecat error quidem eius ullamcorper tempore soluta quod pellentesque officia eos voluptatum condimentum. Donec tempore, sem est netus quisquam, tempus euismod dolorum laboris officiis ultrices ipsum libero sodales.

Header Settings

In the Header settings section, you will get a lot of header customization options. In this section, you can change the logo and change the page/post’s Title bar padding, Page margin-top, Title bar overlay color etc.

Updating Your Theme

We are strongly recommended to install “Envato Toolkit” plugin for ease of use. Once necessary plugin installed and activated “Envato Toolkit” menu will be available at your admin side.

Important : If you have missing plugins or having issues to install any of them, all the related could be found under “recommended-plugins” folder within the downloaded package.

User Account Information

To obtain your API Key, visit your “My Settings” page on any of the Envato Marketplaces. Once a valid connection has been made any changes to the API key below for this username will not effect the results for 5 minutes because they’re cached in the database. If you have already made an API connection and just purchase a theme and it’s not showing up, wait five minutes and refresh the page. If the theme is still not showing up, it’s possible the author has not made it available for auto install yet.

Marketplace Username: Enter your Envato marketplace username.

Secret API Key: Enter your Envato marketplace Secret API Key (http://themeforest.net/user/[your-username]/api_keys/edit, Login to your Themeforest account, Settings > API Key)

Backup Information

This plugin will automatically save your theme as a ZIP archive before it does an upgrade. The directory those backups get saved to is wp-content/envato-backups. However, if you’re experiencing problems while attempting to upgrade, it’s likely to be a permissions issue and you may want to manually backup your theme before upgrading. Alternatively, if you don’t want to backup your theme you can check the box below.

Skip Theme Backup: Strongly recommended keep unchecked.

Alternative Way

You can also update the theme by replacing the old theme folder. First go to your theme directory then delete the theme folder and paste the new version of the theme.

Sample Doc Title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Theme Installation

Extract the zipped package downloaded from ThemeForest to your desktop, in the extracted package you will find the aprimo.zip file which is the WordPress theme.

You can install the theme in two ways:

FTP: Extract aprimo.zip file and upload the extracted folder to /wp-content/themes/ folder on your server.

WordPress: Navigate to Appearance -> Add New Themes -> Upload page. Select aprimo.zip file. Press the Install Now button to upload and install the theme.

After uploading the theme, you have to activate it. Navigate to Appearance -> Themes page to activate the theme.

Optimize Images

Optimizing your images will helps your WordPress site load faster.

Download and activate WP Smush.it This plugin will optimize every image you upload and you can use the Bulk Smush.it feature to smush all of your uploaded images.

Alternatives to WP Smush.it include EWWW Image OptimizerCW Image OptimizerImsanity and Hammy. Many WordPress users prefer using these plugins as they do not rely on an external server to process your images.

Header Settings

In the Header settings section, you will get a lot of header customization options. In this section, you can change the logo and set the menu button, navigation bar settings etc.

Updating Your Theme

We are strongly recommended to install “Envato Toolkit” plugin for ease of use. Once necessary plugin installed and activated “Envato Toolkit” menu will be available at your admin side.

Important : If you have missing plugins or having issues to install any of them, all the related could be found under “recommended-plugins” folder within the downloaded package.

User Account Information

To obtain your API Key, visit your “My Settings” page on any of the Envato Marketplaces. Once a valid connection has been made any changes to the API key below for this username will not effect the results for 5 minutes because they’re cached in the database. If you have already made an API connection and just purchase a theme and it’s not showing up, wait five minutes and refresh the page. If the theme is still not showing up, it’s possible the author has not made it available for auto install yet.

Marketplace Username: Enter your Envato marketplace username.

Secret API Key: Enter your Envato marketplace Secret API Key (http://themeforest.net/user/[your-username]/api_keys/edit, Login to your Themeforest account, Settings > API Key)

Backup Information

This plugin will automatically save your theme as a ZIP archive before it does an upgrade. The directory those backups get saved to is wp-content/envato-backups. However, if you’re experiencing problems while attempting to upgrade, it’s likely to be a permissions issue and you may want to manually backup your theme before upgrading. Alternatively, if you don’t want to backup your theme you can check the box below.

Skip Theme Backup: Strongly recommended keep unchecked.

Alternative Way

You can also update the theme by replacing the old theme folder. First go to your theme directory then delete the theme folder and paste the new version of the theme.

Optimize Images

Optimizing your images will helps your WordPress site load faster.

Download and activate WP Smush.it This plugin will optimize every image you upload and you can use the Bulk Smush.it feature to smush all of your uploaded images.

Alternatives to WP Smush.it include EWWW Image OptimizerCW Image OptimizerImsanity and Hammy and Compress JPEG & PNG images

Many WordPress users prefer using these plugins as they do not rely on an external server to process your images.

Theme updating issue

Sometimes, your website may break when you update the new version of the theme.

You have to delete the Charles core plugin before installing the updated theme in this case. Then install the plugin again from Appearance > Install plugins after installing the new version.

Doc title example

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Updating Your Theme

We are strongly recommended to install “Envato Toolkit” plugin for ease of use. Once necessary plugin installed and activated “Envato Toolkit” menu will be available at your admin side.

Important : If you have missing plugins or having issues to install any of them, all the related could be found under “recommended-plugins” folder within the downloaded package.

User Account Information

To obtain your API Key, visit your “My Settings” page on any of the Envato Marketplaces. Once a valid connection has been made any changes to the API key below for this username will not effect the results for 5 minutes because they’re cached in the database. If you have already made an API connection and just purchase a theme and it’s not showing up, wait five minutes and refresh the page. If the theme is still not showing up, it’s possible the author has not made it available for auto install yet.

Marketplace Username: Enter your Envato marketplace username.

Secret API Key: Enter your Envato marketplace Secret API Key (http://themeforest.net/user/[your-username]/api_keys/edit, Login to your Themeforest account, Settings > API Key)

Backup Information

This plugin will automatically save your theme as a ZIP archive before it does an upgrade. The directory those backups get saved to is wp-content/envato-backups. However, if you’re experiencing problems while attempting to upgrade, it’s likely to be a permissions issue and you may want to manually backup your theme before upgrading. Alternatively, if you don’t want to backup your theme you can check the box below.

Skip Theme Backup: Strongly recommended keep unchecked.

Alternative Way

You can also update the theme by replacing the old theme folder. First go to your theme directory then delete the theme folder and paste the new version of the theme.

Contact Page

You can create and configure the Contact page by following the below steps-

Creating the Contact page

Navigate from your WordPress dashboard to Pages > Add New. Then Select the page template as “Contact Page” and click on the Publish button to create the Contact page.

Configuring the Contact page

Go to Theme Settings > Contact Page Settings from your WordPress dashboard to configure the Contact page settings. Here you will get everything you need to change the Contact page template.

This is a doc title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Your theme (Gullu) contains outdated copies

This message appears when WooCommerce plugin changes any of its core files. Usually, this happens when WooCommerce publishes a major update or any minor update after the major update. (Example. 3.3, 3.3.1)

We recommend clients to always read the changelog of your theme if the latest update of the theme supports that version of WooCommerce as noted in the plugin itself throughout the theme.

If you recently updated WooCommerce, you might have spotted a notice like this on your Plugins page.

If you see that the latest version of the theme doesn’t support the released WooCommerce version then please wait until we release a theme update that will support the latest version of this plugin.

If you accidentally updated the plugin then don’t worry, we probably are working on the update and when the theme update is ready you will be notified by email if you have already enabled.

Demo Import

If you want your site to look like exactly the ‘Gullu’ demos then you have to import the demo content successfully.

We integrated the One Click Demo installation feature to ‘Gullu’ WordPress theme. You can import all demo content just by a click only.

OneClick Demo Installation Process

  • Install the theme and activate it. Then install all the required plugins. Make sure all the required plugins are activated.
  • After activating all the required plugins navigate to Appearance > ‘One Click Demo Import’ menu from the WordPress dashboard.

Note: If the option data do not import then you have to import it manually. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

The recommended method to import the demo content.

If you failed to import the demo content by one click then you have to follow the below steps to import the demo content manually.  You will get all demo content data with the theme package. You will find the demos in ‘gullu>inc/demo{disired-demo-number} this path.

  • Navigate to Tools > Import then install the WordPress plugin and click on the ‘Run Importer’. Upload here the ‘theme_content.xml’ file.
  • Install the Widget Importer & Exporter plugin to import the demo widgets. Then navigate to Tools > Widget Importer & Exporter and upload here the ‘widget_data.wie’ file.
  • Now you have to import the Dental Options as like the demo. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

How to update premium plugins?

We have integrated some premium plugins with the theme and bundled those plugins with the theme. You don’t have to input your Themeforest product ID to unlock any theme features. We are not providing the third party plugin’s license along with the theme.

We are providing the plugins file only and we are continuously updating the bundled plugins with the theme updates. You can install/get those plugins on Appearance > Instal Plugins. Or you can get the plugin files in the rogan/inc/tgm/plugins folder.

Language Translations

All of our Themes are able to be translated into any language. The process of translating the theme is a user responsibility. The following instructions are given as guidance.

  1. Open wp-config.php and replace this: define ('WPLANG', ''); with this (substitute the language string (bg_BG) with your own!): define ('WPLANG', 'bg_BG');
  2. Download and install POEDIT
  3. Connect to your site -> open your theme/languages directory
  4. Download the default.pot file and open it with POEDIT.
  5. Translate file and save it as bg_BG (the file name must match with the string you inserted into wp-config.php)
  6. Two files will be generated after save. bg_BG.pot and bg_BG.mo
  7. Upload the .mo and .pot files into wp-content/themes/your-theme/languages folder
Your WordPress installation should be in the language you intend on using the site.

if

The if statement is a conditional statement in C++ that allows you to execute code based on a condition. The general syntax of an if statement is as follows:

if (condition) {
  // code to execute if the condition is true
}

The condition can be any Boolean expression. If the condition evaluates to true, the code block inside the if statement is executed. If the condition evaluates to false, the code block inside the else statement is executed.

Here is an example of an if statement:

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    cin >> x;
    if (x > 0)
        cout << "This number is Positive" << endl;

    return 0;
}

Output:

  • Case 1: if you entered a positive digit like 5, your if condition will be true and the block of code that follows the condition will be executed.
    This number is Positive
  • Case 2: if you entered zero or a negative digit like -5, your if condition will be false and the block of code that follows the condition will not be executed which means that nothing will appear on your result screen.

Demo Import

If you want your site to look like exactly the ‘Charles’ demos then you have to import the demo content successfully.

We integrated the One Click Demo installation feature to ‘Charles’ WordPress theme. You can import all demo content just by a click only.

OneClick Demo Installation Process

  • Install the theme and active it. Then install all required plugins. Make sure all the required plugins are activated.
  • After activating all the required plugins navigate to Appearance > ‘One Click Demo Import’ menu from the WordPress dashboard.

Note: If the option data do not import then you have to import it manually. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

The recommended method to import the demo content.

If you failed to import the demo content by one click then you have to follow the below steps to import the demo content manually.  You will get all demo content data with the theme package. You will find the demos in ‘charles>inc/demo{disired-demo-number} this path.

  • Navigate to Tools > Import then install the WordPress plugin and click on the ‘Run Importer’. Upload here the ‘theme_content.xml’ file.
  • Install the Widget Importer & Exporter plugin to import the demo widgets. Then navigate to Tools > Widget Importer & Exporter and upload here the ‘widget_data.wie’ file.
  • Now you have to import the Dental Options as like the demo. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

C++

Welcome to the World of C++ Programming!

Hello, I’m Adel Nasim, the creator of Adel Nasim YouTube Channel, and I’m excited to guide you through the essentials of C++ programming. Whether you’re a novice or looking to deepen your skills, this written course, alongside my YouTube tutorials, is your comprehensive resource for mastering C++. We’ll cover everything from the basics to advanced concepts, ensuring you gain both theoretical knowledge and practical coding skills.

Get ready for a journey that blends theory with hands-on examples, equipping you with the confidence to tackle real-world challenges. Whether you’re building your programming foundation or enhancing existing skills, let’s dive into the world of C++ together. Happy coding!

Introduction

C++ is a cross-platform programming language that can be used to create high-performance applications. It is a general-purpose language, which means it can be used to develop a wide variety of software, including operating systems, games, embedded systems, and more.

C++ is a popular choice for developing high-performance applications because it gives programmers a high level of control over system resources and memory. It is also a very efficient language, which means that C++ programs typically run faster than programs written in other languages.

C++ is a relatively complex language to learn, but it is also a very powerful language. Once you have mastered the basics of C++, you will be able to develop almost any type of software you can imagine.

Why is C++?

C++ is one of the most popular programming languages in the world for a reason. It is a powerful, versatile, and efficient language that can be used to create a wide variety of software.

Here are just a few of the reasons why C++ is so popular:

  • Performance: C++ programs are typically very fast and efficient. This is because C++ gives programmers a high level of control over system resources and memory.
  • Versatility: C++ can be used to develop a wide variety of software, from operating systems to games to embedded systems.
  • Portability: C++ programs can be compiled and run on a variety of platforms, including Windows, macOS, Linux, and more.
  • Community: C++ has a large and active community of developers. This means that there is a wealth of resources available to help you learn and use C++.

Difference between C and C++

C++ was developed as an extension of the C programming language. Both languages have a similar syntax, but C++ adds a number of new features, including:

  • Classes and objects: C++ supports classes and objects, which provide a way to encapsulate data and code into reusable units.
  • Templates: C++ templates allow you to create generic functions and classes that can be used with different data types.
  • Exception handling: C++ provides exception handling features that allow you to deal with errors in a structured way.

Get Started

If you are interested in learning C++, there are a number of resources available to help you get started. There are many good books and tutorials available online, and there are also a number of C++ communities where you can ask for help and advice.

Once you have learned the basics of C++, you can start developing your own applications. There are a number of different C++ compilers and development environments available, so you can choose the one that best suits your needs.

Conclusion

C++ is a powerful and versatile programming language that can be used to create a wide variety of software. It is a popular choice for developing high-performance applications, and it is also a good choice for beginners because it is relatively easy to learn.

Getting Started

What is C++?

C++ is a general-purpose programming language that is used to create a wide range of applications, including operating systems, games, embedded systems, and web applications. C++ is known for its speed, efficiency, and flexibility.

Getting started with C++

To get started with C++, you will need to install a C++ compiler and IDE. A compiler is a program that converts C++ code into machine code that can be executed by a computer. An IDE is an integrated development environment that provides a variety of tools for writing, editing, compiling, and debugging C++ code.

Installing a C++ compiler and IDE

There are many different C++ compilers and IDEs available. For this tutorial, we will use Visual Studio for C++. Visual Studio is a free and powerful IDE that provides comprehensive support for C++ development.

To install Visual Studio for C++, visit the Visual Studio website and download the latest version.

Writing your first C++ program

Once you have installed Visual Studio for C++, you can start writing your first C++ program. To do this, create a new project and select the “C++ Console App” template.

Once you have created a new project, you can start writing C++ code in the main source file. The main source file is typically named main.cpp.

Here is a simple example of a C++ program:

C++
#include <iostream>
int main() {
  std::cout << "Hello, world!" << std::endl;
  return 0;
}

This program prints the message “Hello, world!” to the console.

Once you have written your C++ program, you can compile and run it by pressing F5.

Learning more about C++

Now that you have written your first C++ program, you can start learning more about the language. There are many resources available online and in libraries.

Here are a few tips for learning C++:

  • Start with the basics. Learn about variables, data types, operators, functions, and control flow statements.
  • Find a good tutorial or book. There are many resources available that can teach you the basics of C++.
  • Practice regularly. The best way to learn C++ is by writing code. Try to write simple programs at first, and gradually work your way up to more complex programs.
  • Use an IDE. An IDE can make it easier to write, edit, compile, and debug C++ code.

Conclusion

Getting started with C++ can be daunting, but it is also rewarding. C++ is a powerful and versatile language that can be used to create a wide range of applications.

By following the tips in this guide, you can start learning C++ today and start creating your own applications.

First Project in C++

 

Example:

C++

#include <iostream>
int main()
{ 
    std::cout << "Welcome to C++";
    return 0;
}


This is a simple C++ program that prints the message “Welcome to C++” to the console.

  • #include <iostream>: This line tells the compiler to include the header file iostream. This header file contains declarations for the standard input/output library.
  • int main(): This line defines the main function. The main function is the entry point for all C++ programs.
  • std::cout << “Welcome to C++”;: This line prints the message “Welcome to C++” to the console using the std::cout object.
  • return 0;: This line returns the value 0 from the main function. This indicates that the program terminated successfully.

When you compile and run this program, the following output will be printed to the console:

Welcome to C++

This is a very simple example of a C++ program, but it illustrates some of the basic concepts of the language, such as header files, functions, and input/output.

Escape Sequence

Escape sequences are special characters that are used to represent non-printing characters or to control the behavior of output streams. They are prefixed with a backslash (\).

Types of Escape Sequences

There are three types of escape sequences in C++:

  • Character escape sequences: These escape sequences represent non-printing characters, such as newline, tab, and backspace.
  • Hexadecimal escape sequences: These escape sequences represent characters using their hexadecimal values.
  • Octal escape sequences: These escape sequences represent characters using their octal values.

Common Escape Sequences

Here are some of the most common escape sequences in C++:

Escape Sequence Description
\n Newline
\t Tab
\\ Backslash
\" Double quote
\' Single quote
\? Question mark
\a Alert
\b Backspace
\f Form feed
\r Carriage return
\v Vertical tab
\x Hexadecimal escape sequence
\NNN Octal escape sequence

Using Escape Sequences

Escape sequences can be used in string and character literals. For example, the following code prints the string “Hello, world!” followed by a newline character:

C++
std::cout << "Hello, world!" << std::endl;

The std::endl object represents the newline character. It is equivalent to the escape sequence \n.

Escape sequences can also be used to represent non-printing characters, such as the tab character. For example, the following code prints the string “Hello, world!” followed by a tab character:

C++
std::cout << "Hello, world!" << '\t';

Example

Here are some more examples of how to use escape sequences in C++:

C++
// Print the string "This is a quote \" inside a string." 
std::cout << "This is a quote \" inside a string."; 

// Print the character 'a' with a backspace before it. 
std::cout << '\b' << 'a';

// Print the string "Hello, world!" followed by a newline character and a tab character. 
std::cout << "Hello, world!" << std::endl << '\t';
Conclusion

Escape sequences are a powerful tool that can be used to control the behavior of output streams and to represent non-printing characters in C++.

Variables vs Data type

Variables vs Data types in C++

Variables

Variables are named memory locations that can store data. They are declared using the var_name : data_type syntax. For example, the following code declares a variable named my_integer that can store an integer value:

C++
int my_integer;

Once a variable is declared, it can be used to store and retrieve data. For example, the following code assigns the value 10 to the my_integer variable:

C++
my_integer = 10;

The following code prints the value of the my_integer variable to the console:

C++
std::cout << my_integer << std::endl;

Output:

10

Data types

Data types define the type of data that a variable can store. C++ has a variety of data types, including integers, floating-point numbers, characters, strings, and Boolean values.

Here are some examples of data types in C++:

  • int: Stores integer values
  • float: Stores floating-point numbers
  • char: Stores a single character
  • string: Stores a sequence of characters
  • bool: Stores a Boolean value (true or false)

When a variable is declared, it must be assigned a data type. This tells the compiler how much memory to allocate for the variable and what type of data it can store.

For example, the following code declares a variable named my_string that can store a string value:

C++
string my_string;

The string data type is a special data type that is used to store sequences of characters.

Example

Here is an example of how to use variables and data types in C++:

C++
int my_integer = 10;
float my_floating_point_number = 3.14159;
char my_character = 'a';
string my_string = "Hello, world!";
bool my_boolean_value = true;

// Print the values of the variables.
std::cout << my_integer << std::endl;
std::cout << my_floating_point_number << std::endl;
std::cout << my_character << std::endl;
std::cout << my_string << std::endl;
std::cout << my_boolean_value << std::endl;

Output:

10
3.14159
a
Hello, world!
true

Variables and data types are essential concepts in C++. By understanding how they work, you can write more efficient and effective code.

Priorities & Calculations in C++

C++ has a set of operator precedence rules that determine the order in which expressions are evaluated. Operators with higher precedence are evaluated before operators with lower precedence.

Here is a table of the operator precedence rules in C++:

Operator Group Operators
Parentheses ()[]{}
Unary operators +-!~*&++--sizeofcasttype-name
Multiplication, division, and modulus */%
Addition and subtraction +-
Bitwise AND &
Bitwise OR |
Bitwise XOR ^
Equality and inequality ==!=
Less than, less than or equal to, greater than, greater than or equal to <<=>>=
Logical AND &&
Logical OR ||
Assignment =+=-=*=/=%=&=, `
Conditional operator ? :
Comma ,

When evaluating an expression, operators with the highest precedence are evaluated first, followed by operators with lower precedence.

Here are some examples of how operator precedence works in C++:

// Evaluates to 13.
int x = 5 * 2 + 3;

// Evaluates to 11.
int y = 5 + 2 * 3;

// Evaluates to true.
bool z = 5 < 10 && 10 > 5;

// Evaluates to false.
bool w = 5 > 10 || 10 < 5;

It is important to be aware of operator precedence when writing C++ code. Otherwise, you may get unexpected results.

Here is another example of how operator precedence can be used to control the order of evaluation:

// Evaluates to 16.
int a = (5 + 3) * 2;

// Evaluates to 11.
int b = 5 + (3 * 2);

In the first expression, the addition operator (+) has higher precedence than the multiplication operator (*). Therefore, the addition operation is evaluated first, and then the multiplication operation is evaluated.

In the second expression, the multiplication operation has higher precedence than the addition operation. Therefore, the multiplication operation is evaluated first, and then the addition operation is evaluated.

By understanding operator precedence, you can write more concise and efficient C++ code.

Basic Arithmetic & Casting

Basic Arithmetic in C++

C++ provides a number of operators for performing basic arithmetic operations. These operators include:

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Modulo (remainder)

These operators can be used to perform arithmetic operations on variables of different data types. For example, the following code performs arithmetic operations on variables of type int and float:

int a = 10;
float b = 3.14159;

// Add two integers.
int c = a + 5;

// Multiply two floats.
float d = b * 2;

// Divide two integers.
float e = a / 2;

// Calculate the remainder of a division operation.
int f = a % 2;

The results of these operations are stored in the corresponding variables.

Casting in C++

Casting is a way to convert a value from one data type to another. This can be useful when you need to perform arithmetic operations on values of different data types.

There are two types of casting in C++:

  • Implicit casting: Implicit casting occurs when the compiler automatically converts a value from one data type to another. For example, the following code implicitly converts the value of the variable a from type int to type float before performing the multiplication operation:

 

int a = 10;
float b = 3.14159;

// Multiply an int and a float.
float c = a * b;
  • Explicit casting: Explicit casting is when the programmer explicitly converts a value from one data type to another. This can be done using the cast operators (static_castreinterpret_castconst_cast, and dynamic_cast). For example, the following code explicitly converts the value of the variable b from type float to type int before performing the division operation:

 

int a = 10;
float b = 3.14159;

// Divide a float by an int.
int c = static_cast<int>(b) / a;

Explicit casting is often used to prevent errors that can occur when implicitly casting values.

Example

Here is an example of how to use casting in C++:

// Convert a string to an integer.
int a = static_cast<int>("10");

// Convert a floating-point number to a character.
char b = static_cast<char>(3.14159);

// Convert a pointer to an integer to a pointer to a float.
float *c = reinterpret_cast<float*>(pInt);

// Convert a const object to a non-const object.
int *d = const_cast<int*>(pInt);

Casting can be a powerful tool for converting values between different data types. However, it is important to use it carefully to avoid errors.

Prefix and Postfix & Compound assignment

Prefix and postfix operators in C++

Prefix and postfix operators are used to modify the value of a variable. The prefix operator is used before the variable, while the postfix operator is used after the variable.

The following table shows some of the most common prefix and postfix operators in C++:

Operator Prefix Postfix
++ Increments the value of the variable by 1. Increments the value of the variable by 1, and returns the original value.
Decrements the value of the variable by 1. Decrements the value of the variable by 1, and returns the original value.

Example

The following code shows how to use the prefix and postfix operators to increment the value of a variable:

int a = 10;

// Increment the value of a by 1 using the prefix operator.
a++;

// Increment the value of a by 1 using the postfix operator.
int b = a++

// Print the values of a and b.
std::cout << a << " " << b << std::endl;

Output:

12 11

Compound assignment operators in C++

Compound assignment operators combine arithmetic operations with assignment operations. This makes it possible to modify the value of a variable in a single statement.

The following table shows some of the most common compound assignment operators in C++:

Operator Description Example
+= Adds the operand to the left operand x += 5; is equivalent to x = x + 5;
-= Subtracts the operand from the left operand y -= 3; is equivalent to y = y - 3;
*= Multiplies the operand with the left operand z *= 2; is equivalent to z = z * 2;
/= Divides the left operand by the operand a /= 4; is equivalent to a = a / 4;
%= Computes the modulo of the left operand and the operand b %= 7; is equivalent to b = b % 7;
&= Performs a bitwise AND operation on the left operand and the operand c &= 6; is equivalent to c = c & 6;
^= Performs a bitwise XOR operation on the left operand and the operand e ^= 8; is equivalent to e = e ^ 8;
<<= Shifts the left operand left by the number of bits specified by the operand f <<= 3; is equivalent to f = f << 3;
>>= Shifts the left operand right by the number of bits specified by the operand g >>= 2; is equivalent to g = g >> 2;

Example

The following code shows how to use compound assignment operators to modify the value of a variable:

int a = 10;

// Increment the value of a by 1 using the compound assignment operator.
a += 1;

// Print the value of a.
std::cout << a << std::endl;

Output:

11

Compound assignment operators can be a powerful tool for writing concise and efficient C++ code.

Variable Scope (Local vs Global)

Variable scope is a concept in programming that determines where a variable can be accessed from in a program. There are two types of variable scope in C++: local and global.

  • Local variables: Local variables are declared within a function or block of code. They can only be accessed from within the function or block of code in which they are declared.
  • Global variables: Global variables are declared outside of any function or block of code. They can be accessed from anywhere in the program.

Example of local variable scope:

int main() {
  int local_variable = 10;

  // local_variable can only be accessed from within this function.
  std::cout << local_variable << std::endl;

  // This code will cause an error because local_variable is not accessible here.
  std::cout << global_variable << std::endl;

  return 0;
}

Example of global variable scope:

int global_variable = 20;

int main() {
  // global_variable can be accessed from anywhere in the program.
  std::cout << global_variable << std::endl;

  // This code is also valid.
  int local_variable = global_variable;

  return 0;
}

It is important to be aware of variable scope when writing C++ code. Otherwise, you may accidentally access a variable that is not defined or that you are not supposed to access.

Here are some general rules for variable scope in C++:

  • Local variables are scoped to the function or block of code in which they are declared.
  • Global variables are scoped to the entire program.
  • Variables declared in a function can shadow variables declared in the global scope.
  • Variables declared in a block of code can shadow variables declared in the function scope.

By understanding variable scope, you can write more efficient and reliable C++ code.

Selection Statement - if Statement

Selection statements in C++ are used to control the flow of a program. They allow you to execute different blocks of code based on different conditions.

The two main selection statements in C++ are:

  • if statement: The if statement allows you to execute a block of code if a condition is true.
  • switch statement: The switch statement allows you to select one of multiple blocks of code based on the value of an expression.

In this section will know more about if statement.

if

The if statement is a conditional statement in C++ that allows you to execute code based on a condition. The general syntax of an if statement is as follows:

if (condition) {
  // code to execute if the condition is true
}

The condition can be any Boolean expression. If the condition evaluates to true, the code block inside the if statement is executed. If the condition evaluates to false, the code block inside the else statement is executed.

Here is an example of an if statement:

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    cin >> x;
    if (x > 0)
        cout << "This number is Positive" << endl;

    return 0;
}

Output:

  • Case 1: if you entered a positive digit like 5, your if condition will be true and the block of code that follows the condition will be executed.
    This number is Positive
  • Case 2: if you entered zero or a negative digit like -5, your if condition will be false and the block of code that follows the condition will not be executed which means that nothing will appear on your result screen.

else

The else statement in C++ is used to provide an alternate block of code to be executed if the condition of an if statement is false.

The general syntax of an else statement is as follows:

if (condition) {
  // code to execute if the condition is true
} else {
  // code to execute if the condition is false
}

For example, the following code uses an else statement to print a different message depending on whether the number variable is positive or negative:

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    cin >> x;
    if (x > 0)
        cout << "This number is positive" << endl;
    else
        cout << "This number is negative" << endl;


    return 0;
}

Output should be one of the previous statements depending on the entered number. if the number is positive like 5, the output will be “This number is positive” and vice versa.

The else statement is a powerful tool for controlling the flow of your program. By using else statements, you can write more complex and efficient code.

Here are some general rules for using the if else statement:

  • The else statement must be used in conjunction with an if statement.
  • The else statement can be used to provide an alternate block of code to be executed if the condition of the if statement is false.
  • You can use nested if else statements to create more complex conditional statements:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int x = 0;
        cin >> x;
        if (x % 2 == 0)
            if (x > 50)
                cout << "it's Ok" << endl;
            else
                cout << "it's not Ok" << endl;
        else
            cout << "Odd" << endl;
    
    
        return 0;
    }
    

By understanding how to use the if else statement, you can write more efficient and reliable C++ code.

else if

Logical Operators

Logical operators in C++ are used to combine or modify Boolean expressions. They allow you to create more complex conditional statements.

The three logical operators in C++ are:

  • And (&&): Returns true if both of its operands are true. Otherwise, it returns false.
  • Or (||): Returns true if either of its operands is true. Otherwise, it returns false.
  • Not (!): Negates the value of its operand. If the operand is true, it returns false. Otherwise, it returns true.

Logical operators can be used to create more complex conditional statements. For example, the following code uses the && operator to check if a digit is in a specific range of numbers or not:

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    cout << "Enter a number";
    cin >> x;
    if (x >= 1 && x <= 100)
        cout << "Ok" << endl;
    else
        cout << "Out of range" << endl;

    return 0;
}

Another Example:

#include <iostream>

using namespace std;

int main()
{
    int a = 0;
    cout << "Enter your age";
    cin >> a;
    char g = '\0';
    cout << "Enter your gender";
    cin >> g;
    
    if (a < 18 && g == 'm')
        cout << "male, " << "young boy" << endl;
    else if (a >= 18 && g == 'm')
        cout << "male," << "grown up man" << endl;
    else if (a < 18 && g == 'f')
        cout << "female," << "young girl" << endl;
    else
        cout << "female," << "grown up girl" << endl;
    
    return 0;
}

Note : \0 in C++ is a null character. It is a character with all bits set to zero. It is used to mark the end of a string in C++.

The following code uses the || operator to check if a number is greater than 10 or less than 5:

#include <iostream>

using namespace std;

int main()
{
    int number = 3;

    if (number > 10 || number < 5) 
        cout << "The number is greater than 10 or less than 5." << endl;
    
    return 0;
}

The following code uses the ! operator to negate the value of the Boolean expression number > 10:

#include <iostream>

using namespace std;

int main()
{
    int number = 3;

    if (! (number > 10)) 
        cout << "The number is not greater than 10." << endl;
    
    return 0;
}

Logical operators can be used to create very complex conditional statements. However, it is important to use them carefully to avoid making your code difficult to read and maintain.

Here are some general rules for using logical operators:

  • Logical operators can be used to combine Boolean expressions to create more complex conditional statements.
  • The && operator returns true if both of its operands are true. Otherwise, it returns false.
  • The || operator returns true if either of its operands is true. Otherwise, it returns false.
  • The ! operator negates the value of its operand. If the operand is true, it returns false. Otherwise, it returns true.
  • Logical operators can be used in nested expressions.

By understanding how to use logical operators, you can write more efficient and reliable C++ code.

Selection Statement – Switch Statement

Selection statements in C++ are used to control the flow of a program. They allow you to execute different blocks of code based on different conditions.

The two main selection statements in C++ are:

  • if statement: The if statement allows you to execute a block of code if a condition is true.
  • switch statement: The switch statement allows you to select one of multiple blocks of code based on the value of an expression.

We explained “if statement” in “Selection Statement – if Statement” section, and now we are going to explain more about “switch statement”.

The switch statement in C++ is a control statement that allows you to execute different blocks of code based on the value of an expression. The general syntax of a switch statement is as follows:

switch (expression) {
  case value1:
    // code to execute if expression equals value1
  case value2:
    // code to execute if expression equals value2
  ...
  default:
    // code to execute if expression does not equal any of the values in the case statements
}

The expression can be any integer expression. The switch statement evaluates the expression and compares it to the values of the case statements. If the expression equals one of the values in the case statements, the code block inside that case statement is executed. If the expression does not equal any of the values in the case statements, the code block inside the default statement is executed.

Here is an example of a switch statement:

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    cin >> x;
    
    switch (x)
    {
        case 1: cout << "case #1" << endl;
            break;
        case 2: cout << "case #2" << endl;
            break;
        case 3: cout << "case #3" << endl;
            break;
        default:
            cout << "Out of range" << endl;
            break;
    }
    
    return 0;
}

You can also use characters instead of numbers in switch statement. For Example:

#include <iostream>

using namespace std;

int main()
{
    char c = 'a';
    
    switch (c)
    {
        case 'a': cout << "case #a" << endl;
            break;
        case 'b': cout << "case #b" << endl;
            break;
        default:
            cout << "Out of range" << endl;
            break;
    }
    
    return 0;
}

Output will be:

case #a

Remember!
Using a capital letter like ‘A’ in the previous example is not like using a small letter like ‘a’. They are not the same!

Benefits of using switch statements

Switch statements can be more efficient than using a series of if statements, especially when there are many different cases. Switch statements can also make your code more readable and maintainable.

Conclusion

Switch statements are a powerful tool for controlling the flow of your C++ program. By understanding how to use them, you can write more efficient and reliable code.

Repetition Statement

A repetition statement in C++ is a control statement that allows you to execute a block of code repeatedly until a certain condition is met. There are three types of repetition statements in C++:

  • while loop: The while loop executes a block of code repeatedly while a condition is true.
  • do-while loop: The do-while loop executes a block of code at least once, and then it evaluates a condition. If the condition is true, the code block is executed again.
  • for loop: The for loop executes a block of code a fixed number of times.

Repetition statements are a powerful tool for controlling the flow of your C++ program. They can be used to solve a variety of problems, such as:

  • Iterating over a collection of data
  • Performing a task a certain number of times
  • Waiting for a certain event to occur

While Loop

The while loop in C++ is a control statement that allows you to execute a block of code repeatedly while a condition is true. The general syntax of a while loop is as follows:

while (condition) {
  // code to execute while the condition is true
}

The condition can be any Boolean expression. The while loop evaluates the condition and if it is true, the code block inside the while loop is executed. The code block inside the while loop is executed repeatedly until the condition evaluates to false.

Here is an example of a while loop:

#include <iostream>

using namespace std;

int main()
{
    while (true)
    {
        cout << " a word" <<endl;
    }
    
    return 0;
}

The previous code is a simple infinite loop in C++. It will print the phrase “a word” to the console forever, or until the program is terminated.

The while (true) statement creates an infinite loop. This means that the code block inside the loop will be executed forever, or until the program is terminated.

The cout << " a word" << endl; statement prints the phrase “a word” to the console. The endl; object at the end of the line inserts a newline character, which causes the next line of output to be printed on a new line.

Here is a step-by-step explanation of what happens when you run this code:

  1. The compiler evaluates the condition of the while statement. Since the condition is always true, the code block inside the loop is executed.
  2. The compiler prints the phrase “a word” to the console.
  3. The compiler goes back to step 1 and repeats the process.

This process continues forever, or until the program is terminated.

To terminate the program, you can press Ctrl+C on your keyboard.

Here are some things to keep in mind about infinite loops:

  • Infinite loops can be useful for certain tasks, such as polling for input or waiting for a certain event to occur.
  • However, it is important to use infinite loops carefully, as they can also cause your program to crash if you are not careful.
  • For example, if you accidentally create an infinite loop that prints output to the console, your console window will quickly fill up with output and your program will become unresponsive.

To overcome these problems we should make 3 steps:

  1. declare a variable and initializes it to any value we want.
  2. add a condition to while statement.
  3. set a counter for our variable.

These steps are shown in the following example:

#include <iostream>

using namespace std;

int main()
{
    int c = 0;
    while (c < 5)
    {
        cout << " a word" <<endl;
        c++;
    }
    
    return 0;
}

int c = 0;, declares an integer variable named c and initializes it to the value 0.

The while (c < 5) statement creates a loop that will iterate as long as the value of the c variable is less than 5.

The cout << " a word" << endl; statement prints the phrase “a word” to the console. The endl; object at the end of the line inserts a newline character, which causes the next line of output to be printed on a new line.

The c++; statement increments the value of the c variable by 1.

Here is a step-by-step explanation of what happens when you run this code:

  1. The compiler declares the c variable and initializes it to the value 0.
  2. The compiler evaluates the condition of the while statement. Since the condition is true, the code block inside the loop is executed.
  3. The compiler prints the phrase “a word” to the console.
  4. The compiler increments the value of the c variable by 1.
  5. The compiler goes back to step 2 and repeats the process.

This process continues until the value of the c variable is equal to 5. At that point, the condition of the while statement will evaluate to false and the loop will terminate.

Here is the output of this program:

a word
a word
a word
a word
a word

Here is another example:

#include <iostream>

using namespace std;

int main()
{
    int c = 0, num = 0, sum = 0;
    while (c < 4)
    {
        cout << "Enter a number: ";
        cin >> num;
        sum = sum + num;
        c++;
    }
    cout << " sum = " << sum << endl;
    return 0;
}

This code is a simple C++ program that prompts the user to enter four numbers and then prints the sum of those numbers to the console.

Here is a step-by-step explanation of what happens when you run this code:

  1. The compiler declares the cnum, and sum variables and initializes them to the values 0, 0, and 0, respectively.
  2. The while (c < 4) statement creates a loop that will iterate as long as the value of the c variable is less than 4.
  3. The cout << "Enter a number: "; statement prints the message “Enter a number: ” to the console.
  4. The cin >> num; statement reads a number from the user and stores it in the num variable.
  5. The sum = sum + num; statement increments the value of the sum variable by the value of the num variable.
  6. The c++; statement increments the value of the c variable by 1.
  7. The compiler goes back to step 2 and repeats the process.

This process continues until the value of the c variable is equal to 4. At that point, the condition of the while statement will evaluate to false and the loop will terminate.

After the loop has terminated, the program prints the message ” sum = ” to the console, followed by the value of the sum variable.

Here is an example of the output of this program:

Enter a number: 10
Enter a number: 20
Enter a number: 30
Enter a number: 40
 sum = 100

While loops are a powerful tool for controlling the flow of your C++ program. By understanding how to use them, you can write more efficient and reliable code.

Here are some tips for using while loops:

  • Make sure that the condition of the while loop will eventually evaluate to false. Otherwise, the while loop will run forever.
  • Use a break statement to exit the while loop early.
  • Use a continue statement to skip the rest of the current iteration of the while loop.

Do - while loop

The do-while loop in C++ is a control statement that allows you to execute a block of code at least once, and then it evaluates a condition. If the condition is true, the code block is executed again. The code block is executed repeatedly until the condition evaluates to false.

The general syntax of a do-while loop is as follows:

do {
  // code to execute
} while (condition);

The condition can be any Boolean expression. The do-while loop executes the code block at least once, and then it evaluates the condition. If the condition is true, the code block is executed again. The code block is executed repeatedly until the condition evaluates to false.

Here is an example of a do-while loop:

#include <iostream>

using namespace std;

int main()
{
    int c = 0, num = 0, sum = 0;
    do
    {
        cout << "Enter a number: ";
        cin >> num;
        sum += num;
        c++;
    }
    while (c <= 4);
    cout << "sum = " << sum << endl;
    return 0;
}

This code prompts the user to enter four numbers and then prints the sum of those numbers to the console. The program uses a do-while loop to ensure that the user enters at least one number, even if they enter an invalid number the first time.

Here is a step-by-step explanation of what happens when you run this code:

  1. The compiler declares the cnum, and sum variables and initializes them to the values 0, 0, and 0, respectively.
  2. The do statement begins the do-while loop.
  3. The cout << "Enter a number: "; statement prints the message “Enter a number: ” to the console.
  4. The cin >> num; statement reads a number from the user and stores it in the num variable.
  5. The sum += num; statement increments the value of the sum variable by the value of the num variable.
  6. The c++; statement increments the value of the c variable by 1.
  7. The while (c <= 4); statement evaluates the condition of the do-while loop. If the c variable is less than or equal to 4, the loop will continue to iterate. Otherwise, the loop will terminate.
  8. If the condition of the loop is true, the code block inside the loop is executed.
  9. Steps 3-7 are repeated until the condition of the loop is false.
  10. After the loop has terminated, the program prints the message “sum = ” to the console, followed by the value of the sum variable.

Here is an example of the output of this program:

Enter a number: 10
Enter a number: 20
Enter a number: 30
Enter a number: 40
sum = 100

Do-while loops can be used to solve a variety of problems, such as:

  • Validating user input
  • Checking for a certain condition to be met
  • Performing a task a certain number of times

The differences between while loop and do – while loop:

Feature While loop Do-while loop
Condition is checked Before the code block is executed. After the code block is executed.
Guarantee of execution The code block is not guaranteed to be executed at least once. The code block is guaranteed to be executed at least once.

Table explanation

  • While loop: The while loop checks the condition before the code block is executed. If the condition is true, the code block is executed. The code block is executed repeatedly until the condition evaluates to false.
  • Do-while loop: The do-while loop checks the condition after the code block is executed. The code block is executed at least once, regardless of the value of the condition. The code block is executed repeatedly until the condition evaluates to false.

For loop

The for loop in C++ is a control statement that allows you to execute a block of code repeatedly a certain number of times. The general syntax of a for loop is as follows:

for (initialization; condition; increment) {
  // code to execute
}

The initialization statement is executed once, before the for loop starts. The condition statement is evaluated before each iteration of the loop. If the condition is true, the code block inside the loop is executed. The increment statement is executed after each iteration of the loop.

Here is an example of a for loop:

#include <iostream>

using namespace std;

int main()
{
    
    for (int c = 0; c < 10; c++)
    {
        cout << c << endl;
    }
    
    return 0;
}

The for loop works as follows:

  1. The initialization statement initializes the c variable to 0.
  2. The condition statement checks if the c variable is less than 10. If it is, the code block inside the loop is executed.
  3. The code block inside the loop prints the value of the c variable to the console.
  4. The increment statement increments the c variable by 1.
  5. Steps 2-4 are repeated until the condition statement evaluates to false.

When the condition statement evaluates to false, the for loop terminates.

Here is the output of this program:

0
1
2
3
4
5
6
7
8
9

Here is another example that prompts the user to enter 10 marks and then prints the average of those marks to the console:

#include <iostream>

using namespace std;

int main()
{
    int m = 0, sum = 0;
    for (int i = 1; i <= 10; i++)
    {
        cout << "Enter your marks:";
        cin >> m;
        sum = sum + m;
    }
    cout << "the avg = " << ((double)sum / 10) << endl;
    
    return 0;
}

The for loop works as follows:

  1. The initialization statement initializes the i variable to 1.
  2. The condition statement checks if the i variable is less than or equal to 10. If it is, the code block inside the loop is executed.
  3. The code block inside the loop prompts the user to enter their marks and stores the value in the m variable. The code block also adds the value of the m variable to the sum variable.
  4. The increment statement increments the i variable by 1.
  5. Steps 2-4 are repeated until the condition statement evaluates to false.

When the condition statement evaluates to false, the for loop terminates.

After the for loop has terminated, the program prints the average of the marks to the console. The average is calculated by dividing the sum of the marks by the number of marks.

You used the (double) cast in the expression ((double)sum / 10) to ensure that the result of the division operation is a floating-point number. This is important because the sum variable is an integer variable, and the division of two integers results in an integer. If you did not use the (double) cast, the program would print the integer result of the division operation to the console, which may not be accurate.

Here is an example of the output of this program:

Enter your marks: 10
Enter your marks: 20
Enter your marks: 30
Enter your marks: 40
Enter your marks: 50
Enter your marks: 60
Enter your marks: 70
Enter your marks: 80
Enter your marks: 90
Enter your marks: 100
the avg = 55.000000

This code prints the numbers from 10 to 50 to the console, separated by spaces:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 10; i <= 50; i++)
    {
        cout << i << " ";
    }

    return 0;
}

The for loop works as follows:

  1. The initialization statement initializes the i variable to 10.
  2. The condition statement checks if the i variable is less than or equal to 50. If it is, the code block inside the loop is executed.
  3. The code block inside the loop prints the value of the i variable to the console, followed by a space.
  4. The increment statement increments the i variable by 1.
  5. Steps 2-4 are repeated until the condition statement evaluates to false.

When the condition statement evaluates to false, the for loop terminates.

Here is the output of this program:

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

Why is size_t used as the loop counter?

The size_t type is used as the loop counter because it is the type that is returned by the sizeof operator. This ensures that the loop counter can be used to iterate over any type of data, including arrays and objects.

This code prints the numbers from 10 to 1 to the console, in reverse order, separated by spaces:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 10; i >= 1; i--)
    {
        cout << i << " ";
    }

    return 0;
}

The for loop works as follows:

  1. The initialization statement initializes the i variable to 10.
  2. The condition statement checks if the i variable is greater than or equal to 1. If it is, the code block inside the loop is executed.
  3. The code block inside the loop prints the value of the i variable to the console, followed by a space.
  4. The decrement statement decrements the i variable by 1.
  5. Steps 2-4 are repeated until the condition statement evaluates to false.

When the condition statement evaluates to false, the for loop terminates.

Here is the output of this program:

10 9 8 7 6 5 4 3 2 1

Examples of loop break vs continue

break and continue are two flow control statements in C++ that can be used to alter the normal flow of a loop.

break terminates the loop immediately and unconditionally.

continue skips the rest of the current iteration of the loop and causes the loop to continue with the next iteration.

Here is an example of how to use continue in C++:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 0; i < 10; i++)
    {
        if (i == 5)
            continue;
        cout << "i = " << i << endl;
    }
    
    return 0;
}

This code is a for loop that prints the values of the variable i to the console, from 0 to 9, inclusive, except for the number 5. The if statement inside the loop checks if i is equal to 5. If it is, the continue statement skips the rest of the current iteration of the loop and causes the loop to continue with the next iteration.

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares a variable i and initializes it to 0.
  2. The program starts a for loop that iterates 10 times.
  3. Inside the for loop, the program checks if i is equal to 5.
  4. If i is equal to 5, the program skips the rest of the current iteration of the loop using the continue statement.
  5. Otherwise, the program prints the value of i to the console.
  6. The program then increments i by 1.
  7. The for loop repeats steps 3-6 until it has iterated 10 times.

Here is the output of this code:

i = 0
i = 1
i = 2
i = 3
i = 4
i = 6
i = 7
i = 8
i = 9

Here is an example of how to use break in C++:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 0; i < 10; i++)
    {
        if (i == 4)
            break;
        cout << "i = " << i << endl;
    }
    
    return 0;
}

This code is a for loop that prints the values of the variable i to the console, from 0 to 3, inclusive. The if statement inside the loop checks if i is equal to 4. If it is, the break statement terminates the loop immediately and unconditionally.

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares a variable i and initializes it to 0.
  2. The program starts a for loop that iterates 10 times.
  3. Inside the for loop, the program checks if i is equal to 4.
  4. If i is equal to 4, the break statement terminates the loop immediately and unconditionally.
  5. Otherwise, the program prints the value of i to the console.
  6. The program then increments i by 1.
  7. The for loop repeats steps 3-6 until it has iterated 10 times or until the loop is terminated by the break statement.

In this case, the loop will be terminated by the break statement when i is equal to 4. Therefore, the output of the code will be:

i = 0
i = 1
i = 2
i = 3

Which one to use?

Which one to use depends on what you want to achieve. If you want to terminate the loop immediately, use break. If you want to skip the rest of the current iteration of the loop and continue with the next iteration, use continue.

Here are some general tips for using break and continue:

  • Use break sparingly. Terminating a loop early can make your code more difficult to read and understand.
  • Use continue to avoid writing duplicate code. If you find yourself writing the same code inside a loop multiple times, consider using continue.
  • Use break and continue to make your code more efficient. For example, you can use break to terminate a loop early if you have already found what you are looking for.

Nested Loop

A nested loop is a loop that is contained within another loop. This means that the inner loop will iterate for each iteration of the outer loop.

Here is an example of a nested loop in C++:

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 1; i <= 5; i++)
    {
        for ( size_t j = 1; j <= 6; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

This code is a nested for loop that prints a rectangle of asterisks to the console. The outer loop iterates 5 times, and the inner loop iterates 6 times. This means that the code inside the inner loop will be executed 30 times.

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares two variables i and j, and initializes them to 1.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is less than or equal to 5. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is less than or equal to 6. If it is, the program prints an asterisk to the console.
  5. The inner for loop then increments j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is greater than 6.
  7. After the inner for loop has terminated, the program prints a newline character to the console.
  8. The outer for loop then increments i by 1.
  9. The outer for loop repeats steps 3-8 until i is greater than 5.

Here is the output of the code:

******
******
******
******
******

Nested loops can be used to solve a variety of problems. For example, you could use nested loops to iterate over all the elements of a two-dimensional array, or to generate all the possible combinations of two sets of values.

Here are some tips for using nested loops:

  • Use nested loops sparingly. Nested loops can make your code more difficult to read and understand.
  • Use nested loops to avoid writing duplicate code. If you find yourself writing the same code inside a loop multiple times, consider using nested loops.
  • Use nested loops to make your code more efficient. For example, you can use nested loops to avoid searching for an element in an array multiple times.

Draw shapes (Triangle)

You can use the logic of nested loops to create different shapes, for example a triangle.

This code is a nested for loop that prints a triangle of asterisks to the console. The outer loop iterates 5 times, and the inner loop iterates for each iteration of the outer loop.

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 1; i <= 5; i++)
    {
        for ( size_t j = 1; j <= i; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares two variables i and j, and initializes them to 1.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is less than or equal to 5. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is less than or equal to i. If it is, the program prints an asterisk to the console.
  5. The inner for loop then increments j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is greater than i.
  7. After the inner for loop has terminated, the program prints a newline character to the console.
  8. The outer for loop then increments i by 1.
  9. The outer for loop repeats steps 3-8 until i is greater than 5.

Here is the output of the code:

*
**
***
****
*****

What if we want to draw this triangle upside down?

We change the condition in our outer for loop.

This code is a nested for loop that prints an inverted triangle of asterisks to the console. The outer loop iterates from 5 to 1, inclusive, and the inner loop iterates for each iteration of the outer loop.

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 5; i >= 1; i--)
    {
        for ( size_t j = 1; j <= i; j++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares two variables i and j, and initializes them to 5 and 1, respectively.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is greater than or equal to 1. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is less than or equal to i. If it is, the program prints an asterisk to the console.
  5. The inner for loop then increments j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is greater than i.
  7. After the inner for loop has terminated, the program prints a newline character to the console.
  8. The outer for loop then decrements i by 1.
  9. The outer for loop repeats steps 3-8 until i is less than 1.

Here is the output of the code:

*****
****
***
**
*

Can we make it harder?

This code prints a right triangle of asterisks to the console. The outer loop iterates from 1 to 5, inclusive, and the inner loop iterates from 4 to i, inclusive, where i is the current iteration of the outer loop.

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 1; i <= 5; i++)
    {
        for ( size_t j = 4; j >= i; j--)
        {
            cout << " ";
        }
        for (size_t k = 1; k <= i; k++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares three variables ij, and k, and initializes them to 1, 4, and 1, respectively.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is less than or equal to 5. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is greater than or equal to i. If it is, the program prints a space to the console.
  5. The inner for loop then decrements j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is less than i.
  7. After the inner for loop has terminated, the program prints an asterisk to the console for each iteration of the inner for loop.
  8. The program then prints a newline character to the console.
  9. The outer for loop then increments i by 1.
  10. The outer for loop repeats steps 3-9 until i is greater than 5.

Here is the output of the code:

    *
   **
  ***
 ****
*****

Let’s print it upside down!

#include <iostream>

using namespace std;

int main()
{
    for ( size_t i = 5; i >= 1; i--)
    {
        for ( size_t j = 4; j >= i; j--)
        {
            cout << " ";
        }
        for (size_t k = 1; k <= i; k++)
        {
            cout << "*";
        }
        cout << endl;
    }

    return 0;
}

Look what we have here as an output!

*****
 ****
  ***
   **
    *

Let’s draw a different triangle

#include <iostream>

using namespace std;

int main()
{
    int e = 1;
    for (int a = 1; a <= 5; a++)
    {
        for (int b = 4; b >= a; b--)
        {
            cout << " ";
        }
        for (int c = 0; c < e; c++)
        {
            cout << "*";
        }
        cout << endl;
        e = e + 2;
    }

    return 0;
}

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares four variables ea, c, and b, and initializes them to 1, 1, 0 and 4, respectively.
  2. The program starts the outer for loop.
  3. The outer for loop checks if a is less than or equal to 5. If it is, the inner for loop is executed.
  4. The inner for loop checks if b is greater than or equal to a. If it is, the program prints a space to the console.
  5. The inner for loop then decrements b by 1.
  6. The inner for loop repeats steps 4 and 5 until b is less than a.
  7. After the inner for loop has terminated, the program prints an asterisk to the console for each iteration of the inner for loop.
  8. The program then prints a newline character to the console.
  9. The outer for loop then increments a by 1.
  10. The outer for loop repeats steps 3-9 until a is greater than 5.

Here is the output of the code:

    *
   ***
  *****
 *******
*********

Let’s make it upside down:

#include <iostream>

using namespace std;

int main()
{
    int e = 9;
    for (int r = 1; r <= 5; r++)
    {
        for (int c = 0; c < e; c++)
        {
            cout << "*";
        }
        cout << endl;
        e = e - 2;
        for (int s = 0; s < r; s++)
        {
            cout << " ";
        }
    }

    return 0;
}

Output:

*********
 *******
  *****
   ***
    *

You can also use nested loops to draw other shapes, such as squares, rectangles, and diamonds.

Draw shapes (square), Draw any Letter Ex:( X,Z,N,E,F)

Nested loops in C++ are a powerful tool for drawing different shapes to the console. By using nested loops, we can iterate over multiple dimensions and print different characters to create different patterns.

Example 1:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 1; i <= 10; i++)
    {
        for (size_t j = 1; j <= 10; j++)
        {
            if (i == 1 || i == 10)
                cout << "*";
            else if (j == 1 || j == 10)
                cout << "*";
            else
                cout << " ";
        }
        cout << endl;
    }

    return 0;
}

This code prints a hollow square of asterisks to the console. The outer for loop iterates from 1 to 10, inclusive, and the inner for loop iterates from 1 to 10, inclusive.

The if statement inside the inner for loop checks if i is equal to 1 or 10, or if j is equal to 1 or 10. If any of these conditions are met, the program prints an asterisk to the console. Otherwise, the program prints a space to the console.

Here is a step-by-step explanation of what happens when you run this code:

  1. The program declares two variables i and j, and initializes them to 1.
  2. The program starts the outer for loop.
  3. The outer for loop checks if i is less than or equal to 10. If it is, the inner for loop is executed.
  4. The inner for loop checks if j is less than or equal to 10. If it is, the program prints an asterisk to the console if i is equal to 1 or 10, or if j is equal to 1 or 10. Otherwise, the program prints a space to the console.
  5. The inner for loop then increments j by 1.
  6. The inner for loop repeats steps 4 and 5 until j is greater than 10.
  7. After the inner for loop has terminated, the program prints a newline character to the console.
  8. The outer for loop then increments i by 1.
  9. The outer for loop repeats steps 3-8 until i is greater than 10.

Here is the output of the code:

**********
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
**********

Example 2:

If we want to print a letter like X to the console, expecting an output like this:

*   *
 * * 
  *  
 * * 
*   *

We need to set our logic.
To understand how we can put the asterisks in the previous shape, let’s present them this way:

/*
 1 2 3 4 5
1* * * * *
2* * * * *
3* * * * *
4* * * * *
5* * * * *
*/

Now let’s think about it looking at this shape, when the column meets the row we get a star, so we need a loop that goes through all the meeting points between every row and column and we need an if condition to specify our exact locations to make two diagonal lines cross forming our X letter shape.

all of this is represented in the following code:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 1; i <= 5; i++)
    {
        for (size_t j = 1; j <= 5; j++)
        {
            if (i == j || j == 6-i)
                cout << "*";
            else
                cout << " ";
        }
        cout << endl;
    }

    return 0;
}

Example 3:

By understanding how we asterisks are lined here:

/*
 1 2 3 4 5 
1* * * * * 
2* * * * * 
3* * * * * 
4* * * * * 
5* * * * * 
*/

We can think of multiple ways to manipulate our code producing different letters and shapes..

Look at this code:

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 1; i <= 5; i++)
    {
        for (size_t j = 1; j <= 5; j++)
        {
            if (j == (6) - i || i == 1 || i == 5)
                cout << "*";
            else
                cout << " ";
        }
        cout << endl;
    }

    return 0;
}

Guess what this shape is?!

Output:

*****
   *
  *  
 *   
*****

Example 4:

Now let’s make our shape more complicated

**********
**      **
* *    * *
*  *  *  *
*   **   *
*   **   *
*  *  *  *
* *    * *
**      **
**********

Applying this code which is no different than previous examples

#include <iostream>

using namespace std;

int main()
{
    for (size_t i = 1; i <= 10; i++)
    {
        for (size_t j = 1; j <= 10; j++)
        {
            if (i == j || j == 11 - i || i == 1 || i == 10 || j == 1 || j == 10)
                cout << "*";
            else
                cout << " ";
        }
        cout << endl;
    }

    return 0;
}

 

Function Part 1

A function in C++ is a block of code that performs a specific task. Functions can be used to encapsulate common operations, making your code more reusable and easier to understand. Functions can also be used to improve the performance of your code by avoiding duplicate code.

To create a function in C++, you use the following syntax:

return_type function_name(parameter_list) {
  // Function body
}

The return_type specifies the type of data that the function will return. The function_name is the name of the function. The parameter_list is a list of parameters that the function will accept. The function_body is the code that the function will execute.

Here is an example of a simple function in C++:

int sum(int x, int y)
{
    int s = 0;
    s = x + y;
    return s;
}

This function takes two integer parameters, x and y, and returns the sum of those two parameters.

To call a function, you simply use its name followed by a pair of parentheses. For example, to call the sum() function, you would write:

int s = sum(10, 20);

This would assign the value 30 to the variable s.

The code could be written this way:

#include <iostream>

using namespace std;

int sum(int x, int y)
{
    int s = 0;
    s = x + y;
    return s;
}
int main()
{
    int s = 0;
    s = sum(10, 20);
    cout << "sum = " << s << endl;
    
    return 0;
}

The following example takes two float parameters and return the sum of them:

#include <iostream>

using namespace std;

float sum(float x, float y)
{
    float s = 0;
    s = x + y;
    return s;
}
int main()
{
    float s = 0;
    s = sum(20.5, 30.6);
    cout << "sum = " << s << endl;
    
    return 0;
}

Output:

sum = 51.1

The importance of using return:

We need to write a return in a function in C++ to specify the value that the function will return to the calling function. This is important because it allows us to use the function to perform calculations and then use the result of those calculations in our code.

Without the return statement, the function would not be able to return any value to the calling function. This would mean that we would not be able to use the function to perform calculations and then use the result of those calculations in our code.

By using the return statement, we can terminate the execution of the function early and avoid the error. This makes our code more robust and reliable.

Overall, the return statement is an important part of C++ programming. It allows us to return values from functions and to terminate the execution of functions early. This makes our code more reusable, efficient, and reliable.

But can we write a function without using return?

See this example:

#include <iostream>

using namespace std;

void print()
{
    cout << "myName" << endl;
}

int main()
{
    print();
    
    return 0;
}

This code defines a function called print() and a main function. The print() function simply prints the string “myName” to the console. The main function calls the print() function and then returns 0.

The print() function is declared with the void return type. This means that the function does not return any value. We use the void return type when we want a function to perform an action but not return any value.

When you run this code, the following output will be printed to the console:

myName

We use the void return type for the print() function because we only want it to print the string “myName” to the console. We do not need the function to return any value.

 

Functions can also be nested, meaning that one function can call another function. This can be useful for breaking down complex tasks into smaller, more manageable functions.

Functions are a powerful tool in C++ and can be used to improve the quality and performance of your code.

Here are some tips for using functions in C++:

  • Give your functions meaningful names. This will make your code more readable and easier to maintain.
  • Use functions to encapsulate common operations. This will make your code more reusable and easier to understand.
  • Use functions to improve the performance of your code by avoiding duplicate code.
  • Use functions to break down complex tasks into smaller, more manageable functions.

Function Part 2

Example 1:

#include <iostream>

using namespace std;

double avg(int m1, int m2, int m3) 
{
    return double(m1 + m2 + m3) / 3;
}

int main()
{
    int mm1, mm2, mm3;
    cout << "Enter your marks" << endl;
    cin >> mm1 >> mm2 >> mm3;
    cout << "avg = " << avg(mm1, mm2, mm3) << endl;
    
    return 0;
}

This code defines a function called avg(), which takes three integer parameters (m1, m2, and m3) and returns the average of those three parameters as a double value.

The function works by first converting the integer parameters to double values using the double() function. This is necessary because the average of three integers is a fractional number, and we want the function to return a double value.

Next, the function calculates the sum of the three parameters and divides that sum by 3. This gives us the average of the three parameters.

Finally, the function returns the average value.

The program works as follows:

  1. The program declares three integer variables mm1mm2, and mm3 to store the marks entered by the user.
  2. The program prompts the user to enter their marks and reads the marks into the three variables.
  3. The program calls the avg() function to calculate the average of the three marks.
  4. The program prints the average to the console.

Example 2:

#include <iostream>

using namespace std;

int max(int n1, int n2, int n3) 
{
    int mx = n1;
    if (mx < n2)
        mx = n2;
    if (mx < n3)
        mx = n3;
    return mx;
}

int min(int n1, int n2, int n3) 
{
    int mn = n1;
    if (mn > n2)
        mn = n2;
    if (mn > n3)
        mn = n3;
    return mn;
}

int main()
{
    cout << "max = " << max(100, 200, 300) << endl;
    cout << "min = " << min(100, 200, 300) << endl;
    
    return 0;
}

This code defines two functions called max() and min()which both take three integer parameters (n1, n2, and n3) and returns the largest and the smallest of those three parameters.

The first function works by first initializing a variable called mx to the value of the first parameter, n1. Then, the function checks if mx is less than the second parameter, n2. If it is, the function assigns the value of n2 to mx. Next, the function checks if mx is less than the third parameter, n3. If it is, the function assigns the value of n3 to mx. Finally, the function returns the value of mx, which is the largest of the three parameters.

The second function works by first initializing a variable called mn to the value of the first parameter, n1. Then, the function checks if mn is greater than the second parameter, n2. If it is, the function assigns the value of n2 to mn. Next, the function checks if mn is greater than the third parameter, n3. If it is, the function assigns the value of n3 to mn. Finally, the function returns the value of mn, which is the smallest of the three parameters.

Here is the output of the program:

min = 100
max = 300

There are two ways to define a function in a C++ program:

  1. Function declaration: This is a prototype of the function that tells the compiler about the function’s name, return type, and parameters. The function declaration must be placed before the first call to the function.
  2. Function definition: This is the actual code that implements the function. The function definition can be placed anywhere in the program, but it is generally placed at the end of the program.

For example, here is a function declaration and definition:

// Function declaration
int add(int a, int b);

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

The function declaration tells the compiler that there is a function called add() that takes two integer parameters and returns an integer value. The function definition provides the actual code that implements the function.

You can also arrange function declarations and definitions in different ways in your code. For example, you can:

  • Declare all of your functions at the beginning of your program and then define them at the end of your program.
  • Declare and define your functions in the order that they are called in your program.
  • Declare your functions in a header file and define them in a source file.

The best arrangement for your code will depend on the specific needs of your program.

Here is an example of how to use function declarations and definitions in a C++ program:

// Function declaration
int add(int a, int b);

int main() {
  // Function call
  int sum = add(1, 2);

  // Print the sum
  cout << "The sum is: " << sum << endl;

  return 0;
}

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

Of course you should pay a massive attention to the sequential arrangement of your program.

The sequential arrangement of functions in a C++ program is important for two main reasons:

  • Readability: A well-organized program is easier to read and understand. By arranging functions in a logical order, you can make it easier for other programmers to follow the flow of your code.
  • Maintainability: A well-maintained program is easier to update and fix bugs in. By arranging functions in a logical order, you can make it easier to find and fix problems in your code.

Note !

The main function is the entry point for all C++ programs. It is the first function that is called when the program is executed. The main function is responsible for initializing the program, calling other functions, and returning a value to the operating system.

The main function is important for several reasons:

  • It is the starting point for the program execution.
  • It is responsible for initializing the program.
  • It controls the flow of the program by calling other functions.
  • It returns a value to the operating system when the program terminates.

Without the main function, the program would not be able to start executing.

Here is an example of a simple main function in C++:

int main() {
  // Initialize the program
  // ...

  // Call other functions
  // ...

  // Return a value to the operating system
  return 0;
}

This main function initializes the program, calls other functions, and returns a value of 0 to the operating system.

You can use the main function to control the flow of your program by calling other functions. For example, you could write a function to calculate the sum of two numbers and then call that function from the main function.

You can also use the main function to return a value to the operating system. This value is used to indicate whether the program terminated successfully or not.

The main function is a very important part of any C++ program. It is the starting point for the program execution, and it controls the flow of the program.

Example 3:

#include <iostream>

using namespace std;

int avg(int x, int y, int z)
{
    return (x + y + z) / 3;
}

void print()
{
    cout << "Hello" << endl;
}

void xy()
{
    cout << 5 * 10 << endl;
}

int main()
{
    cout << "Nothing" << endl;
    return 0;
}

int f2()
{
    return 5;
}

This code defines four functions: avg(), print(), xy(), and f2(). The avg() function takes three integer parameters and returns the average of those three parameters. The print() function prints the string “Hello” to the console. The xy() function prints the product of 5 and 10 to the console. The f2() function returns the integer 5.

The main function in the code simply prints the string “Nothing” to the console and then returns 0.

When you run this code, the following output will be printed to the console:

Nothing

This is because the only function that is called from the main function is the cout << "Nothing" << endl; statement.

You can use the other functions in the code by calling them from the main function or from other functions.

Function part 3 (built in functions)

Built-in functions in C++ are functions that are provided by the compiler and are available to use in any C++ program. These functions are typically used for common tasks such as input/output, mathematical operations, and string manipulation.

ere are some of the most common built-in functions in C++:

  • Mathematical functions:
    • abs(): Returns the absolute value of a number.
    • sqrt(): Calculates the square root of a number.
    • pow(): Raises a number to a power.
    • sin(): Calculates the sine of an angle in radians.
    • cos(): Calculates the cosine of an angle in radians.
    • tan(): Calculates the tangent of an angle in radians.
    • floor(): Returns the greatest integer less than or equal to a number.
    • ceil(): Returns the smallest integer greater than or equal to a number.
  • String manipulation functions:
    • strlen(): Returns the length of a string.
    • strcpy(): Copies one string to another string.
    • strcat(): Concatenates two strings.
    • strcmp(): Compares two strings and returns an integer value indicating whether they are equal, less than, or greater than each other.
  • Input/output functions:
    • cin: Reads data from the standard input stream.
    • cout: Writes data to the standard output stream.
    • cerr: Writes data to the standard error stream.
    • fopen(): Opens a file for reading or writing.
    • fclose(): Closes a file.

Example 1:

cout << sqrt(18) << endl;

Output:

4.24264

Example 2:

cout << abs(-18) << endl;

Output:

18

Example 3:

cout << mod(10.5,2) << endl;

Output:

0.5

Example 4:

cout << floor(10.2) << endl;

Output:

10

Example 5:

cout << floor(-10.2) << endl;

Output:

-11

Example 6:

cout << ceil(10.2) << endl;

Output:

11

Example 6:

#include <iostream>

using namespace std;

int main()
{
    cout << sqrt(abs(pow(-3,2))) << endl;

    return 0;
}

To use a built-in function, you simply need to include the appropriate header file. So you might have a problem executing this program. you would need to include the <cmath> header file.

The <cmath> header file contains declarations for a number of mathematical functions, such as sqrt(), pow(), sin(), cos(), and tan(). These functions are useful for performing common mathematical operations, such as calculating the square root of a number, raising a number to a power

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    cout << sqrt(abs(pow(-3,2))) << endl;

    return 0;
}

Output:

3

Example 7:

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

int main()
{
    cout << max(10,5) << endl;

    return 0;
}

You would need to include the <algorithm> header file to use any of the algorithms provided by the C++ standard library. These algorithms include sorting, searching, merging, and many more.

Output:

10

Example 8:

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

int main()
{
    cout << max(15,max(10,5)) << endl;

    return 0;
}

Output:

15

Example 9:

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

int main()
{
    
    int x = 0, y = 10;
    swap(x,y);
    cout << "x= " << x << "y= " << y << endl;

    return 0;
}

Output:

x= 10y= 0

Built-in functions can be a very useful tool for C++ programmers. By using built-in functions, you can avoid having to write your own code for common tasks.

 

 

Function part 4 (Random functions)

Random functions in C++ are used to generate random numbers. There are two built-in random functions in C++: rand() and srand().

The rand() function generates a random integer between 0 and RAND_MAX, where RAND_MAX is a macro that is defined in the cstdlib header file. The srand() function is used to seed the random number generator. If you don’t call srand(), the random number generator will be seeded with a default value.

Example 1:

#include <iostream>
#include <cstdlib>

using namespace std;
int main()
{
    
    cout << rand() << endl;
    
    return 0;
}

This code prints a random integer to the console.

Example 2:

#include <iostream>
#include <cstdlib>

using namespace std;
int main()
{
    for (size_t i = 0; i < 10; i++)
    {
        cout << rand() << endl;
    }
    
    return 0;
}

This code is a for loop that prints 10 random integers to the console.

Example 3:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    for (size_t i = 0; i < 10; i++)
    {
        cout << rand()%10 << endl;
    }
    
    return 0;
}

This code generates a random number between 0 and 9 and prints it to the console. The modulus operator (%) returns the remainder of a division operation. So, the expression rand()%10 will return the remainder of the operation rand() / 10. This will give us a number between 0 and 9.

Example 4:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    for (size_t i = 1; i <= 10; i++)
    {
        cout << rand()%(30 - 20 + 1) + 20 << endl;
    }
    
    return 0;
}

This code generates a random number between 20 and 30 and prints it to the console.

Example 5:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(0));
    for (size_t i = 1; i <= 10; i++)
    {
        cout << rand()%(30 - 20 + 1) + 20 << endl;
    }
    
    return 0;
}

The srand(time(0)); function seeds the random number generator with the current time. This ensures that the random numbers are different each time the program is run.

The srand() function takes an integer seed as its argument and initializes the random number generator with that seed. The time(0) function returns the current time as a time_t value, which is an integer.

By seeding the random number generator with the current time, we are using a value that is constantly changing, which ensures that the random numbers are different each time the program is run.

It is important to seed the random number generator before using the rand() function. If you do not seed the random number generator, it will be seeded with a default value, which will result in the same sequence of random numbers being generated each time the program is run.

Example 6:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    int x, y;
    x = time(0);
    for (size_t i = 0; i < 10000; i++)
    {
        cout << time(NULL) << endl;
        y = time (0);
    }
    cout << "The token time:" << y - x << endl;
    return 0;
}

This code prints the current time 10000 times to the console and then prints the total time it took to do so.

The program works as follows:

  1. The int x, y; declaration creates two integer variables, x and y.
  2. The x = time(0); statement assigns the current time to the variable x.
  3. The for (size_t i = 0; i < 10000; i++) loop iterates 10000 times.
  4. On each iteration of the for loop, the following code is executed:
    • The current time is printed to the console using the cout << time(NULL) << endl; statement.
  5. The y = time(0); statement assigns the current time to the variable y.
  6. The cout << "The token time:" << y - x << endl; statement prints the total time it took to print the current time 10000 times to the console.

The time(NULL) function is a synonym for the time(0) function.

You can use this code to measure the performance of your code or to calculate the elapsed time between two events.

Function part 5 (Call By Reference vs Call By Value)

Call by value and call by reference are two different ways to pass arguments to functions in C++.

Call by value is the default passing mechanism in C++. When a function is called by value, a copy of the actual argument is passed to the function. The function then operates on this copy, and any changes made to the copy inside the function will not be reflected in the actual argument outside the function.

Call by reference allows you to pass the reference of the actual argument to the function. This means that the function operates directly on the actual argument outside the function. Any changes made to the argument inside the function will be reflected in the actual argument outside the function.

To pass an argument by reference, you need to use the & operator before the argument name

For example, the following code shows how to call a function by value:

#include <iostream>
using namespace std;

void swap(int x, int y)
{
    int z = x;
        x = y;
        y = z;
}

int main()
{
    int x = 10, y = 20;
    swap(x, y);
    cout << "x= " << x << " y= " << y << endl;
    
    return 0;
}

//x= 10 y= 20

The following code shows how to call the same function by reference:

#include <iostream>
using namespace std;

void swap(int&x, int&y)
{
    int z = x;
        x = y;
        y = z;
}

int main()
{
    int x = 10, y = 20;
    swap(x, y);
    cout << "x= " << x << " y= " << y << endl;
    
    return 0;
}

//x= 20 y= 10

As you can see, the result of calling the swap() function is different depending on whether it is called by value or by reference.

Call by reference is often used to modify the values of the arguments outside the function. For example, the swap() function could be used to swap the values of two variables.

Call by reference can also be used to pass large objects to functions without having to copy them. This can improve the performance of your program.

However, it is important to use call by reference carefully, as it can lead to unexpected results if not used correctly. For example, if you pass a reference to a local variable to a function, and the function returns, the local variable will go out of scope, but the reference to it will still be valid. This can lead to a program crash if you try to access the local variable through the reference.

In general, it is best to use call by value unless you have a specific reason to use call by reference.

For example, the following code shows how to call a function by value:

#include <iostream>
using namespace std;

void fun(int x, int y)
{
    x += 1;
    y += 2;
}
int main()
{
    int k = 50, r = 10;
    fun(k, r);
    cout << "K= " << k << " R= " << r << endl;
    
    return 0;
}

//K= 50 R= 10

The following code shows how to call the same function by reference:

#include <iostream>
using namespace std;

void fun(int&x, int&y)
{
    x += 1;
    y += 2;
}
int main()
{
    int k = 50, r = 10;
    fun(k, r);
    cout << "K= " << k << " R= " << r << endl;
    
    return 0;
}

//K= 51 R= 12

As you can see, the result of calling the fun() function is different depending on whether it is called by value or by reference.

Function part 6 (Recursion 1)

Recursion is a programming technique where a function calls itself directly or indirectly. This can be used to solve problems that can be broken down into smaller, simpler problems of the same type.

Recursion can be a bit difficult to understand at first, but it is a powerful tool that can be used to solve a wide variety of problems.

Here is a simple example of a recursive function in C++:

#include <iostream>
using namespace std;
void f(int n)
{
    if (n < 1)
        return;
    else
        cout << "round:" << n << endl;
    f(n - 1);
}

int main()
{
    f(5);
    return 0;
}

The function f(int n) is a recursive function that prints the string “round:” followed by the integer n to the console n times.

The function works by recursively calling itself to print the string “round:” followed by the integer n - 1 to the console. This process continues until n is equal to 1, at which point the function returns.

Output:

round: 5
round: 4
round: 3
round: 2
round: 1

Recursive functions can be a bit difficult to understand at first, but they are a powerful tool that can be used to solve a wide variety of problems.

You should pay attention to these 3 contents of a recursive function (base case, logic and subproblem), which are marked in the following function:

void f(int n)
{
    if (n < 1)
        return; //base case
    else
        cout << "round:" << n << endl; //logic
    f(n - 1); //subproblem
}

The three contents of a recursive function are:

  • Base case: The base case is a special case that is handled directly in the function without making any recursive calls. The base case is usually a simple case that can be solved directly.
  • Logic: The logic of a recursive function is the code that is executed to break down the problem into smaller, simpler problems of the same type. The logic usually involves making recursive calls to the function with smaller input values.
  • Subproblem: A subproblem is a smaller, simpler problem of the same type as the original problem. Recursive functions work by breaking down the original problem into subproblems and then solving the subproblems using the same recursive function.

Here is an example of a recursive function in C++ that calculates the factorial of a number:

#include <iostream>
using namespace std;
int fact(int n)
{
    if (n == 0 || n == 1)
        return 1;
    else
        return n*fact(n - 1);
}

int main()
{
    cout << fact(5) << endl;
    return 0;
}

The function fact(int n) is a recursive function that calculates the factorial of a number. The factorial of a number is the product of all the positive integers less than or equal to that number. For example, the factorial of 5 is 120, because 120 is the product of 1, 2, 3, 4, and 5. So, the  output of our program will be 120.

The function fact(int n) works by recursively calling itself to calculate the factorial of the number one less than the input number. For example, to calculate the factorial of 5, the function would first call itself to calculate the factorial of 4. This would then call itself to calculate the factorial of 3, and so on. Eventually, the function would reach the base case, where the input number is 0 or 1. The base case is a special case that is handled directly in the function without making any recursive calls. The factorial of 0 is 1 and the factorial of 1 is also 1, so the function simply returns 1 in these cases.

Fibonacci Series

The Fibonacci sequence is a series of numbers where each number is the sum of the two previous numbers. The first two numbers in the sequence are 0 and 1, and each subsequent number is the sum of the previous two numbers.

Here is the Fibonacci sequence up to the first 10 numbers:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The Fibonacci sequence can be generated using the following recurrence relation:

F(n) = F(n - 1) + F(n - 2)

where F(n) is the nth number in the Fibonacci sequence.

The Fibonacci sequence has a number of interesting properties. For example, the ratio of successive Fibonacci numbers approaches the golden ratio as the numbers get larger. The golden ratio is an irrational number that is approximately equal to 1.618.

The Fibonacci sequence appears in many different areas of mathematics and nature. For example, it can be used to model the growth of a population of rabbits, the spiral pattern of a seashell, and the branching pattern of a tree.

Here are some examples of how the Fibonacci sequence is used in the real world:

  • Finance: The Fibonacci sequence can be used to identify potential support and resistance levels for stock prices.
  • Music: The Fibonacci sequence can be used to create musical compositions with a pleasing rhythm and structure.
  • Art: The Fibonacci sequence can be used to create works of art with a balanced and harmonious composition.
  • Architecture: The Fibonacci sequence can be used to design buildings and other structures that are aesthetically pleasing and structurally sound.

The Fibonacci sequence is a fascinating and versatile mathematical sequence that has many applications in the real world.

Example:

#include <iostream>
using namespace std;
int fib(int n)
{
    if (n == 0 || n == 1)
        return n;
    else
        return fib(n - 1) + fib(n - 2);
}

int main()
{
    cout << fib(3) << endl;
    return 0;
}

The function fib(int n) works by recursively calling itself to calculate the Fibonacci numbers of the previous two numbers. If the input number n is 0 or 1, the function simply returns the number, because the first two Fibonacci numbers are 0 and 1. Otherwise, the function returns the sum of the Fibonacci numbers of the previous two numbers.

Output:

2

 

Function part 7 (Recursion 2)

Example 1:

#include <iostream>
using namespace std;
int sum(int n)
{
    if (n == 1)
        return 1;
    else
        return n + sum(n - 1);
}

int main()
{
    cout << sum(5) << endl;
    return 0;
}

This function calculates the sum of the first n natural numbers. The first n natural numbers are the numbers from 1 to n.

The function works by recursively calling itself to calculate the sum of the first n - 1 natural numbers. If the input number n is 1, the function simply returns the number 1, because the sum of the first natural number is 1. Otherwise, the function returns the sum of the input number n and the sum of the first n - 1 natural numbers.

Output:

15

Example 2:

#include <iostream>
using namespace std;
int sum(int x, int y)
{
    if (x == y)
        return x;
    else
        return y + sum(x, y - 1);
}

int main()
{
    cout << sum(4, 6) << endl;
    return 0;
}

This is a recursive function sum. It takes two integer parameters, x and y, which represent the range of numbers to sum. Here’s how the function works:

  • The base case: If x is equal to y, it means we have reached the end of the range, so it returns x. This is the terminating condition for the recursion.
  • The recursive case: If x is not equal to y, it adds the current value of y to the result of calling the sum function again with the same x and y-1. This effectively breaks down the sum of the range into smaller subproblems by reducing the upper bound (y) by 1 in each recursive call.

n the main function, it calls the sum function with the arguments 4 and 6 and then outputs the result to the console using cout. In this case, it will calculate the sum of integers from 4 to 6 (inclusive) and print the result.

When you run this code, it will output the sum of integers from 4 to 6, which is 4 + 5 + 6 = 15. So, the output of this code will be:

15

Function part 8 (Overloading Function)

Function overloading is a feature of C++ that allows you to have two or more functions with the same name, as long as they have different parameters. This can be useful when you want to have a single function that can perform different tasks, depending on the type of data that is passed to it as an argument.

For example, this code is a set of three C++ functions that print different types of data to the console.

#include <iostream>
using namespace std;

void print(int a)
{
    cout << "Integer = " << a << endl;
}
void print(float a)
{
    cout << "Float = " << a << endl;
}
void print(char c)
{
    cout << "Character = " << c << endl;
}

int main()
{
    print(1);
    print('a');
    return 0;
}

The first function, print(int a), takes an integer as an argument and prints it to the console with the prefix “Integer = “.

The second function, print(float a), takes a floating-point number as an argument and prints it to the console with the prefix “Float = “.

The third function, print(char c), takes a character as an argument and prints it to the console with the prefix “Character = “.

Output:

Integer = 1
Character = a

 

Function part 9 (Default arguments)

Default arguments are a feature of C++ that allows you to specify a default value for a function parameter. This means that if a caller of the function does not provide a value for a particular parameter, the default value will be used instead.

Default arguments can be useful for simplifying the code that calls a function, and for making the function more flexible. For example, you could have a function that takes two parameters, but where the second parameter is optional. You could then specify a default value for the second parameter, so that callers of the function do not have to provide a value for it if they do not want to.

Here is an example of how to use default arguments in C++:

#include <iostream>
using namespace std;

int sum(int a = 5, int b = 5, int c = 5)
{
    return a + b + c;
}

int main()
{
    cout << sum(10, 55) << endl;
    return 0;
}

The code you provided is a C++ program that calculates the sum of three integers. The program uses default arguments to provide default values for the three integers. This means that if the caller of the sum() function does not provide values for all three integers, the default values will be used instead.

The main() function calls the sum() function with the arguments 10 and 55. The sum() function will then return the sum of the three integers, which is 70. The main() function will then print the result to the console.

Output:

70

Here are some tips for using default arguments:

  • Do not write your default argument in the middle of two arguments like this (int a, int b = 5, int c), it will produce an error to the compiler.
  • Be careful not to overwrite default parameters with values that are not valid for the function.
  • Use default parameters to provide default values for parameters that are not essential to the function’s functionality.

Function part 10 (Inline Function)

An inline function in C++ is a function whose code is substituted at the point of call. This means that the compiler copies the code of the inline function into the calling function, instead of generating a call instruction.

Inline functions are typically used for small functions that are frequently called. This can improve the performance of the program, as it eliminates the overhead of function calls.

To declare an inline function in C++, you use the inline keyword before the function declaration. For example:

#include <iostream>
using namespace std;

inline void p()
{
    cout << "hello" << endl;
}

int main()
{
    p();
    p();
    p();
    return 0;
}

inline void p(), defines an inline function called p(). The function takes no arguments and simply prints the word “hello” to the console, followed by a newline character.

The three lines, p();, p();, and p();, call the p() function three times.

When the program is executed, the following output will be printed to the console:

hello
hello
hello

It is important to note that the compiler is not obligated to inline a function, even if it is declared as inline. The compiler may choose not to inline a function if it is too large or if it is called indirectly.

Here are some of the benefits of using inline functions:

  • Improved performance: Inline functions can improve the performance of a program by eliminating the overhead of function calls.
  • Reduced code size: Inline functions can reduce the code size of a program by removing the need to generate separate code for each function call.
  • Increased readability: Inline functions can make code more readable by eliminating the need to jump back and forth between different functions.

However, there are also some potential drawbacks to using inline functions:

  • Increased compile time: Inlining functions can increase the compile time of a program, as the compiler needs to copy the code of the inline function into each calling function.
  • Increased code size: If an inline function is called frequently, it can increase the code size of the program.
  • Reduced maintainability: Inline functions can make code more difficult to maintain, as the code for the inline function is scattered throughout the program.

Overall, inline functions can be a useful tool for improving the performance and readability of code. However, it is important to use them carefully, as they can also increase the compile time and code size of a program.

Here are some tips for using inline functions effectively:

  • Only inline small functions that are frequently called.
  • Avoid inlining functions that are too large or that are called indirectly.
  • Use the inline keyword consistently, so that the compiler can make informed decisions about whether or not to inline a function.
  • Document your code clearly, so that other developers understand how and why inline functions are being used.

Static variable

A static variable in C++ is a variable that is allocated once and remains in memory throughout the execution of the program. Static variables can be declared at global scope, namespace scope, class scope, or function scope.

Static variables at global scope are initialized when the program starts and are destroyed when the program ends. Static variables at namespace scope are initialized when the namespace is loaded and are destroyed when the namespace is unloaded. Static variables in classes are initialized when the class is first used and are destroyed when the program ends. Static variables in functions are initialized when the function is first called and are destroyed when the function returns.

Static variables can be useful for a variety of purposes, such as:

  • Storing global state information: Static variables can be used to store global state information that needs to be accessed by multiple functions in a program.
  • Implementing singletons: Static variables can be used to implement singletons, which are classes that can only have one instance.
  • Implementing lazy initialization: Static variables can be used to implement lazy initialization, which is a technique for delaying the initialization of a variable until it is first used.

Here is an example of a static variable declared in a function:

#include <iostream>
using namespace std;

void fun()
{
    static int x = 0;
    x++;
    cout << x << endl;
}

int main()
{
    fun();
    fun();
    return 0;
}

This code is a C++ program that defines a function called fun() and then calls it twice from the main() function. The fun() function declares a static variable called x and increments it each time it is called. The function then prints the value of x to the console.

Because x is a static variable, its value is preserved between function calls. This means that when the fun() function is called the second time, the value of x will be 1, not 0. Therefore, the output of the program will be as follows:

1
2

This code demonstrates how static variables can be used to store state information that needs to be accessed by multiple function calls.

Aliasing & Constant Variable

Aliasing

Aliasing in C++ is when two or more different names refer to the same memory location. This can happen when you use pointers or references, or when you declare two variables of the same type and initialize them to the same value.

For example, the following code creates an alias to the variable x:

int x = 1;
int &y = x;

Now, both the variables x and y refer to the same memory location. If you change the value of x, the value of y will also change.

Example:

#include <iostream>
using namespace std;

int main()
{
    int x = 1;
    int &y = x;
    x = 5;
    int &z = y;
    cout << "x = " << x << " " << "y = " << y << " " << "z = " << z << endl;
    y = 7;
    cout << "x = " << x << " " << "y = " << y << " " << "z = " << z << endl;
    y = x + z - 3;
    cout << "x = " << x << " " << "y = " << y << " " << "z = " << z << endl;

    return 0;
}

The code begins by declaring an integer variable named x and initializing it to 1. Then, it declares an integer reference named y and binds it to the variable x. This means that y is now an alias for x.

Next, the code assigns the value 5 to the variable x. This also changes the value of the variable y, since it is an alias for x.

Then, the code declares another integer reference named z and binds it to the variable y. This means that z is also an alias for x.

Now, all three variables x, y, and z refer to the same memory location. This means that changing the value of any one of these variables will also change the value of the other two variables.

The code then prints the values of the variables x, y, and z to the console. The output will be:

x = 5 y = 5 z = 5

Next, the code assigns the value 7 to the variable y. This also changes the values of the variables x and z, since they are all aliases for the same memory location.

The code then prints the values of the variables x, y, and z to the console. The output will be:

x = 7 y = 7 z = 7

Finally, the code calculates the value of x + z - 3 and assigns it to the variable y. This also changes the values of the variables x and z, since they are all aliases for the same memory location.

The code then prints the values of the variables x, y, and z to the console. The output will be:

x = 11 y = 11 z = 11

This code demonstrates how aliasing can be used to change the values of multiple variables at once. It also demonstrates how aliasing can be used to create aliases for complex expressions.

It is important to note that aliasing can be a powerful tool, but it can also lead to confusion and errors if used incorrectly. It is important to carefully consider the implications of aliasing before using it in your code.

Constant Variable

A constant variable in C++ is a variable whose value cannot be changed after it is initialized. To declare a constant variable, you use the const keyword before the variable type. For example:

const double Pi = 3.14;

Once you have declared a constant variable, you cannot assign a new value to it. If you try to do so, the compiler will generate an error.

Example:

#include <iostream>
using namespace std;

int main()
{
    const double Pi = 3.14;
    int r;
    cout << "please enter r: ";
    cin >> r;
    double a = Pi * r * r;
    cout << "Area of circle = " << a << endl;

    return 0;
}

This code calculates the area of a circle. The program begins by declaring a constant double variable named Pi and initializing it to the value 3.14. Then, it declares an integer variable named r and prompts the user to enter a value for it.

Next, the program calculates the area of the circle using the following formula:

  • Area = πr²

The program then prints the area of the circle to the console.

Here is a breakdown of the code:

int main()
{
  // Declare a constant double variable named Pi and initialize it to the value 3.14.
  const double Pi = 3.14;

  // Declare an integer variable named r.
  int r;

  // Prompt the user to enter a value for r.
  cout << "please enter r: ";
  cin >> r;

  // Calculate the area of the circle.
  double a = Pi * r * r;

  // Print the area of the circle to the console.
  cout << "Area of circle = " << a << endl;

  return 0;
}

Output:

please enter r: 5
Area of circle = 78.5

Aliasing and constant variables can interact in a few interesting ways:

  • If you have a constant variable and you create an alias to it, the alias is also constant. This is because the alias is just another name for the same variable, and the value of the variable cannot be changed.
  • If you have a constant variable and you pass it to a function as a parameter, the function cannot change the value of the variable. This is because the function is only allowed to modify the local copy of the variable.
  • If you have a pointer to a constant variable, you can still use the pointer to dereference the variable and read its value. However, you cannot use the pointer to change the value of the variable.

Here is an example of aliasing and constant variables in C++:

#include <iostream>
using namespace std;

int main()
{
    int i = 1;
    int &j = i;
    cout << "j = " << j << endl;
    const int &k = j;
    cout << "k = " << k << endl;

    return 0;
}

Output:

j = 1
k = 1

 

One Dimensional Array (part 1)

An array is a data structure that stores a collection of elements of the same data type. These elements are stored in contiguous memory locations, and they can be accessed using an index. Arrays provide a way to manage and manipulate a large set of data efficiently.

In C++, you can declare an array by specifying its data type and the number of elements it will hold. Here’s a basic syntax:

data_type array_name[array_size];

Arrays in C++ are zero-indexed, meaning the first element is accessed using the index 0, the second element with index 1, and so on. You can access and modify array elements using square brackets:

array_name[index] = new_value;

Here is an example:

#include <iostream>
using namespace std;

int main()
{
    int x[5];
    x[0] = 10;
    x[1] = 20;
    cout << x[0] << endl;
    x[2];
    x[3];
    x[4];

    return 0;
}

1. int x[5];

This line declares an integer array named x with a size of 5. It means that x can store five integer values. However, at this point, the values in the array are uninitialized, which means they contain random data.
2. x[0] = 10;

Here, we assign the value 10 to the first element of the array x. In C++, arrays are zero-indexed, so x[0] refers to the first element.
3. x[1] = 20;

Similarly, we assign the value 20 to the second element of the array x, which is x[1].
4. cout << x[0] << endl;

This line prints the value of the first element of the array x, which is 10, to the console. It uses the cout object from the C++ Standard Library to output the value, followed by an end-of-line character (endl) for formatting.
5. x[2];

These lines appear to be accessing the third element of the array x, but they don’t do anything. It’s essentially a “noop” operation, and the value in x[2] remains uninitialized or unchanged.
6. x[3]; and x[4];

Similar to the previous line, these lines access the fourth and fifth elements of the array x, but they also don’t perform any meaningful operation.

Output:

10

Here is another example:

#include <iostream>

using namespace std;

int main()
{
    int x[5];
    x[0] = 10;
    x[1] = 5;
    x[4] = x[0] + x[1];
    cout<< x[4] << endl;

    return 0;
}

Output:

15

Arrays only accept constant array size, Example:

#include <iostream>

using namespace std;

int main()
{
    const int t = 5;
    int x[t];

    return 0;
}

This code declares an integer array `x` with a size of 5, and the size is determined by the constant `t`, which is set to 5. The `const` keyword ensures that `t` cannot be changed later in the program. This code doesn’t perform any further operations on the array; it simply demonstrates how to declare an array with a size determined by a constant.

You can also declare the size of your array, and declare the initial values of your array:

#include <iostream>

using namespace std;

int main()
{
    int x[5] = { 1,4,8,7,2 };
    cout << x[0] << endl;

    return 0;
}

This code declares an integer array x with a size of 5 and initializes it with the values 1, 4, 8, 7, and 2. It then prints the first element of the array, which is 1, to the console. This code demonstrates how to create an array and access its elements in C++.

But what if you declared no initial values into your array?

#include <iostream>

using namespace std;

int main()
{
    int x[5];
    cout << x[3] << endl;

    return 0;
}

This code declares an integer array x with a size of 5 but does not initialize its elements. Therefore, when you attempt to print the value of the fourth element, it will display a random or garbage value. It’s important to initialize array elements before using them to avoid unpredictable behavior in your programs.

What if you declared only one initial value that equals to 0?

#include <iostream>

using namespace std;

int main()
{
    int x[5] = {0};
    cout << x[3] << endl;

    return 0;
}

This code declares an integer array x with a size of 5 and initializes all its elements to 0. It then prints the value of the fourth element of the array, which is 0, to the console. This code demonstrates how to create an array with specific initial values in C++.

You can also declare a size of array and declare some of the first initial values, for example:

#include <iostream>

using namespace std;

int main()
{
    int x[5] = {1,2,3};
    cout << x[3] << endl;

    return 0;
}

This code declares an integer array x with a size of 5 and initializes the first three elements with values, while the remaining two elements are automatically initialized to 0. It then prints the value of the fourth element, which is 0, to the console.

Or, you can declare no size of your array and only declare the initial values of your array:

#include <iostream>

using namespace std;

int main()
{
    int x[] = {1,2,3,4,5};
    cout << x[3] << endl;

    return 0;
}

This code declares an integer array x and initializes it with values using an array initialization list. It then prints the value of the fourth element of the array, which is 4, to the console. This code demonstrates how to create an array and access its elements in C++.

How does the compiler store the values on an array?

The compiler stores the values of an array in contiguous memory locations. This means that the values of the array elements are stored next to each other in memory. The compiler allocates a block of memory that is large enough to store all of the array elements, and then it stores the values of the elements in this block of memory.

The compiler keeps track of the address of the first element in the array, and then it uses this address to access the other elements in the array. For example, to access the element at index i, the compiler adds i to the address of the first element.

The specific way that the compiler stores the values of an array depends on the data type of the array elements. For example, if the array elements are integers, the compiler will store each integer in a single memory location. However, if the array elements are structs, the compiler will store each struct in a contiguous block of memory locations.

This code shows you how to read and store user input in an array in C++, it allows the user to input an integer value for the first element of an array, arr[0], and then it displays the value that was entered.

#include <iostream>

using namespace std;

int main()
{
    int arr[50];
    cout << "Enter arr[0]: " << endl;
    cin >> arr[0];
    cout << arr[0] << endl;

    return 0;
}

 

To traverse the elements of an array, you can use loops like for or while. Looping through an array allows you to perform operations on each element systematically.

Example:

#include <iostream>

using namespace std;

int main()
{
    int arr[10];
    for (size_t i = 0; i < 10; i++)
    {
        cout << "Enter arr[" << i << "]: ";
        cin >> arr[i];
    }
    for (size_t i = 0; i < 10; i++)
    {
        cout << "arr[" << i << "] = " << arr[i] << endl;
    }

    return 0;
}

This code allows the user to input 10 integer values, one for each element of the array, and then it displays the values along with their indices. It demonstrates how to read and store multiple user inputs in an array and subsequently print the contents of the array in C++.

One Dimensional Array (part 2)

Arrays are incredibly versatile, and you can perform various operations on them, such as copying the initial values of an existing array into another one.

Of course we cannot use the following command:

arr2 = arr1;

Because we aren’t assigning a single value. Each array has a collection of values, so if we need to assign a single value in an array we have to specify its index:

arr2[0] = arr1[0];

But what if we need to assign all the values of an array into another array?

Example 1:

#include <iostream>

using namespace std;

int main()
{
    const int s = 4;
    int arr1[s] = { 10,20,30,40 };
    int arr2[s];

    for (size_t i = 0; i <= s-1; i++)
    {
        arr2[i] = arr1[i];
    }

    for (size_t i = 0; i < s; i++)
    {
        cout << arr2[i] << " ";
    }
    cout << endl;

    return 0;
}

This code initializes an array arr1 with values, then copies the contents of arr1 into another array arr2. Finally, it prints the elements of arr2. This demonstrates how to copy the contents of one array into another in C++.

Output:

10 20 30 40

Example 2:

#include <iostream>

using namespace std;

int main()
{
    const int s = 5;
    int arr[s] = { 100,200,200,500,0 };
    int sum = 0;
    
    for (size_t i = 0; i < s; i++)
    {
        //sum += arr[i];
        sum = sum + arr[i];
    }
    cout << "sum = " << sum << endl;

    return 0;
}

This code calculates the sum of the elements in the integer array arr and then prints the result to the console. It demonstrates how to use a loop to iterate through an array and accumulate values.

Output:

sum = 1000

Example 3:

#include <iostream>

using namespace std;

int main()
{
    const int s = 5;
    int arr[s] = { 100,200,200,500,100 };
    long long d = 1;
    
    for (size_t i = 0; i < s; i++)
    {
        d *= arr[i];
    }
    cout << "multi = " << d << endl;

    return 0;
}
  • long long d = 1; :This line initializes a long long integer variable d to 1. This variable will be used to accumulate the product of the elements in the array.
  • long long is a data type in C++ that represents a 64-bit integer. It’s designed to store very large integer values. It can hold a wider range of values compared to regular int or long integers.
  • So, the statement long long d = 1; declares a variable named d with a data type of long long and initializes it with the value 1. This variable can then be used to store and manipulate large integer values in your program.

In summary, this code calculates the product of the elements in the integer array arr and then prints the result to the console. It demonstrates how to use a loop to iterate through an array and accumulate the product of its elements.

Output:

multi = 200000000000

Example 4:

#include <iostream>

using namespace std;

int main()
{
    const int s = 5;
    int arr[s] = { 100,200,200,501,101 };
    int sumEven, sumOdd = 0;
    
    for (size_t i = 0; i < s; i++)
    {
        if (arr[i] % 2 == 0)
            sumEven += arr[i];
        else
            sumOdd += arr[i];
    }
    cout << "Sum of even numbers = " << sumEven << endl;
    cout << "Sum of odd numbers = " << sumOdd << endl;

    return 0;
}

This code calculates the sum of even and odd numbers separately in the integer array arr and then prints the results to the console.

Output:

Sum of even numbers = 500
Sum of odd numbers = 602

Example 5:

#include <iostream>

using namespace std;

int main()
{
    const int s = 6;
    int marks[s] = { 100,99,98,88,70,90 };
    int sum = 0;
    for (size_t i = 0; i < s; i++)
    {
        sum += marks[i];
    }
    cout << "Average = " << sum / s << endl;

    return 0;
}

This code calculates the average of the marks stored in the integer array marks and then prints the average to the console.

Output:

Average = 90

Example 6:

#include <iostream>

using namespace std;

int main()
{
    const int s = 6;
    int arr[s] = { 22,100,95,101,200,90 };
    int max = 0;
    for (size_t i = 0; i < s; i++)
    {
        if (arr[i] > max)
            max = arr[i];
    }
    cout << "Maximum number = " << max << endl;

    return 0;
}

This code finds the maximum value among the numbers stored in the integer array arr and then prints the maximum value to the console.

Output:

Maximum number = 200

Example 7:

#include <iostream>

using namespace std;

int main()
{
    int vector[5];
    cout << "Enter 5 numbers: ";
    for (int i = 0; i < 5; i++)
        cin >> vector[i];
    cout << endl;
    
    int Element;
    cout << "What is the element you are looking for? ";
    cin >> Element;
    
    bool Found = false;
    int i;
    for (i = 0; i < 5; i++)
        if (Element == vector[i])
        {
            Found = true;
            break;
        }
    cout << endl;
    if (Found)
        cout << Element << " found at position " << i << endl;
    else
        cout << Element << " is not in this array!" << endl;

    return 0;
}

In this C++ code, you’re taking user input to populate an integer array `vector` of size 5 and then searching for a specific element within the array. Let’s break down the code step by step:

  1. int vector[5];
    – This line declares an integer array `vector` with a size of 5, which can store up to five integer values.
  2. Input Loop to Populate the Array:
    – The code prompts the user to enter five numbers and stores them in the `vector` array using a `for` loop that iterates five times. Each input is assigned to a different element of the array.
  3. int Element;
    – This line declares an integer variable `Element`, which will store the value the user is searching for.
  4. Prompt for the Element to Search:
    – The code asks the user to input the element they want to search for.
  5. Search Loop:
    – The `for` loop is used to search for the element within the array. If the element is found, the loop breaks, and the `Found` flag is set to `true`. The variable `i` keeps track of the position where the element was found.
  6. Output the Result:
    – The code then checks if the element was found (i.e., `Found` is `true`). If found, it displays the element and its position in the array. If not found, it informs the user that the element is not in the array.

In summary, this code allows the user to enter five numbers into an array and then search for a specific element within the array. It provides feedback on whether the element was found and its position in the array.

One Dimensional Array part 3 (Passing Array To Function)

In C++, you can pass an array to a function, and this is a fundamental concept when working with arrays. When you pass an array to a function, you’re essentially allowing that function to operate on the array’s elements or modify the array if needed.

Here’s an explanation of how to pass an array to a function in C++:

Array Declaration in a Function

Array Parameters: To pass an array to a function, you need to declare the function parameter as an array. You can declare it in two ways:

  • Using a Fixed Size: If you know the size of the array in advance, you can specify the size in the function parameter, like this:
void functionName(int arr[5]) {
    // Code to work with the array
}
  • Using a Pointer: You can also declare the function parameter as a pointer to the array’s elements without specifying the size, like this:
void functionName(int *arr, int size) {
    // Code to work with the array
}

In this case, you pass the size of the array as a separate argument.

Passing the Array to the Function

Calling the Function: When you call the function, you provide the array as an argument. If you declared the function parameter with a fixed size, you pass the array directly. If you used a pointer, you pass the array and its size as arguments.

Example with a fixed-size array parameter:

int myArray[5] = {1, 2, 3, 4, 5};
functionName(myArray);

Example with a pointer parameter:

int myArray[5] = {1, 2, 3, 4, 5};
functionName(myArray, 5);

Using the Array in the Function

Working with the Array: Inside the function, you can access and manipulate the elements of the array as needed. You can use array indices (e.g., arr[0], arr[1]) to access individual elements, and you can use loops to iterate through the elements.

Example of accessing array elements:

void functionName(int arr[5]) {
    for (int i = 0; i < 5; i++) {
        // Access and manipulate arr[i]
    }
}

Here is a demonstration of passing an array to functions for setting values in the array and then printing those values:

#include <iostream>
using namespace std;

void set(int arr[], int s)
{
    for (size_t i = 0; i < s; i++)
    {
        cout << "Enter array value: ";
        cin >> arr[i];
    }
}

void print(int arr[], int s)
{
    for (size_t i = 0; i < s; i++)
    {
        cout << arr[i] << " ";
    }
}

int main()
{
    int a[5];
    set(a, 5);
    print(a, 5);

    return 0;
}

The set function allows the user to set values in the array, and the print function prints the values stored in the array. It’s a practical example of how to work with arrays and functions in C++.

Modifying the Array

Example 1:

This code shows an implementation of the “Bubble Sort” algorithm. Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, indicating that the list is sorted. Here’s a breakdown of the code:

#include <iostream>
using namespace std;

int main()
{
    int vector[] = {6,5,4,1,2};
    int t = 0;
    
    // Bubble Sort algorithm
    for (size_t i = 0; i < 5 - 1; i++)
    {
        for (size_t j = 0; j < 5 - i - 1; j++)
        {
            if (vector[j] > vector[j + 1])
            {
                t = vector[j];
                vector[j] = vector[j + 1];
                vector[j + 1] = t;   
            }
        }
    }
    
    for (size_t i = 0; i < 5; i++)
    {
        cout << vector[i] << endl;
    }

    return 0;
}
  1. int vector[] = {6, 5, 4, 1, 2};:
    An integer array vector is initialized with unsorted values.
  2. int t = 0;:
    An integer variable t is declared to be used for swapping elements during the sorting process.
  3. Bubble Sort Algorithm:
    The nested for loops are used to implement the Bubble Sort algorithm. The outer loop (i) controls the number of passes, and the inner loop (j) compares adjacent elements and swaps them if they are out of order.
  4. If the element at index j is greater than the element at index j + 1, a swap is performed to put them in ascending order.
  5. Printing the Sorted Array:
    After sorting is complete, the code uses a for loop to print the sorted elements in ascending order.

The output of this code will be the sorted array in ascending order, which is the result of applying the Bubble Sort algorithm to the initial unsorted array. Bubble Sort is not the most efficient sorting algorithm for large data sets, but it’s easy to understand and implement.

Example 2:

This code performs the sorting of an integer array using the Bubble Sort algorithm. It sorts the array in ascending order and then prints the sorted values. Let’s break down the code step by step:

#include <iostream>
using namespace std;

const int s = 5;
void sort(int arr[])
{
    int t = 0;
    for (size_t i = 0; i < 5 - 1; i++)
    {
        for (size_t j = 0; j < 5 - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                t = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = t;   
            }
        }
    }
}

void print(int vector[])
{
    for (size_t i = 0; i < 5; i++)
    {
        cout << vector[i] << endl;
    }
}

int main()
{
    int vector[] = {0,-1,55,-5,-100};
    sort(vector);
    print(vector);
    return 0;
}

The output of this code will be the sorted array in ascending order, which is the result of applying the Bubble Sort algorithm to the initial unsorted array.

Example 3:

This code demonstrates how to reverse the elements of an integer array using a reversArray function. It reverses the array in-place and then prints the reversed array:

#include <iostream>
using namespace std;

void reversArray(int arr[], int s)
{
    for (size_t i = 0; i < s / 2; i++)
    {
        swap(arr[i], arr[s - i - 1]);
    }
}

int main()
{
    int vector[] = {3,2,4,5,6};
    reversArray(vector, 5);
    for (size_t i = 0; i < 5; i++)
    {
        cout << vector[i] << " ";
    }

    return 0;
}

The output of this code will be the reversed array, where the elements are reversed in place. This is achieved by swapping the first element with the last element, the second element with the second-to-last element, and so on. It’s a simple and efficient way to reverse the order of elements in an array.

 

Note:

If you don’t want to modify your array you can initial its value as a constant in the function. Example:

void print(const int arr[], int s)
{
    //body of the function
}

This way any try to modify the array will produce an error.

One Dimensional Array part4 (Array Of Character)

An array of characters in C++ is often referred to as a “string.” It is a fundamental data structure used to store sequences of characters, such as words, sentences, or even individual characters. In C++, strings are represented as arrays of characters, terminated by a special null character, ‘\0’, which indicates the end of the string.

to initiate a character we use a single quotation like this ‘L’.

Example 1:

char ch[5] = { 'a','b','c','d','e','\0' };

The null character (‘\0’), NULL or 0, is used to indicate the end of the string. This character is automatically added to the end of string literals and is crucial for various string manipulation functions.

If you add characters after the null character they won’t be read by the program.

Example 2:

#include <iostream>
using namespace std;
int main()
{
    char ch[5];
    cin >> ch;
    cout << ch << endl;
    return 0;
}

This code reads a sequence of characters into a char array and then prints the array. However, there are a few things to note about potential issues and improvements in the code:

  1. Array Size:
    The char array ch has a size of 5. If you enter more than 4 characters, it will result in a buffer overflow, causing undefined behavior. It’s essential to ensure that the input doesn’t exceed the array size.
  2. Input Method:
    When using cin >> ch, it reads characters until it encounters whitespace. If you want to read an entire line (including spaces), you should use cin.getline(ch, size) or cin.get(ch, size).

Example 3:

#include <iostream>
using namespace std;

int main() {
    char ch[10];

    // Read up to 9 characters into the char array
    cin.get(ch, 10);

    // Output the char array
    cout << ch << endl;

    return 0;
}

This code reads up to 9 characters (plus the null terminator) into a char array using cin.get() and then prints the array.
Here are a few points to note:

  1. Array Size:
    The char array ch has a size of 10. Since cin.get() reads up to one less than the specified size (leaving space for the null terminator), it effectively reads up to 9 characters.
  2. Input Method:
    cin.get(ch, 10) reads characters until either 9 characters are read, the newline character is encountered, or the end of file is reached. It stops reading after reaching the specified number of characters or encountering one of these conditions.
  3. Null Terminator:
    The array is not explicitly null-terminated by cin.get(); however, C++ streams automatically append a null terminator at the end of the string when reading into a character array. Therefore, the array ch is effectively treated as a C-style string.

Output:

The cout << ch << endl; statement prints the contents of the char array, treating it as a null-terminated string. If fewer than 9 characters were entered, it prints the characters entered. If 9 characters were entered, it prints those 9 characters followed by the null terminator.

Input Limitation:

Keep in mind that the user input is limited to 9 characters, and exceeding this limit may lead to unexpected behavior. It’s essential to handle potential input overflows based on the specific requirements of your program.

Example 4:

#include <iostream>
using namespace std;
int main()
{
    char ch1[10], ch2[10];
    cin.getline(ch1, 10);
    cin.getline(ch2, 10);
    cout << ch1 << endl;
    cout << ch2 << endl;
    return 0;
}

This code reads two lines of input into separate char arrays and then prints each array on a new line.

Here are some points to note:

  1. Array Size:
    Both ch1 and ch2 are char arrays with a size of 10. The cin.getline() function reads characters until it encounters a newline character or reaches the specified size (leaving space for the null terminator).
  2. Input Limitation:
    The user input for each line is limited to 9 characters, and the null terminator is automatically added by cin.getline().
  3. Handling Spaces:
    Unlike cin >>, cin.getline() reads the entire line, including spaces. This allows you to input strings with spaces.

Output:

The cout << ch1 << endl; statement prints the contents of the first char array, treating it as a null-terminated string.
Similarly, cout << ch2 << endl; prints the contents of the second char array.
Newline Character:

Each call to cin.getline() reads until it encounters a newline character or reaches the specified size. The newline character is consumed but not stored in the arrays.
This code allows you to input two lines of text (up to 9 characters each) and then prints each line on a new line. It’s suitable for reading and displaying multiple lines of text, handling spaces, and avoiding buffer overflow issues.

 

There are some functions that are part of the C Standard Library and are used for manipulating C-style strings, which are arrays of characters. Here’s an explanation of each function:

  • strcpy (String Copy):

Description: The strcpy function is used to copy the contents of one C-style string to another.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    char ch1[] = "AAA";
    char ch2[4];
    strcpy_s(ch2, ch1);
    cout << ch2 << endl;
    return 0;
}
  1. strcpy_s Function:
    The strcpy_s function is part of the C Standard Library and is designed to provide safer string copying by including a size check.
  2. Buffer Size:
    The size of ch2 is explicitly specified as 4, which includes three characters for the content of ch1 (“AAA”) and one additional space for the null terminator (‘\0’).
  3. Safe String Copy:
    Unlike the standard strcpy function, strcpy_s requires you to provide the size of the destination array (destsz). It checks if there is enough space in the destination array to accommodate the source string and the null terminator. If there isn’t enough space, the function does not perform the copy and returns an error code.

Output:

The cout << ch2 << endl; statement outputs the contents of ch2, which should be “AAA” in this case.

By using strcpy_s, you are taking steps to prevent buffer overflow issues that could occur if the destination array is not large enough to hold the contents of the source string. This is a good practice for enhancing the safety and robustness of your code.

  • strcat (String Concatenate):

Description: The strcat function is used to concatenate (append) the contents of one C-style string to another.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    char ch1[] = "AAA";
    char ch2[4] = "HH";
    strcat(ch2, ch1);
    cout << ch2 << endl;
    return 0;
}
  1. strcat Function:
    The strcat function is part of the C Standard Library and is used to concatenate the contents of one C-style string to another.
  2. Buffer Size:
    The size of ch2 is explicitly specified as 4, which includes two characters (“HH”) and one additional space for the null terminator (‘\0’).
  3. Concatenation:
    The strcat(ch2, ch1); line appends the contents of ch1 to the end of ch2. It starts copying characters from the null terminator of ch2 to the end of ch1 until it encounters the null terminator of ch1. The null terminator of ch2 is updated accordingly.

Output:

The cout << ch2 << endl; statement outputs the contents of ch2 after the concatenation. Since the size of ch2 is limited to 4, it can hold “HH” and the null terminator, but only one additional character from ch1 (“A”) can be accommodated.
Result:

The output of this code is “HHA”, which is the result of concatenating “AAA” to the end of the existing content in ch2.
It’s important to ensure that the destination array has enough space to accommodate the concatenated string, and using functions like strcat requires careful management of buffer sizes to prevent buffer overflows.

  • strcmp (String Compare):

Description: The strcmp function is used to compare two C-style strings lexicographically.

The strcmp function returns an integer value indicating the lexicographic relationship between the two strings. It returns:
– 0 if the strings are equal,
– a negative value if str1 is lexicographically less than str2,
– a positive value if str1 is lexicographically greater than str2.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    cout << strcmp("abc", "abc") << endl;
    return 0;
}

Output:

The cout statement outputs the result of the comparison using strcmp. In this case, since the strings are equal, the output will be 0.

The strcmp function is commonly used for sorting strings, dictionary operations, and other scenarios where you need to determine the lexicographic order of strings. It’s important to handle the result appropriately based on your specific requirements in the program.

  • strlen (String Length):

Description: The strlen function is used to determine the length of a C-style string.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    char ch[] = "jjjjjjjjjjjjjjjjjjjjj";
    cout << strlen(ch) << endl;
    return 0;
}

Output:

The cout statement outputs the result of strlen(ch), which is the length of the string “jjjjjjjjjjjjjjjjjjjjj”. Since there are 21 characters in the string, the output will be 21.

The strlen function is useful for obtaining the length of strings, and it’s important to note that the length does not include the null terminator. Make sure that the string is properly null-terminated to get accurate results with strlen.

 

 

 

 

 

Two Dimensional Array

A two-dimensional array in C++ is a structure that allows you to store elements in a tabular form, organized in rows and columns. It is essentially an array of arrays.

Here’s an explanation of a two-dimensional array in C++:

  • Declaration and Initialization:
// Declaration of a 2D array
int matrix[3][4];

// Initialization of a 2D array
int anotherMatrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
  • Structure:

In a 2D array, elements are arranged in rows and columns. The first index represents the row, and the second index represents the column.

  • Memory Representation:

In memory, a 2D array is stored in a contiguous block of memory. The elements of each row are stored together, and rows are stored one after the other.

  • Accessing Elements:
int value = matrix[1][2];  // Accessing the element in the second row and third column
  • Initialization with Nested Loops:

Common Operations:

– Iterating through elements using nested loops.
– Performing operations on each element.
– Passing a 2D array to functions.

Example 1:

#include <iostream>
using namespace std;
int main()
{
    int a[3][4];
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 4; j++)
        {
            cin >> a[i][j];
        }
    }
    for (size_t r = 0; r < 3; r++)
    {
        for (size_t c = 0; c < 4; c++)
        {
            cout << a[r][c] << " ";
        }
        cout << endl;
    }
    return 0;
}

This code allows the user to input values into a 2D array a[3][4] and then prints the array in a tabular form.

Here are the key points:

  1. 2D Array Input:
    The nested loops (for loops) are used to iterate over each element of the 2D array and input values using cin.
  2. 2D Array Output:
    Another set of nested loops is used to iterate over each element of the 2D array and output the values using cout.
    The inner loop prints each row, and the outer loop moves to the next row, creating a tabular form.
  3. Tabular Output:
    The cout << a[r][c] << ” “; statement prints each element of the 2D array followed by a space.
    The cout << endl; statement is used to move to the next line after printing each row.
  4. User Interaction:
    The user is prompted to input values for each element of the 2D array. The input is expected to be provided in a row-wise fashion.
  5. Array Size:
    The array a is declared with 3 rows and 4 columns, creating a 3×4 matrix.

This code allows the user to interactively input values into a 3×4 2D array and then displays the array in a tabular format.

Example 2:

#include <iostream>
using namespace std;

int main() {
    // Initialization of a 2D array with predefined values
    int arr[2][4] = {{1, 1, 1, 1}, {2, 2, 2, 2}};
    
    // Variable to store the sum of array elements
    int sum = 0;

    // Nested loops to iterate over each element of the 2D array
    for (size_t r = 0; r < 2; r++) {
        for (size_t c = 0; c < 4; c++) {
            // Accumulate the values to calculate the sum
            sum += arr[r][c];
        }
    }

    // Output the sum of array elements
    cout << "sum = " << sum << endl;

    return 0;
}

Output:

In this specific example, the sum is calculated as follows: 1 + 1 + 1 + 1 + 2 + 2 + 2 + 2 = 12.
The output will be sum = 12.

This code is a simple illustration of how to iterate over elements in a 2D array and perform a basic operation, in this case, calculating the sum of all elements.

Example 3:

#include <iostream>
using namespace std;
int main()
{
    int marks[10][5];
    for (size_t r = 0; r < 10; r++)
    {
        for (size_t c = 0; c < 5; c++)
        {
            cout << "Enter mark " << c + 1 << " " << "for student " << r + 1 << ": " << endl;
            cin >> marks[r][c];
        }
    }
    double s = 0;
    float avg[10];
    for (size_t r = 0; r < 10; r++)
    {
        s = 0;
        for (size_t c = 0; c < 5; c++)
        {
            s += marks[r][c];
        }
        avg[r] = s / 5;
        cout << "Average for student #" << r + 1 << " = "<< avg[r] << endl;
    }
    return 0;
}

This code collects marks for 10 students in 5 subjects, calculates the average mark for each student, and then outputs the average for each student.

Example 4:

#include <iostream>
using namespace std;
int main()
{
    char MTXchar[5][5] = {{'*','$','$','$','$'},
                          {'$','*','$','$','$'},
                          {'$','$','*','$','$'},
                          {'$','$','$','*','$'},
                          {'$','$','$','$','*'}};
                          
    for (size_t r = 0; r < 5; r++)
    {
        for (size_t c = 0; c < 5; c++)
        {
            
            if (c == r)
                cout << MTXchar[r][c];
            else
                cout << " ";
        }
        cout << endl;
    }
    return 0;
}

This code defines a 5×5 matrix (MTXchar) containing ” characters on the main diagonal and ‘$’ characters elsewhere. It then prints only the characters on the main diagonal, resulting in a diagonal line of ” characters.

Output:

The code outputs a diagonal line of ‘*’ characters on the console.

*    
 *   
  *  
   * 
    *

 

Passing a two-dimensional array to a function in C++ involves specifying the array as a parameter in the function declaration. Since a 2D array is essentially an array of arrays, you need to specify the size of the columns (since the rows are implicitly known based on the number of arrays).

  • Function Declaration:

When declaring a function that accepts a 2D array, you need to specify the array parameter along with the size of the columns. The size of the rows is not explicitly specified.

void functionName(int arr[][COLS], size_t rows, size_t cols) {
    // Function logic using arr
}

– int arr[][COLS]: This syntax indicates that the function takes a 2D array of integers with a specified number of columns (COLS).
– size_t rows: This parameter can be used to pass the number of rows in the array.
– size_t cols: This parameter can be used to pass the number of columns in the array

  • Function Call:

When calling the function, you need to provide the actual 2D array along with the number of rows and columns.

int myArray[ROWS][COLS];
functionName(myArray, ROWS, COLS);

– myArray: The name of the 2D array you want to pass.
– ROWS: The number of rows in the array.
– COLS: The number of columns in the array.

Example 5:

#include <iostream>
using namespace std;
void f(int arr[][5], int r)
{
    for (size_t i = 0; i < r; i++)
    {
        for (size_t j = 0; j < 5; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}
int main()
{
    int a[2][5] = {1,2,3,4,5,
                   10,20,30,40,50};
    f(a, 2);
    return 0;
}

The function f takes a 2D array (arr) and its number of rows (r) as parameters.
It uses nested loops to iterate over each element of the array and prints the elements in a tabular form.

The main function calls the function f with the 2D array a and the number of rows (2) as arguments.

Output:

The output of this code would be the elements of the 2D array a printed in a tabular form.

The printed output would look like:

1 2 3 4 5 
10 20 30 40 50 
  • Transpose matrix

The transpose of a matrix is an operation that flips the matrix over its diagonal, switching the row and column indices of the matrix. In other words, if the original matrix has elements at position (i, j), the transposed matrix will have the element at position (j, i).

Example 6:

#include <iostream>
using namespace std;
int main()
{
    int arr[3][3];
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 3; j++)
        {
            cin >> arr[i][j];
        }
    }
    cout << "Matrix is: \n";
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 3; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    cout << "Transpose matrix is:\n";
    for (size_t i = 0; i < 3; i++)
    {
        for (size_t j = 0; j < 3; j++)
        {
            cout << arr[j][i] << " ";
        }
        cout << endl;
    }

    return 0;
}

This code takes user input for a 3×3 matrix, prints the original matrix, and then prints its transpose.

Here are the key points:

  1. Input:
    The nested loops take user input for a 3×3 matrix.
  2. Original Matrix Output:
    After taking input, the code outputs the original matrix.
  3. Transpose Matrix Output:
    Another set of nested loops outputs the transpose of the matrix. It switches the row and column indices.

Example Output:

If the user enters:

1 2 3
1 2 3
1 2 3

The output would be:

Matrix is: 
1 2 3 
1 2 3 
1 2 3 
Transpose matrix is:
1 1 1 
2 2 2 
3 3 3

 

Pointer

In C++, a pointer is a variable that stores the memory address of another variable. Pointers provide a powerful mechanism for working with memory and data structures. They allow direct manipulation of memory addresses and enable efficient memory management.

Declaring Pointers

To declare a pointer, you use the data type followed by an asterisk (*) and the pointer name. For example:

int *ptr; // Declares a pointer to an integer
double *dblPtr; // Declares a pointer to a double

Initializing Pointers

Pointers should be initialized before use. You can initialize a pointer by assigning the address of a variable to it. The address-of operator (&) is used to obtain the memory address of a variable.

int num = 10;
int *ptr = &num; // Initializes ptr with the address of num

Dereferencing Pointers

Dereferencing a pointer means accessing the value stored at the memory address it points to. The dereference operator (*) is used for this purpose.

int num = 10;
int *ptr = &num;

cout << *ptr; // Prints the value stored at the address pointed by ptr

Example 1:

#include <iostream>
using namespace std;

int main() {
    // Declaration of a pointer to an integer
    int *ptr;

    // Declaration and initialization of an integer variable
    int val = 5;

    // Assigning the address of 'val' to the pointer 'ptr'
    ptr = &val;

    // Printing the address stored in the pointer
    cout << ptr << endl;

    // Printing the value stored at the address pointed by 'ptr'
    cout << *ptr << endl;

    // Return 0 to indicate successful execution
    return 0;
}

This code declares a pointer, initializes an integer variable, assigns the address of that variable to the pointer, and then prints both the pointer’s value (memory address) and the value it points to.

Here are the key points:

  1. Pointer Declaration:
    int *ptr;: Declares a pointer to an integer. This pointer is currently uninitialized.
  2. Variable Declaration and Initialization:
    int val = 5;: Declares an integer variable named val and initializes it with the value 5.
  3. Assigning Address to Pointer:
    ptr = &val;: Assigns the memory address of the variable val to the pointer ptr. Now ptr “points” to the memory location of val.
  4. Printing Pointer’s Value (Memory Address):
    cout << ptr << endl;: Prints the memory address stored in the pointer ptr. The address is typically represented in hexadecimal format.
  5. Printing Value at the Address Pointed by Pointer:
    cout << *ptr << endl;: Uses the dereference operator (*) to access the value stored at the memory address pointed by ptr. Prints the value stored in the variable val.

Output:
If you run this program, the output will be something like:

0x7ffee3c86a4c   // The memory address (this will vary on each run)
5                // The value stored at the memory address

Example 2:

#include <iostream>
using namespace std;
int main()
{
    int *p;
    int v = 9;
    p = &v;
    cout << *p << endl;
    return 0;
}

This code prints the address of the value pointed to by the pointer p using the expressions &*p.

cout << &*p << endl;: Uses the dereference operator (*) to access the value stored at the memory address pointed by p. The & operator then takes the address of this value. Essentially, &*p is equivalent to just p, so this line prints the memory address stored in the pointer p.

 

Pointer part 2 (Array vs Pointer & Passing Pointer To Function)

Arrays in C++

An array is a collection of elements of the same type stored in contiguous memory locations. In C++, arrays can be of primitive types (int, float, etc.) or user-defined types (structures, classes). Arrays have a fixed size, and the elements are accessed using an index.

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

Pointers in C++

A pointer is a variable that stores the memory address of another variable. Pointers allow for dynamic memory allocation and manipulation. They are often used for efficient memory management and for accessing elements in arrays.

int x = 10;
int *ptr = &x; // ptr now holds the address of x

Array vs. Pointer

In many contexts, arrays and pointers in C++ exhibit similar behavior. When an array name is used in an expression, it decays into a pointer to its first element. For example:

int arr[3] = {1, 2, 3};
int *ptr = arr; // Equivalent to &arr[0]

However, there are differences:

  • An array variable cannot be reassigned to point to a different memory location, whereas a pointer can.
  • Arrays carry information about their size, while pointers do not inherently know the size of the memory they point to.
  • Arrays can be used with the sizeof operator to determine their size, but pointers alone cannot.

Pointer Arithmetic

Pointers can be incremented or decremented to navigate through an array or block of memory.

int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;

cout << *ptr; // Prints the first element (1)
ptr++;        // Moves to the next element
cout << *ptr; // Prints the second element (2)

 

Example 1:

#include <iostream>
using namespace std;
int main()
{
    int arr[7] = {11,22,33,44,55,66,77};
    for (size_t i = 0; i < 7; i++)
    {
        cout << *(arr + i) << endl;
    }
    return 0;
}

code prints the elements of an array using pointer arithmetic.

cout << *(arr + i) << endl;: Utilizes pointer arithmetic to access each element of the array. The expression arr + i calculates the memory address of the i-th element, and *(arr + i) dereferences the pointer to access the value stored at that address.

Output:
If you run this program, the output will be:

11
22
33
44
55
66
77

 

Example 2:

#include <iostream>
using namespace std;
int main()
{
    int arr[7] = {11,22,33,44,55,66,77};
    int *ptr;
    ptr = arr;
    for (size_t i = 0; i < 7; i++)
    {
        cout << *ptr << " ";
        ptr++;
    }
    return 0;
}

This code accomplishes the same goal as the previous example but uses a pointer (ptr) and pointer arithmetic to iterate through the array.

Output:
If you run this program, the output will be:

11 22 33 44 55 66 77

Passing Pointers to Functions

When passing an array to a function, you are actually passing a pointer to the first element of the array. This is due to the array decaying into a pointer in function arguments.

Example 3:

This code demonstrates the usage of pointers and a function that modifies the value it points to.

#include <iostream>
using namespace std;
int fun(int *p)
{
    *p = *p + 1;
    return *p;
}
int main()
{
    int x = 1;
    int *ptr = &x;
    cout << fun(ptr) << endl;
    cout << x << endl;
    cout << fun(&x) << endl;
    cout << x << endl;
    return 0;
}

Key points:

  1. Function fun:
    int fun(int *p): Takes a pointer to an integer as a parameter.
    *p = *p + 1;: Increments the value pointed to by the pointer.
    return *p;: Returns the updated value.
  2. Main Function:
    int x = 1;: Declares and initializes an integer variable x.
    int *ptr = &x;: Declares a pointer ptr and assigns the address of x to it.
    cout << fun(ptr) << endl;: Calls the function fun with the pointer ptr and prints the result. The value of x is now 2.
    cout << x << endl;: Prints the current value of x after the function call. It is now 2.
    cout << fun(&x) << endl;: Calls the function fun with the address of x directly and prints the result.
    The value of x is now 3.cout << x << endl;: Prints the final value of x. It is now 3.

Output:
If you run this program, the output will be:

2
2
3
3

 

Data Structures (struct)

In the world of programming, data structures play a pivotal role in how we organize and manipulate data efficiently. They act as the building blocks that enable us to create well-structured and organized programs. In this explanation, we will delve into one fundamental data structure in C++ known as struct.

What is a Data Structure?

Before we explore struct, let’s define what a data structure is. A data structure is a way of organizing and storing data in a computer’s memory to perform operations on that data more efficiently. It provides a blueprint for the storage and retrieval of information.

Introduction to struct in C++

struct in C++ is a user-defined data type that allows you to group together variables of different data types under a single name. Think of it as creating a custom data type tailored to the specific needs of your program. This makes your code more modular, organized, and easier to understand.

Syntax of struct:

The syntax for defining a struct is straightforward:

struct MyStruct

struct MyStruct

Example 1:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
int main()
{
    car x;
    x.name = "Rolls-Royce";
    x.color = "Red";
    x.model = 2019;
    x.maxSpeed = 270;
    
    cout << x.name << endl;
    return 0;
}

code defines a struct named car that represents information about a car, and it creates an instance of this struct called x to store details about a specific car.

Key points:

  • Struct Definition (car):
    The struct named car has four member variables: name, color, maxSpeed, and model. These variables store information about a car.
  • Instance Creation (x):
    An instance of the car struct named x is created in the main function. This instance can store information about a specific car.
  • Assigning Values:
    Values are assigned to the member variables of the x instance using the dot (.) notation. For example, x.name = “Rolls-Royce” assigns the name “Rolls-Royce” to the name member variable.
  • Printing Information:
    The program prints the name of the car using cout << x.name << endl;. In this case, it will output “Rolls-Royce” to the console.

Output:
If you run this program, the output will be:

Rolls-Royce

Example 2:

Here is another way of initialization the values based on the previous example:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
int main()
{
    car x = {"BMW","Blue",250,2016};
    cout << x.maxSpeed << endl;
    return 0;
}

Output:

250

Example 3:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
int main()
{
    car x = {"BMW","Blue",250,2016};
    car y = x;
    cout << y.name << endl;
    return 0;
}

Instance Creation and Initialization (x and y):

  • An instance of the car struct named x is created with initial values.
  • Another instance named y is created and initialized with the values of x. This is a memberwise copy, and each member of y gets the value of the corresponding member in x.

Example 4:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
}y;
int main()
{
    car x = {"BMW","Blue",250,2016};
    car y = {"Mercedes","Red",300,2016};
    if (x.maxSpeed > y.maxSpeed)
        cout << "car x is faster than car y";
    else
        cout << "car y is faster than car x";
    return 0;
}
  • Global Instance Declaration (y):
    An instance of the car struct named y is declared at the global scope. This means it can be accessed throughout the program.
  • Instance Creation and Initialization (x and Local y):
    – A local instance of the car struct named x is created with initial values.
    – Another local instance named y is created with different values. This y is local to the main function and shadows the global y within this scope.
  • Comparison and Output:
    The program compares the maximum speeds of cars x and y and prints a message indicating which car is faster.

Output:
If you run this program, the output will depend on the values assigned to maxSpeed in x and y. For the provided values, it will output:

car y is faster than car x

Pass ‘struct’ into function:

Example 5:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
void f(car f)
{
    cout << "Name = " << f.name << endl;
    cout << "Color = " << f.color << endl;
}
int main()
{
    car v = {"No name","Red",160,2000};
    f(v);
    return 0;
}

Key points:

  • Function Definition (f):
    The function f takes a car as a parameter and prints information about the car, specifically the name and color.
  • Instance Creation and Initialization (v):
    An instance of the car struct named v is created with initial values.
  • Function Call (f(v)):
    The program calls the function f with the v instance as an argument.

Output:
If you run this program, the output will be:

Name = No name
Color = Red

Example 6:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
};
car read_return(car&s)
{
    cout << "Enter car name:\n";
    cin >> s.name;
    cout << "Enter car color:\n";
    cin >> s.color;
    cout << "Enter car maximum speed:\n";
    cin >> s.maxSpeed;
    cout << "Enter car model:\n";
    cin >> s.model;
    return s;
}
int main()
{
    car v;
    read_return(v);
    car h;
    h = v;
    cout << h.name << endl;
    return 0;
}

Key points:

  • Function Definition (read_return):
    The function read_return takes a car reference as a parameter, reads input to populate its fields, and returns the modified car struct.
  • Function Call (read_return(v)):
    The program calls the function read_return with the v instance as a reference, allowing the function to modify the values of v.
  • Assignment and Printing:
    – The values of v are assigned to h.
    – The program prints the name of h.

Output:
If you run this program and enter values when prompted, the output will depend on the input provided. For example:

Enter car name:
BMW
Enter car color:
Blue
Enter car maximum speed:
250
Enter car model:
2022
BMW

Example 7:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
    void fun(car n)
    {
        cout << n.name << endl;
    }
};

int main()
{
    car v = {"Kia"};
    v.fun(v);
    return 0;
}

Key points:

  • Member Function Definition (fun):
    The member function fun is defined inside the car struct.
    It takes a car as a parameter and prints its name.

Output:
If you run this program, the output will be:

Kia

Example 8:

#include <iostream>
#include <string>
using namespace std;
struct car
{
    string name;
    string color;
    int maxSpeed;
    int model;
    void fun(car n)
    {
        cout << n.name << endl;
    }
};

int main()
{
    car*h;
    car b = {"Toyota","Red",170,2008};
    h = &b;
    cout << h->color << endl;
    return 0;
}

Key points:

  • Pointer Declaration and Initialization (h):
    A pointer to a car named h is declared.
  • Instance Creation and Initialization (b):
    An instance of the car struct named b is created and initialized with specific values.
  • Pointer Assignment (h = &b):
    The address of b is assigned to the pointer h.
  • Pointer Dereferencing (h->color):
    The program prints the color of the car pointed to by h using the arrow operator (->).

Output:
If you run this program, the output will be:

Red

 

String

In C++, a string is a sequence of characters represented using the string class. Unlike C-style strings, which are arrays of characters, C++ strings are dynamic and provide a higher level of abstraction. The string class is part of the C++ Standard Template Library (STL), making it convenient and powerful for handling strings.

Declaring and Initializing Strings:

You can declare a string using the string keyword and initialize it in various ways:

// Declare and initialize strings
string str1 = "Hello, ";  // Initialization using a string literal
string str2("world!");    // Initialization using a constructor

// Concatenate strings
string result = str1 + str2;

When you use a string in C++, you must include its library this way:

#include <string>

Example:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string x = "Ahmad", y;
    y.assign(x);
    cout << "y = " << y << endl;

    return 0;
}

String Assignment:

  • string y;: Declares another string variable y.
  • y.assign(x);: Uses the assign method to copy the contents of string x to string y.

Output:

y = Ahmad

String Methods in C++:

Below is an explanation of various string methods in C++, along with their parameters and examples:

  1. at Method:
    Description: Returns the character at a specified position in the string.
    Parameters: Takes an index as a parameter.
    Example:

    string x = "Ahmad";
    cout << x.at(0) << endl;
    
    // A
  2. length Method:
    Description: Returns the number of characters in the string.
    Parameters: No parameters.
    Example:

     string x = "Ahmad";
     cout << x.length() << endl;
    
     // 5
  3. size Method:
    Description: Same as length, returns the number of characters in the string.
    Parameters: No parameters.
    Example:

    string x = "Ahmad";
    cout << x.size() << endl;
    
    // 5
  4. substr Method:
    Description: Returns a substring of the original string.
    Parameters: Takes starting index and length as parameters.
    Example:

    string x = "Ahmad";
    cout << x.substr(1,3) << endl;
    
    // hma
  5. swap Method:
    Description: Swaps the content of two strings.
    Parameters: Takes another string as a parameter.
    Example:

    string x = "Ahmad", y = "Ali";
    cout << x.swap(y) << endl;
    
    // Swaps the content of x and y
  6. find Method:
    Description: Finds the first occurrence of a substring in the string.
    Parameters: Takes a substring as a parameter.
    Example:

    string x = "Ahmad";
    cout << x.find('a') << endl;
    
    // 3
  7. rfind Method:
    Description: Finds the last occurrence of a substring in the string.
    Parameters: Takes a substring as a parameter.
    Example:

    string x = "Ahmad";
    cout << x.rfind('a') << endl;
    
    // 3
  8. erase Method:
    Description: Erases characters from the string.
    Parameters: Takes starting index and count as parameters.
    Example:

    string x = "Ahmad";
    cout << x.erase(0,3) << endl;
    
    // ad
  9. replace Method:
    Description: Replaces a portion of the string with another string.
    Parameters: Takes starting index, length, and replacement string as parameters.
    Example:

    string x = "Ahmad";
    cout << x.replace(1,4,"li") << endl;
    
    // Ali
  10. insert Method:
    Description: Inserts characters into the string.
    Parameters: Takes starting index and string to insert as parameters.
    Example:

    string x = "Ahmad";
    cout << x.insert(5," Ali") << endl;
    
    // Ahmad Ali

These are some commonly used string methods in C++. Remember to include the <string> header for using these methods.

Introduction

C++ is a cross-platform programming language that can be used to create high-performance applications. It is a general-purpose language, which means it can be used to develop a wide variety of software, including operating systems, games, embedded systems, and more.

C++ is a popular choice for developing high-performance applications because it gives programmers a high level of control over system resources and memory. It is also a very efficient language, which means that C++ programs typically run faster than programs written in other languages.

C++ is a relatively complex language to learn, but it is also a very powerful language. Once you have mastered the basics of C++, you will be able to develop almost any type of software you can imagine.

Why is C++?

C++ is one of the most popular programming languages in the world for a reason. It is a powerful, versatile, and efficient language that can be used to create a wide variety of software.

Here are just a few of the reasons why C++ is so popular:

  • Performance: C++ programs are typically very fast and efficient. This is because C++ gives programmers a high level of control over system resources and memory.
  • Versatility: C++ can be used to develop a wide variety of software, from operating systems to games to embedded systems.
  • Portability: C++ programs can be compiled and run on a variety of platforms, including Windows, macOS, Linux, and more.
  • Community: C++ has a large and active community of developers. This means that there is a wealth of resources available to help you learn and use C++.

Difference between C and C++

C++ was developed as an extension of the C programming language. Both languages have a similar syntax, but C++ adds a number of new features, including:

  • Classes and objects: C++ supports classes and objects, which provide a way to encapsulate data and code into reusable units.
  • Templates: C++ templates allow you to create generic functions and classes that can be used with different data types.
  • Exception handling: C++ provides exception handling features that allow you to deal with errors in a structured way.

Get Started

If you are interested in learning C++, there are a number of resources available to help you get started. There are many good books and tutorials available online, and there are also a number of C++ communities where you can ask for help and advice.

Once you have learned the basics of C++, you can start developing your own applications. There are a number of different C++ compilers and development environments available, so you can choose the one that best suits your needs.

Conclusion

C++ is a powerful and versatile programming language that can be used to create a wide variety of software. It is a popular choice for developing high-performance applications, and it is also a good choice for beginners because it is relatively easy to learn.

FAQs

Supposed to be commonly asked issues, questions & troubleshoot tricks are in this section.

Updating Your Theme

We are strongly recommended to install “Envato Toolkit” plugin for ease of use. Once necessary plugin installed and activated “Envato Toolkit” menu will be available at your admin side.

Important : If you have missing plugins or having issues to install any of them, all the related could be found under “recommended-plugins” folder within the downloaded package.

User Account Information

To obtain your API Key, visit your “My Settings” page on any of the Envato Marketplaces. Once a valid connection has been made any changes to the API key below for this username will not effect the results for 5 minutes because they’re cached in the database. If you have already made an API connection and just purchase a theme and it’s not showing up, wait five minutes and refresh the page. If the theme is still not showing up, it’s possible the author has not made it available for auto install yet.

Marketplace Username: Enter your Envato marketplace username.

Secret API Key: Enter your Envato marketplace Secret API Key (http://themeforest.net/user/[your-username]/api_keys/edit, Login to your Themeforest account, Settings > API Key)

Backup Information

This plugin will automatically save your theme as a ZIP archive before it does an upgrade. The directory those backups get saved to is wp-content/envato-backups. However, if you’re experiencing problems while attempting to upgrade, it’s likely to be a permissions issue and you may want to manually backup your theme before upgrading. Alternatively, if you don’t want to backup your theme you can check the box below.

Skip Theme Backup: Strongly recommended keep unchecked.

Alternative Way

You can also update the theme by replacing the old theme folder. First go to your theme directory then delete the theme folder and paste the new version of the theme.

How to set site’s favicon

Go to Appearance > Customize > Site Identity. Then Select an image as site icon. It’s recommended to use a .ico image as the site icon (favicon).

How to Paginate a Post ?

In order to paginate your blog post, in the Write panel in your WordPress admin, switch to the TEXT view (if you are using the Visual view) and then enter the following code to wherever you want to break the post up into a new page:

<!--nextpage-->

How to change Author Avatar?

The theme uses Gravatar to display users avatars . to create or change your Gravatar :

If you have never setup a Gravatar account:

  1. Register/login to Gravatar. Upon registering, use the SAME email address that is associated with your WordPress User Profile.
  2. Upload your photo and associate it with that specific email address.

 

If you already registered at gravatar.com, follow these steps:

  1. Click on “My Gravatars”.
  2. click on “Add a New Email”.
  3. Then, you’ll need to click on “Add a New Image”.
  4. Upload an image.
  5. Then select the email address, and then select your image from the bottom. Now it’s associated with that email address. Click Save.
  6. It will take about 5-10 minutes to propagate on the internet, and then will appear on site.

Recusandae sapien cursus

Magnis adipisci culpa turpis proin velit, ligula laboris modi nam aut, debitis massa praesentium gravida dicta nam aliquet interdum? Rerum ullamco! Amet veniam repudiandae. Ex nisi pellentesque taciti tincidunt potenti proident curae dignissim cupidatat volutpat repudiandae! Iusto at, eiusmod excepturi. Pulvinar molestias, leo massa? Gravida diam. Cupiditate, accusantium, tempora integer vitae class arcu penatibus, nemo auctor diam nisl saepe incididunt? Egestas. Adipiscing architecto doloremque anim dicta nonummy eaque? Sed a exercitationem pede! Quae egestas lacus. Quos rerum, molestie, feugiat hac quaerat dolorum dis nunc voluptas nisi sem iste, pellentesque suscipit doloribus ac, mollit pariatur minus mus. Etiam sociosqu scelerisque donec.

Debitis felis leo vestibulum architecto? Parturient, corrupti vivamus, elit labore? Vivamus sapiente? Nisl vitae, facilisi suspendisse saepe neque? Voluptas sapien unde debitis quasi sem! Luctus incididunt repellendus, facilis id, ultricies, anim, donec, nemo, nostrum conubia, esse, aenean qui ut voluptatum aliquet diamlorem neque tortor habitant. Eum ridiculus penatibus? Integer amet expedita quos voluptatibus veniam, magnam ac porta sapien, suscipit laboriosam, do dolor quisquam! Iusto, modi. Laboris, ridiculus mi assumenda morbi a vitae vivamus illo aut leo. Maecenas, maecenas integer fames autem temporibus? Ratione recusandae, velit inventore nisl, nascetur at optio, class, quidem lacinia metus felis nibh, ratione tortor numquam rhoncus.

Laudantium taciti pretium esse magnis quis eiusmod! Quis eius eros aspernatur bibendum beatae, mauris do lacus? Ullamcorper quaerat elementum hymenaeos! Alias voluptatem exercitation pharetra, magni, voluptas in hendrerit, ut ratione nascetur, sagittis, eiusmod dignissimos quas. Lacus, accumsan ut culpa fusce, magna consequatur? Primis litora? Voluptas platea aute lacus, aut turpis, congue convallis fringilla platea hic facilisi! Maecenas dolorem nostrum ipsam ducimus massa massa penatibus lobortis consequat, ante commodo ut laborum, pellentesque dis sequi dicta interdum tellus sunt sed. Nemo fringilla, ullamcorper congue voluptatem taciti! Esse cupidatat, iure saepe magnis, at, mus consequatur perferendis potenti maiores accusantium, sagittis ultrices quidem autem.

How to (FAQs)

Harum proident? Volutpat sint. Dicta. Eleifend, distinctio placeat nec commodo asperiores posuere fusce illo, adipiscing leo velit ipsum. Mauris enim itaque penatibus, consectetur fermentum, vel temporibus interdum

Updating Your Theme

We are strongly recommended to install “Envato Toolkit” plugin for ease of use. Once necessary plugin installed and activated “Envato Toolkit” menu will be available at your admin side.

Important : If you have missing plugins or having issues to install any of them, all the related could be found under “recommended-plugins” folder within the downloaded package.

User Account Information

To obtain your API Key, visit your “My Settings” page on any of the Envato Marketplaces. Once a valid connection has been made any changes to the API key below for this username will not effect the results for 5 minutes because they’re cached in the database. If you have already made an API connection and just purchase a theme and it’s not showing up, wait five minutes and refresh the page. If the theme is still not showing up, it’s possible the author has not made it available for auto install yet.

Marketplace Username: Enter your Envato marketplace username.

Secret API Key: Enter your Envato marketplace Secret API Key (http://themeforest.net/user/[your-username]/api_keys/edit, Login to your Themeforest account, Settings > API Key)

Backup Information

This plugin will automatically save your theme as a ZIP archive before it does an upgrade. The directory those backups get saved to is wp-content/envato-backups. However, if you’re experiencing problems while attempting to upgrade, it’s likely to be a permissions issue and you may want to manually backup your theme before upgrading. Alternatively, if you don’t want to backup your theme you can check the box below.

Skip Theme Backup: Strongly recommended keep unchecked.

Alternative Way

You can also update the theme by replacing the old theme folder. First go to your theme directory then delete the theme folder and paste the new version of the theme.

How to set site’s favicon

Go to Appearance > Customize > Site Identity. Then Select an image as site icon. It’s recommended to use a .ico image as the site icon (favicon).

 

How to Paginate a Post ?

In order to paginate your blog post, in the Write panel in your WordPress admin, switch to the TEXT view (if you are using the Visual view) and then enter the following code to wherever you want to break the post up into a new page:

<!--nextpage-->

How to apply custom CSS code.

You can apply your own custom CSS code on Charles theme. Your custom CSS code will not be lost even if you update the theme.

Navigate to Appearance > Customize > Additional CSS

Take a look at the screenshots-

How to set site’s favicon

Go to Appearance > Customize > Site Identity. Then Select an image as site icon. It’s recommended to use a .ico image as the site icon (favicon).

 

Direction Shortcode

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Demo Import

You have to import the demo content successfully if you want your site look exactly like the ‘Aprimo’ demo.

We integrated the One Click Demo installation feature to ‘Aprimo‘ WordPress theme. You can import all demo contents just by a click only.

OneClick Demo Installation Process

  • Install the theme and active it. Then install all required plugins. Make sure all the required plugins are activated.
  • After activating all the required plugins navigate to Appearance > ‘One Click Demo Import’ menu from the WordPress dashboard.

Note: If the Theme Settings data do not import then you have to import it manually. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file. You will find the options.txt in this path- inc/demo{disired-demo-number}/txt

Find your page:

Every demo has 3 pages including the  Default homepage, Gradient homepage, and the Particle background homepage. Navigate to Pages from your WordPress dashboard menu to see all pages. Take a look the below screenshot-
Navigate to Settings > Reading to set your specific page as the front page (homepage).

The recommended method to import the demo content.

If you failed to import the demo content by one click then you have to follow the below steps to import the demo content manually. You will get all demo content data with the theme package. You will find the demos in ‘aprimo>inc/demo{disired-demo-number}’ this path.

  • Navigate to Tools > Import then install the WordPress plugin and click on the ‘Run Importer’. Upload here the ‘contents.xml’ file.
  • Install the Widget Importer & Exporter plugin to import the demo widgets. Then navigate to Tools > Widget Importer & Exporter and upload here the ‘widgets.wie’ file.
  • Now you have to import the Dental Options as like the demo. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

 

Voluptatibus massa tempor

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Language Translations

All of our Themes are able to be translated into any language. The process of translating the theme is a user responsibility. The following instructions are given as guidance.

  1. Open wp-config.php and replace this: define ('WPLANG', ''); with this (substitute the language string (bg_BG) with your own!): define ('WPLANG', 'bg_BG');
  2. Download and install POEDIT
  3. Connect to your site -> open your theme/languages directory
  4. Download the default.pot file and open it with POEDIT.
  5. Translate file and save it as bg_BG (the file name must match with the string you inserted into wp-config.php)
  6. Two files will be generated after save. bg_BG.pot and bg_BG.mo
  7. Upload the .mo and .pot files into wp-content/themes/your-theme/languages folder
Your WordPress installation should be in the language you intend on using the site.

How to set site’s favicon

Go to Appearance > Customize > Site Identity. Then Select an image as site icon. It’s recommended to use a .ico image as the site icon (favicon).

Language Translations

All of our Themes are able to be translated into any language. The process of translating the theme is a user responsibility. The following instructions are given as guidance.

  1. Open wp-config.php and replace this: define ('WPLANG', ''); with this (substitute the language string (bg_BG) with your own!): define ('WPLANG', 'bg_BG');
  2. Download and install POEDIT
  3. Connect to your site -> open your theme/languages directory
  4. Download the default.pot file and open it with POEDIT.
  5. Translate file and save it as bg_BG (the file name must match with the string you inserted into wp-config.php)
  6. Two files will be generated after save. bg_BG.pot and bg_BG.mo
  7. Upload the .mo and .pot files into wp-content/themes/your-theme/languages folder
Your WordPress installation should be in the language you intend on using the site.

How to (FAQs)

Supposed to be commonly asked issues & questions and troubleshoot tricks are in this section.

Updating Your Theme

We are strongly recommended to install “Envato Toolkit” plugin for ease of use. Once necessary plugin installed and activated “Envato Toolkit” menu will be available at your admin side.

Important : If you have missing plugins or having issues to install any of them, all the related could be found under “recommended-plugins” folder within the downloaded package.

User Account Information

To obtain your API Key, visit your “My Settings” page on any of the Envato Marketplaces. Once a valid connection has been made any changes to the API key below for this username will not effect the results for 5 minutes because they’re cached in the database. If you have already made an API connection and just purchase a theme and it’s not showing up, wait five minutes and refresh the page. If the theme is still not showing up, it’s possible the author has not made it available for auto install yet.

Marketplace Username: Enter your Envato marketplace username.

Secret API Key: Enter your Envato marketplace Secret API Key (http://themeforest.net/user/[your-username]/api_keys/edit, Login to your Themeforest account, Settings > API Key)

Backup Information

This plugin will automatically save your theme as a ZIP archive before it does an upgrade. The directory those backups get saved to is wp-content/envato-backups. However, if you’re experiencing problems while attempting to upgrade, it’s likely to be a permissions issue and you may want to manually backup your theme before upgrading. Alternatively, if you don’t want to backup your theme you can check the box below.

Skip Theme Backup: Strongly recommended keep unchecked.

Alternative Way

You can also update the theme by replacing the old theme folder. First go to your theme directory then delete the theme folder and paste the new version of the theme.

How to set site’s favicon

Go to Appearance > Customize > Site Identity. Then Select an image as site icon. It’s recommended to use a .ico image as the site icon (favicon).

 

How to apply custom CSS code.

You can apply your own custom CSS code on Gullu theme. Your custom CSS code will not be lost even if you update the theme.

Navigate to Appearance > Customize > Additional CSS

Take a look at the screenshots-

How to change the transition time of Gullu slider.

You can change the slide transition time of Gullu slider manually. Here are the manual steps-
– Open the file named theme.js from gullu\assets\js directory with your favorite text editor.
– Then navigate to the line number 51 and change the default time value with your own time duration.
Note: This is a custom task by yourself and does this process at your own risk.

Doc title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

How to set site’s favicon

Go to Appearance > Customize > Site Identity. Then Select an image as site icon. It’s recommended to use a .ico image as the site icon (favicon).

 

Example doc title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

How to change Author Avatar?

The theme uses Gravatar to display users avatars . to create or change your Gravatar :

If you have never setup a Gravatar account:

  1. Register/login to Gravatar. Upon registering, use the SAME email address that is associated with your WordPress User Profile.
  2. Upload your photo and associate it with that specific email address.

If you already registered at gravatar.com, follow these steps:

  1. Click on “My Gravatars”.
  2. click on “Add a New Email”.
  3. Then, you’ll need to click on “Add a New Image”.
  4. Upload an image.
  5. Then select the email address, and then select your image from the bottom. Now it’s associated with that email address. Click Save.
  6. It will take about 5-10 minutes to propagate on the internet, and then will appear on site.

Required Plugins

After installing the theme you most have to install the ‘Gullu Core’, ‘Visual composer’ and ‘Codestar Framework’ plugins to import the demo content as well and work the theme correctly.

You will find all required and recommended plugins at Appearance > Install Plugins.

Tips / Guide

Deleniti rerum magni hic, lobortis a mattis quibusdam pellentesque iusto posuere ornare distinctio nostrud penatibus nonummy, facilisi molestiae, accumsan ac ridiculus? Facere quisquam reprehenderit! Morbi laboriosam minim? Asperiores illo tincidunt velit irure, culpa nihil commodo earum, feugiat magni. Aperiam ipsum, ex labore sunt condimentum orci! Potenti harum cupidatat, fugit ab?

Optimize Images

Optimizing your images will helps your WordPress site load faster.

Download and activate WP Smush.it This plugin will optimize every image you upload and you can use the Bulk Smush.it feature to smush all of your uploaded images.

Alternatives to WP Smush.it include EWWW Image Optimizer, CW Image Optimizer, Imsanity and Hammy. Many WordPress users prefer using these plugins as they do not rely on an external server to process your images.

Language Translations

All of our Themes are able to be translated into any language. The process of translating the theme is a user responsibility. The following instructions are given as guidance.

  1. Open wp-config.php and replace this: define ('WPLANG', ''); with this (substitute the language string (bg_BG) with your own!): define ('WPLANG', 'bg_BG');
  2. Download and install POEDIT
  3. Connect to your site -> open your theme/languages directory
  4. Download the default.pot file and open it with POEDIT.
  5. Translate file and save it as bg_BG (the file name must match with the string you inserted into wp-config.php)
  6. Two files will be generated after save. bg_BG.pot and bg_BG.mo
  7. Upload the .mo and .pot files into wp-content/themes/your-theme/languages folder
Your WordPress installation should be in the language you intend on using the site.

How to Paginate a Post ?

In order to paginate your blog post, in the Write panel in your WordPress admin, switch to the TEXT view (if you are using the Visual view) and then enter the following code to wherever you want to break the post up into a new page:

<!--nextpage-->

How to change Author Avatar?

The theme uses Gravatar to display users avatars . to create or change your Gravatar :

If you have never setup a Gravatar account:

  1. Register/login to Gravatar. Upon registering, use the SAME email address that is associated with your WordPress User Profile.
  2. Upload your photo and associate it with that specific email address.

 

If you already registered at gravatar.com, follow these steps:

  1. Click on “My Gravatars”.
  2. click on “Add a New Email”.
  3. Then, you’ll need to click on “Add a New Image”.
  4. Upload an image.
  5. Then select the email address, and then select your image from the bottom. Now it’s associated with that email address. Click Save.
  6. It will take about 5-10 minutes to propagate on the internet, and then will appear on site.

else

The else statement in C++ is used to provide an alternate block of code to be executed if the condition of an if statement is false.

The general syntax of an else statement is as follows:

if (condition) {
  // code to execute if the condition is true
} else {
  // code to execute if the condition is false
}

For example, the following code uses an else statement to print a different message depending on whether the number variable is positive or negative:

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    cin >> x;
    if (x > 0)
        cout << "This number is positive" << endl;
    else
        cout << "This number is negative" << endl;


    return 0;
}

Output should be one of the previous statements depending on the entered number. if the number is positive like 5, the output will be “This number is positive” and vice versa.

The else statement is a powerful tool for controlling the flow of your program. By using else statements, you can write more complex and efficient code.

Here are some general rules for using the if else statement:

  • The else statement must be used in conjunction with an if statement.
  • The else statement can be used to provide an alternate block of code to be executed if the condition of the if statement is false.
  • You can use nested if else statements to create more complex conditional statements:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int x = 0;
        cin >> x;
        if (x % 2 == 0)
            if (x > 50)
                cout << "it's Ok" << endl;
            else
                cout << "it's not Ok" << endl;
        else
            cout << "Odd" << endl;
    
    
        return 0;
    }
    

By understanding how to use the if else statement, you can write more efficient and reliable C++ code.

Reprehenderit bibendum

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Labore scelerisque, ornare?

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

While Loop

The while loop in C++ is a control statement that allows you to execute a block of code repeatedly while a condition is true. The general syntax of a while loop is as follows:

while (condition) {
  // code to execute while the condition is true
}

The condition can be any Boolean expression. The while loop evaluates the condition and if it is true, the code block inside the while loop is executed. The code block inside the while loop is executed repeatedly until the condition evaluates to false.

Here is an example of a while loop:

#include <iostream>

using namespace std;

int main()
{
    while (true)
    {
        cout << " a word" <<endl;
    }
    
    return 0;
}

The previous code is a simple infinite loop in C++. It will print the phrase “a word” to the console forever, or until the program is terminated.

The while (true) statement creates an infinite loop. This means that the code block inside the loop will be executed forever, or until the program is terminated.

The cout << " a word" << endl; statement prints the phrase “a word” to the console. The endl; object at the end of the line inserts a newline character, which causes the next line of output to be printed on a new line.

Here is a step-by-step explanation of what happens when you run this code:

  1. The compiler evaluates the condition of the while statement. Since the condition is always true, the code block inside the loop is executed.
  2. The compiler prints the phrase “a word” to the console.
  3. The compiler goes back to step 1 and repeats the process.

This process continues forever, or until the program is terminated.

To terminate the program, you can press Ctrl+C on your keyboard.

Here are some things to keep in mind about infinite loops:

  • Infinite loops can be useful for certain tasks, such as polling for input or waiting for a certain event to occur.
  • However, it is important to use infinite loops carefully, as they can also cause your program to crash if you are not careful.
  • For example, if you accidentally create an infinite loop that prints output to the console, your console window will quickly fill up with output and your program will become unresponsive.

To overcome these problems we should make 3 steps:

  1. declare a variable and initializes it to any value we want.
  2. add a condition to while statement.
  3. set a counter for our variable.

These steps are shown in the following example:

#include <iostream>

using namespace std;

int main()
{
    int c = 0;
    while (c < 5)
    {
        cout << " a word" <<endl;
        c++;
    }
    
    return 0;
}

int c = 0;, declares an integer variable named c and initializes it to the value 0.

The while (c < 5) statement creates a loop that will iterate as long as the value of the c variable is less than 5.

The cout << " a word" << endl; statement prints the phrase “a word” to the console. The endl; object at the end of the line inserts a newline character, which causes the next line of output to be printed on a new line.

The c++; statement increments the value of the c variable by 1.

Here is a step-by-step explanation of what happens when you run this code:

  1. The compiler declares the c variable and initializes it to the value 0.
  2. The compiler evaluates the condition of the while statement. Since the condition is true, the code block inside the loop is executed.
  3. The compiler prints the phrase “a word” to the console.
  4. The compiler increments the value of the c variable by 1.
  5. The compiler goes back to step 2 and repeats the process.

This process continues until the value of the c variable is equal to 5. At that point, the condition of the while statement will evaluate to false and the loop will terminate.

Here is the output of this program:

a word
a word
a word
a word
a word

Here is another example:

#include <iostream>

using namespace std;

int main()
{
    int c = 0, num = 0, sum = 0;
    while (c < 4)
    {
        cout << "Enter a number: ";
        cin >> num;
        sum = sum + num;
        c++;
    }
    cout << " sum = " << sum << endl;
    return 0;
}

This code is a simple C++ program that prompts the user to enter four numbers and then prints the sum of those numbers to the console.

Here is a step-by-step explanation of what happens when you run this code:

  1. The compiler declares the cnum, and sum variables and initializes them to the values 0, 0, and 0, respectively.
  2. The while (c < 4) statement creates a loop that will iterate as long as the value of the c variable is less than 4.
  3. The cout << "Enter a number: "; statement prints the message “Enter a number: ” to the console.
  4. The cin >> num; statement reads a number from the user and stores it in the num variable.
  5. The sum = sum + num; statement increments the value of the sum variable by the value of the num variable.
  6. The c++; statement increments the value of the c variable by 1.
  7. The compiler goes back to step 2 and repeats the process.

This process continues until the value of the c variable is equal to 4. At that point, the condition of the while statement will evaluate to false and the loop will terminate.

After the loop has terminated, the program prints the message ” sum = ” to the console, followed by the value of the sum variable.

Here is an example of the output of this program:

Enter a number: 10
Enter a number: 20
Enter a number: 30
Enter a number: 40
 sum = 100

While loops are a powerful tool for controlling the flow of your C++ program. By understanding how to use them, you can write more efficient and reliable code.

Here are some tips for using while loops:

  • Make sure that the condition of the while loop will eventually evaluate to false. Otherwise, the while loop will run forever.
  • Use a break statement to exit the while loop early.
  • Use a continue statement to skip the rest of the current iteration of the while loop.

Rogan Documentation

Spot of come to ever hand as lady meet on. Delicate contempt received two yet advanced. Gentleman as belonging he commanded believing dejection in by.

Getting Started

Before building your site, better take a look at this section.

Theme Installation

Extract the zipped package downloaded from ThemeForest to your desktop, in the extracted package you will find the aprimo.zip file which is the WordPress theme.

You can install the theme in two ways:

FTP: Extract aprimo.zip file and upload the extracted folder to /wp-content/themes/ folder on your server.

WordPress: Navigate to Appearance -> Add New Themes -> Upload page. Select aprimo.zip file. Press the Install Now button to upload and install the theme.

After uploading the theme, you have to activate it. Navigate to Appearance -> Themes page to activate the theme.

Contact Page

You can create and configure the Contact page by following the below steps-

Creating the Contact page

Navigate from your WordPress dashboard to Pages > Add New. Then Select the page template as “Contact Page” and click on the Publish button to create the Contact page.

Configuring the Contact page

Go to Theme Settings > Contact Page Settings from your WordPress dashboard to configure the Contact page settings. Here you will get everything you need to change the Contact page template.

Demo Import

You have to import the demo content successfully if you want your site look exactly like the ‘Aprimo’ demo.

We integrated the One Click Demo installation feature to ‘Aprimo‘ WordPress theme. You can import all demo contents just by a click only.

OneClick Demo Installation Process

  • Install the theme and active it. Then install all required plugins. Make sure all the required plugins are activated.
  • After activating all the required plugins navigate to Appearance > ‘One Click Demo Import’ menu from the WordPress dashboard.

Note: If the Theme Settings data do not import then you have to import it manually. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file. You will find the options.txt in this path- inc/demo{disired-demo-number}/txt

Find your page:

Every demo has 3 pages including the  Default homepage, Gradient homepage, and the Particle background homepage. Navigate to Pages from your WordPress dashboard menu to see all pages. Take a look the below screenshot-
Navigate to Settings > Reading to set your specific page as the front page (homepage).

The recommended method to import the demo content.

If you failed to import the demo content by one click then you have to follow the below steps to import the demo content manually. You will get all demo content data with the theme package. You will find the demos in ‘aprimo>inc/demo{disired-demo-number}’ this path.

  • Navigate to Tools > Import then install the WordPress plugin and click on the ‘Run Importer’. Upload here the ‘contents.xml’ file.
  • Install the Widget Importer & Exporter plugin to import the demo widgets. Then navigate to Tools > Widget Importer & Exporter and upload here the ‘widgets.wie’ file.
  • Now you have to import the Dental Options as like the demo. Navigate to ‘Theme Settings > Backup’. Then copy-paste the backup string here and click on the Import a Backup button. You will find the backup string in the options.txt file.

 

Required plugins

After installing the theme you most have to install the ‘Faster Core’, ‘Visual composer’ and ‘Codestar Framework’ plugins to import the demo content as well and work the theme correctly.

You will find all required and recommended plugins at there Appearance > Install Plugins.

FAQs

Supposed to be commonly asked issues, questions & troubleshoot tricks are in this section.

Updating Your Theme

We are strongly recommended to install “Envato Toolkit” plugin for ease of use. Once necessary plugin installed and activated “Envato Toolkit” menu will be available at your admin side.

Important : If you have missing plugins or having issues to install any of them, all the related could be found under “recommended-plugins” folder within the downloaded package.

User Account Information

To obtain your API Key, visit your “My Settings” page on any of the Envato Marketplaces. Once a valid connection has been made any changes to the API key below for this username will not effect the results for 5 minutes because they’re cached in the database. If you have already made an API connection and just purchase a theme and it’s not showing up, wait five minutes and refresh the page. If the theme is still not showing up, it’s possible the author has not made it available for auto install yet.

Marketplace Username: Enter your Envato marketplace username.

Secret API Key: Enter your Envato marketplace Secret API Key (http://themeforest.net/user/[your-username]/api_keys/edit, Login to your Themeforest account, Settings > API Key)

Backup Information

This plugin will automatically save your theme as a ZIP archive before it does an upgrade. The directory those backups get saved to is wp-content/envato-backups. However, if you’re experiencing problems while attempting to upgrade, it’s likely to be a permissions issue and you may want to manually backup your theme before upgrading. Alternatively, if you don’t want to backup your theme you can check the box below.

Skip Theme Backup: Strongly recommended keep unchecked.

Alternative Way

You can also update the theme by replacing the old theme folder. First go to your theme directory then delete the theme folder and paste the new version of the theme.

How to set site’s favicon

Go to Appearance > Customize > Site Identity. Then Select an image as site icon. It’s recommended to use a .ico image as the site icon (favicon).

How to Paginate a Post ?

In order to paginate your blog post, in the Write panel in your WordPress admin, switch to the TEXT view (if you are using the Visual view) and then enter the following code to wherever you want to break the post up into a new page:

<!--nextpage-->

How to change Author Avatar?

The theme uses Gravatar to display users avatars . to create or change your Gravatar :

If you have never setup a Gravatar account:

  1. Register/login to Gravatar. Upon registering, use the SAME email address that is associated with your WordPress User Profile.
  2. Upload your photo and associate it with that specific email address.

 

If you already registered at gravatar.com, follow these steps:

  1. Click on “My Gravatars”.
  2. click on “Add a New Email”.
  3. Then, you’ll need to click on “Add a New Image”.
  4. Upload an image.
  5. Then select the email address, and then select your image from the bottom. Now it’s associated with that email address. Click Save.
  6. It will take about 5-10 minutes to propagate on the internet, and then will appear on site.

Tips / Guide

Quos vesti bulum dictum irure recusandae, aliquet, ullam quod fugit, dictumst, optio, parturient auctor pulvinar, inceptos sem. Habitasse! Mattis, litora ipsum, fringilla elementum.

Optimize Images

Optimizing your images will helps your WordPress site load faster.

Download and activate WP Smush.it This plugin will optimize every image you upload and you can use the Bulk Smush.it feature to smush all of your uploaded images.

Alternatives to WP Smush.it include EWWW Image OptimizerCW Image OptimizerImsanity and Hammy. Many WordPress users prefer using these plugins as they do not rely on an external server to process your images.

Language Translations

All of our Themes are able to be translated into any language. The process of translating the theme is a user responsibility. The following instructions are given as guidance.

  1. Open wp-config.php and replace this: define ('WPLANG', ''); with this (substitute the language string (bg_BG) with your own!): define ('WPLANG', 'bg_BG');
  2. Download and install POEDIT
  3. Connect to your site -> open your theme/languages directory
  4. Download the default.pot file and open it with POEDIT.
  5. Translate file and save it as bg_BG (the file name must match with the string you inserted into wp-config.php)
  6. Two files will be generated after save. bg_BG.pot and bg_BG.mo
  7. Upload the .mo and .pot files into wp-content/themes/your-theme/languages folder
Your WordPress installation should be in the language you intend on using the site.

How to change Author Avatar?

The theme uses Gravatar to display users avatars . to create or change your Gravatar :

If you have never setup a Gravatar account:

  1. Register/login to Gravatar. Upon registering, use the SAME email address that is associated with your WordPress User Profile.
  2. Upload your photo and associate it with that specific email address.

If you already registered at gravatar.com, follow these steps:

  1. Click on “My Gravatars”.
  2. click on “Add a New Email”.
  3. Then, you’ll need to click on “Add a New Image”.
  4. Upload an image.
  5. Then select the email address, and then select your image from the bottom. Now it’s associated with that email address. Click Save.
  6. It will take about 5-10 minutes to propagate on the internet, and then will appear on site.

How to change Author Avatar?

The theme uses Gravatar to display users avatars . to create or change your Gravatar :

If you have never setup a Gravatar account:

  1. Register/login to Gravatar. Upon registering, use the SAME email address that is associated with your WordPress User Profile.
  2. Upload your photo and associate it with that specific email address.

 

If you already registered at gravatar.com, follow these steps:

  1. Click on “My Gravatars”.
  2. click on “Add a New Email”.
  3. Then, you’ll need to click on “Add a New Image”.
  4. Upload an image.
  5. Then select the email address, and then select your image from the bottom. Now it’s associated with that email address. Click Save.
  6. It will take about 5-10 minutes to propagate on the internet, and then will appear on site.

Theme Settings

You can control the theme’s functionality and customize theme’s content from the Theme Settings page. Here you will find all relevant settings to customize the theme.

This section will provide you an in-depth guide on how to use the Theme Options. To access the Theme Settings page, go to- Dashboard > Theme Settings. You will find this page at the top of the Appearance menu.

Header Settings

In the Header settings section, you will get a lot of header customization options. In this section, you can change the logo and change the page/post’s Title bar padding, Page margin-top, Title bar overlay color etc.

Reprehenderit bibendum

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Iusto molestie distinctio

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Shortcodes

This section will introduce you how to use the Faster‘s shortcodes.

Those are our custom shortcodes developed and integrated with the Visual Composer (VC) plugin. So you can use our shortcodes with Visual Composer drag and drop interface.

You will find all VC integrated shortcodes to VC Add Element popup box’s “Faster” tab.

You can build a specific Faster design element with those shortcodes.

You must have to install the required plugins “Faster Core”, “CodeStar Framework” and “Visual Composer” to use all shortcodes as well. All shortcode elements will appear in Visual composer’s shortcode elements popup box (Faster Tab). Take a look at the above screenshot to see all shortcodes.

Note: You can import a demo and check to see how a shortcode working and displaying.

Sample Doc Title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Direction Shortcode

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Dignissimos deleniti recusandae

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Lorem ipsum title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Visual Composer

Visual Composer is a unique plugin, it will help you manage your content on a WordPress site and create stunning layouts in few minutes without coding. Nowadays many websites have complex grid layouts with columns, tabs, sliders and etc. In the past, to create that type of layouts you should be HTML guru or Shortcodes operator ninja.

You will get the Visual Composer plugin with our theme as pre-packaged. You can install it from “Appearance > Install Plugins”.

Here is the documentation with video tutorial Visual Composer Doc

Doc title example

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Doc title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Doc list title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

This is a example title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Changes Log

—– 1.1 (26 april 2018) ——
Added: One click demo importer
New: Sticky menu
Fixed: Particle background in hero section
Improved: Some shortcode options

Getting Started

What is C++?

C++ is a general-purpose programming language that is used to create a wide range of applications, including operating systems, games, embedded systems, and web applications. C++ is known for its speed, efficiency, and flexibility.

Getting started with C++

To get started with C++, you will need to install a C++ compiler and IDE. A compiler is a program that converts C++ code into machine code that can be executed by a computer. An IDE is an integrated development environment that provides a variety of tools for writing, editing, compiling, and debugging C++ code.

Installing a C++ compiler and IDE

There are many different C++ compilers and IDEs available. For this tutorial, we will use Visual Studio for C++. Visual Studio is a free and powerful IDE that provides comprehensive support for C++ development.

To install Visual Studio for C++, visit the Visual Studio website and download the latest version.

Writing your first C++ program

Once you have installed Visual Studio for C++, you can start writing your first C++ program. To do this, create a new project and select the “C++ Console App” template.

Once you have created a new project, you can start writing C++ code in the main source file. The main source file is typically named main.cpp.

Here is a simple example of a C++ program:

C++
#include <iostream>
int main() {
  std::cout << "Hello, world!" << std::endl;
  return 0;
}

This program prints the message “Hello, world!” to the console.

Once you have written your C++ program, you can compile and run it by pressing F5.

Learning more about C++

Now that you have written your first C++ program, you can start learning more about the language. There are many resources available online and in libraries.

Here are a few tips for learning C++:

  • Start with the basics. Learn about variables, data types, operators, functions, and control flow statements.
  • Find a good tutorial or book. There are many resources available that can teach you the basics of C++.
  • Practice regularly. The best way to learn C++ is by writing code. Try to write simple programs at first, and gradually work your way up to more complex programs.
  • Use an IDE. An IDE can make it easier to write, edit, compile, and debug C++ code.

Conclusion

Getting started with C++ can be daunting, but it is also rewarding. C++ is a powerful and versatile language that can be used to create a wide range of applications.

By following the tips in this guide, you can start learning C++ today and start creating your own applications.

Required Plugins

After installing the theme you most have to install the ‘Charles Core’, ‘Elementor’ and ‘Piklist’ plugins to import the demo content as well and work the theme correctly.

You will find all required and recommended plugins at Appearance > Install Plugins.

Reiciendis tristique dui

Felis nam purus. Lobortis, recusandae id penatibus gravida aspernatur, quos! Mollis aliquam do tincidunt occaecati blandit diam quis! Fames aperiam cursus ipsum? Sapiente deserunt, ipsum rerum posuere diam eum voluptates. Potenti! Sunt quae habitasse, blandit felis! Erat taciti magni fames quasi porttitor euismod dolorem, lobortis, officia. Ducimus blanditiis class praesentium, in et. Dis expedita luctus justo pellentesque? Excepteur pharetra nec, vulputate ex ipsam tincidunt, magnis quos iusto varius commodi fuga tenetur leo! Occaecat cursus aute, aute nisl nemo, velit odit leo delectus nostra cillum, iure maiores voluptatibus blanditiis, leo ea inventore excepteur, porro vitae, architecto arcu, ultrices augue incididunt et.

Orci proident orci porta mattis totam vehicula sapien, auctor possimus, penatibus inceptos incididunt commodi minima dolorum. Turpis aperiam sollicitudin platea quae vehicula, error. Mollitia! Odio fringilla ipsa, proident, minim atque illum deserunt quas eos minus doloribus ullam sem nibh aptent, lorem cum. Quae temporibus convallis. Eu distinctio metus! Lacus elit inventore, curae. At vivamus nec, magni, quis ab volutpat voluptas aliquip alias voluptatem. Sem veniam beatae. Ac rutrum placeat dis, rem perferendis. Cubilia eligendi distinctio? Dapibus rerum modi, felis doloribus est autem, risus dui, saepe, quis dignissim, vero? Beatae mollitia, nobis, provident! Dapibus, dolorem, mattis tristique, iusto libero, dui, quisquam.

Lorem parturient felis sodales sagittis veniam dapibus suspendisse. Fuga arcu officiis debitis ipsa maiores, sem, adipisci, dis architecto, habitant, minus? Irure sit aenean cras, fringilla! Placeat, mi labore! Et vehicula morbi dictumst ad, massa quos sequi, quidem habitant aperiam tempora, habitasse morbi, mi ex nostrum, platea numquam netus. Magnam eum donec, pellentesque ducimus ullam? Earum tempus? Inventore felis quia ea tempore, egestas, ipsam, unde dui eum? Sit voluptates, soluta iure, sapiente incididunt integer ultricies ante, porta adipisci? Dolores aliquet aliquam. Ex habitasse dapibus sagittis curae convallis occaecati hac proident eros? Assumenda in? Aliqua sed, assumenda eget, assumenda doloribus autem consectetuer.

OOP in C++

Object-Oriented Programming (OOP) is an acronym that stands for the following concepts:

In procedural programming, the emphasis lies in writing procedures or functions designed to perform operations on data. In contrast, object-oriented programming revolves around the creation of objects that encapsulate both data and functions.

Object-oriented programming offers numerous advantages over procedural programming:

  1. OOP execution is typically faster and more straightforward.
  2. OOP provides a well-defined structure for organizing programs.
  3. OOP promotes the “Don’t Repeat Yourself” (DRY) principle in C++, reducing code duplication and enhancing code maintainability, modification, and debugging.
  4. OOP facilitates the development of highly reusable applications with reduced code volume and shorter development timelines.

As a helpful tip, adhering to the “Don’t Repeat Yourself” (DRY) principle involves identifying and extracting common code segments within an application, centralizing them for reuse rather than duplicating them throughout the codebase.

Review Function

The Structure of C++ program

#include <iostream>
using namespace std;

int main()
{
    cout << "Welcome to OOP in C++" << endl;

    return 0;
}

Let’s break down the structure and purpose of each command line in the provided C++ code:

#include <iostream>

Structure: This line begins with the #include preprocessor directive, followed by the <iostream> header file enclosed in angle brackets.

Purpose: This line includes the Input/Output Stream Library (iostream), which is essential for performing input and output operations in C++. It provides functionalities like cin for input and cout for output.

using namespace std;

Structure: The using namespace std; line declares that the code will be using the std namespace.

Purpose: The std namespace contains the standard C++ library components, including the cout and endl used in the code. By including this line, you can use these components without explicitly specifying the namespace each time you use them.

int main()
{

Structure: This line marks the beginning of the main function, which is the entry point of every C++ program.

Purpose: The main function is where the program execution starts. It is required in every C++ program, and the code within the curly braces {} defines the body of the main function.

cout << "Welcome to OOP in C++" << endl;

Structure: This line uses the cout object to output the text “Welcome to OOP in C++” to the console. The << operator is used for streaming the text to the output.

Purpose: This line is responsible for displaying a welcome message on the console, indicating that the program is focused on Object-Oriented Programming (OOP) in C++.

    return 0;
}

Structure: The return 0; line signifies the end of the main function. The 0 is returned to the operating system, indicating that the program executed successfully.

Purpose: The return 0; line is a common way to indicate a successful termination of the program. The value 0 is typically returned to the operating system to signify that the program executed without errors.

Libraries in C++

In C++, a library is a collection of pre-compiled functions, classes, and procedures that can be used by a program. These libraries provide a set of functionalities that can be utilized to perform common tasks, ranging from basic input/output operations to complex mathematical computations. Libraries offer a way to modularize code, promote code reuse, and streamline development by providing ready-made solutions for various tasks.

Here are some key aspects of libraries in C++:

  1. Standard Template Library (STL):
    The C++ Standard Library, often referred to as the Standard Template Library (STL), is a core part of C++. It includes a wide range of generic algorithms (e.g., sorting, searching) and data structures (e.g., vectors, lists, maps) that are implemented using templates. The STL simplifies programming by providing efficient and generic solutions to common problems.
  2. Header Files:
    C++ libraries are typically distributed as header files (with the extension .h or .hpp) and implementation files (with the extension .cpp). Header files contain declarations of functions, classes, and other entities that can be used in your program, while the implementation files contain the actual code.
  3. IOStream Library:
    The iostream library is a fundamental part of the C++ Standard Library and provides functionality for input and output operations. It includes cin (for input) and cout (for output), among other stream classes. Here’s an example of using the iostream library:

    #include <iostream>
    
    int main() {
        std::cout << "Hello, C++!" << std::endl;
        return 0;
    }
    
  4. Math Library:
    The cmath library provides a set of mathematical functions, such as trigonometric, logarithmic, and exponential functions.
  5. User-Defined Libraries:
    Apart from the standard libraries, you can create your own libraries to encapsulate and organize your code. This involves creating header files that declare the functions and classes, and implementation files that define their behavior. You can then include your custom library in other C++ programs.

Function in C++

In the realm of programming, functions play a pivotal role in organizing code, enhancing reusability, and promoting a structured approach to problem-solving. In C++, a function is a self-contained unit of code designed to perform a specific task or achieve a particular objective. It encapsulates a set of instructions, allowing you to break down a complex program into smaller, more manageable pieces.

Key Concepts
1. Modularity:
Functions enable the decomposition of a program into smaller, more manageable modules. Each function handles a specific aspect of the overall functionality, promoting a modular and organized code structure.

2. Reusability:
Once a function is defined, it can be reused in different parts of the program or even in other programs. This promotes the “Don’t Repeat Yourself” (DRY) principle, saving both time and effort.

3. Abstraction:
Functions provide a level of abstraction, allowing you to focus on high-level functionality without getting bogged down by the implementation details. This abstraction enhances code readability and simplifies the debugging process.

4. Parameters and Return Values:
Functions can accept input parameters and return values, allowing for dynamic and interactive code. Parameters provide a way to pass information into a function, while return values allow functions to communicate results back to the calling code.

Basic Syntax
A typical C++ function follows this basic syntax:

returnType functionName(parameterType1 parameterName1, parameterType2 parameterName2, ...) {
    // Function body: Code to perform the desired task
    // Optionally, a return statement to provide a result back to the caller
}

Let’s break down the components:

returnType: Specifies the type of data the function will return (if any).
functionName: The unique identifier for the function.
parameters: Input values that the function receives.
functionBody: The set of instructions defining the function’s behavior.

Example:

#include <iostream>
using namespace std;
int sum(int x, int y)
{
    return x + y;
}

int main()
{
    cout << sum(10,20) << endl;
    return 0;
}

This C++ code is a simple program that calculates and displays the sum of two numbers.

  • Define a Sum Function:
int sum(int x, int y)
{
    return x + y;
}

This block of code creates a function called sum. It takes in two numbers (x and y) and gives back their sum.

  • Use the Sum Function in the Main Part:
int main()
{
    cout << sum(10, 20) << endl;
    return 0;
}

Here, the main part is like the director of the program. It says, “Hey, calculate the sum of 10 and 20 using the sum function, and show me the result on the screen.” The endl is like pressing Enter on the keyboard; it moves to the next line.

  • Run the Program:

When you run this program, it does the calculation (10 + 20) inside the sum function, then displays the result (30) on the screen. The return 0; part tells the computer that everything went well.

 

Review Arrays

Classes

Constructors

Unordered list items

The HTML  element represents an unordered list of items, typically rendered as a bulleted list. An unordered list starts with the <ul> tag. Each list item starts with the <li> tag. The list items will be marked with bullets (small black circles) by default:

  • List Item [direction] Docly Settings > Header > Logo [/direction]
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

The HTML  element represents an ordered list of items — typically rendered as a numbered list. An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list items will be marked with numbers by default:

  1. List Item [direction] Docly Settings > Header > Logo [/direction]
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Required plugins

After installing the theme you most have to install the ‘Faster Core’, ‘Visual composer’ and ‘Codestar Framework’ plugins to import the demo content as well and work the theme correctly.

You will find all required and recommended plugins at there Appearance > Install Plugins.

Dignissimos deleniti recusandae

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Page Building

Create a new page

  1. On the top left side of the WordPress dashboard, click Pages > Add New
  2. Click Edit with Elementor to enter Elementor Page Builder.


The website editing screen is located on the right side. This is your workspace, where you can add sections and templates.

The panel is located on the left side of the screen and contains creative tools called widgets, that allow you to add elements to your page.

Some of the most commonly used widgets include Button, Image, text, and more.

To find a specific widget, use the search field.

Sample doc title

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to Docly SettingsHeader Logo
  • Consectetur adipiscing elit
  • Integer molestie lorem at massa
  • Facilisis in pretium nisl aliquet

Ordered List Items

  1. Go to Docly SettingsHeader Logo
  2. Consectetur adipiscing elit
  3. Integer molestie lorem at massa
  4. Facilisis in pretium nisl aliquet

Sample doc title issues

What is an Extension?

For editing menu navigation settings go to  Theme Options Header Top of Header . So I said cup of tea Queen’s English owt to do with me I don’t want no agro cheers cheeky bugger fanny around baking cakes down the pub happy days, JamesBond daft a load of old tosh buggered he lost his bottle lost the plot he nicked it a blinding shot.

[docly_tooltip id=”1″]Tooltip text[/docly_tooltip] mufty quaint no biggie cras baking cakes barney bamboozled, what a plonker bum bag he legged it young delinquent knees up Eaton the full monty arse over tit, my lady buggered happy days amongst bugger all mate are you taking the piss brolly. [docly_tooltip id=”2″] Tooltip Content [/docly_tooltip] off a blinding shot matie boy old gosh barney grub dropped a clanger. And for styling menus go to  Theme Options Header Top of Header Menu Styles of this Row

Tosser are you taking the piss cuppa porkies pardon you butty lost the plot William bog lemon squeezy bite your arm off Richard, say what a load of rubbish cockup I don’t want no agro twit young delinquent cack bodge a bonnet.

Unordered list items

  • Go to