Program Reverse a String using Stack in C++

Problem: Given a String, reverse the given string using stack. 

Input: str = "algolesson"
Output: str = "nosselogla"

Input: str = "orange"
Output: str = "egnaro"

Steps to reverse the string using stack.
  • Create one empty Stack.
  • Push all the characters of the given string one by one into the stack.
  • Create a new empty string.
  • Add the top character of the stack to the empty string then pop the top character.  
  • Repeat the fourth step until the stack gets empty and you will get the reverse of the given string.
Gif for Reverse string using stack

Example: C++ Code to reverse a string using stack.

//C++ Program to reverse String using Stack
#include <iostream>
#include <stack>
using namespace std;

int main()
{
    string str = "orange";
    stack<char> sc;
    string s = "";
    //push all the char to the stack
    for (int i = 0; i < str.size(); i++)
    {
        sc.push(str[i]);
    }
    //pop all the char from the stack
    // and add then to new empty string.
    while (!sc.empty())
    {
        s += sc.top();
        sc.pop();
    }
    cout << "Reverser String " << s << endl;
}

Output:
Reverser String egnaro
  • Time Complexity: O(n)
  • Space Complexity: O(n)
As you can see that we are using extra space to reverse the given string which means that this is not an efficient algorithm because we solve the same problem without using any extra space and without using a stack. 

Example: C++ Code to reverse a string without using extra space and without using stack.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str = "orange";

    //size of the given string
    int n = str.size();
    
    for (int i = 0; i < n / 2; i++)
    {
        swap(str[i], str[n - 1 - i]);
    }
    cout << "Reverse String " << str << endl;
}

Output:
Reverse String egnaro

Time Complexity: O(n).
Space Complexity: O(1)

Binary Search Algorithm with code in C++.

Binary Search is one the most popular and widely used search algorithms used to search whether a particular element is present in the given sorted array or not. It is much better than the Linear search algorithm because it is much faster.  

Problem: Given a sorted array of integers arr[ ] of size n and a target element x, write a C++ program to search the position of x in the given array.

Input: arr[ ] = {7, 10, 11, 15, 20, 30, 26}   x = 20

Output: 4
x is present at index 4.

Input: arr[ ] = {11, 15, 22, 30, 35, 43, 60, 75, 120}   x = 65

Output: -1
x is not present in the arr[ ].

Binary Search Explanation. 

When you try to find the target element in the given array, the worst-case scenario is that when you have to check each element of the given array and it leads to O(n) time complexity. But when the array elements are arranged in sorted order, you can use this extra information to reduce the time complexity to O(log n)

  • If you use a binary search on 100 elements to find your target, the worst-case scenario would be 10 searches. Can you imagine a huge performance improvement? ðŸ˜²

You get this huge performance improvement because, for each iteration, you reduce the number of elements you will be looking at in half. The idea is to compare the target element to the middle element of the array. 

  • If you find the target element is equal to the middle element, return the position of the middle element and stop.
  • If the target element is smaller than the middle element, continue searching on the left side of the middle element. high = mid-1
  • If the target element is greater than the middle element, continue searching on the right side of the middle element. low = mid+1
  • Repeat all three steps until you find the matching element else return -1.
Binary Search Gif

Example: C++ code for Binary Search Algorithm.

#include <iostream>
using namespace std;

int binarySearch(int arr[], int n, int key)
{ 
    int low = 0, high = n - 1; 

    while (low <= high)
    {
        int mid = low + (high - low) / 2;
        //target is found
        if (arr[mid] == key)
        {
            return mid;
        }
        else if (arr[mid] < key) //target might be present in right half
        {
            low = mid + 1;
        }
        else    //target might be present in left half
        {
            high = mid - 1;
        }
    }
    return -1;
}

int main()
{

    int arr[] = {7, 10, 11, 15, 20, 30, 36};
    // size of given array
    int size = sizeof(arr) / sizeof(arr[0]);
    // target element to be find
    int x = 20;

    int index = binarySearch(arr, size, x);
    if (index == -1)
    {
        cout << "Value is not present in the given array." << endl;
    }
    else
    {
        cout << "Value present at index: " << index << endl;
    }
}

Output:
Value present at index: 4
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
Important points to note: 

int low = 0, high = n - 1;

low and high work like a boundary and we will be looking at elements inside the boundary to find out the target element x and these boundaries get change with each iteration until we found our target loop gets terminated when low == high.

int mid = (high + low) / 2; //formula 1 
int mid = low + (high - low) / 2; //formula 2

Now, a few of you might be thinking that why we are using formula 2 instead of formula 1 as both the formula is going to give the same result? The answer to this question is to avoid integer overflow as the maximum value the integer datatype can hold is 2147483647.  So when you in case of adding two bigger numbers and try to store them in integer datatype it will give you a wrong answer. 


I believe the remaining part of the code was easy to understand with the help of the above explanation and animation gif. If you have any questions or suggestions related to the post, you can share them with us in the comment section below.

Linear Search Algorithm with code in C++.

Linear Search is a searching algorithm that is also known as a sequential search. It is one of the very popular searching algorithms that is used to search whether an element is present in the given array or not. 

Problem: Given an array of integers arr[ ] of size n and a target element x, write a C++ program to search the position of x in the given array. You can return -1 in the element x is not present in the given array. 

Input arr[ ] = {20, 10, 7, 30, 11, 15, 36} 
x = 11

Output:  4
Element is present at index 4

Input arr[ ] = {5, 10, 8, 30, 12, 70, 25, 19}
x = 15

Output: -1 
Element is not present at any index.

Linear Search working

Steps to follow:

  • Start from the 0 index element of the given array and start comparing each element with x.
  • If you find an index element matches with x, return the index. arr[index]  == x
  • If you are unable to find the matching element in the array, return -1.

Example: C++ Program for Linear search.

#include <iostream>
using namespace std;

// Function for Linear Search
int linearSearch(int arr[], int n, int x)
{
    int i;
    for (i = 0; i < n; i++)
    {
        if (arr[i] == x)
        {
            return i;
        }
    }
    return -1;
}
int main()
{
    // Elements present in the array
    int arr[] = {20, 10, 7, 30, 11, 15, 36};
    // size of given array
    int size = sizeof(arr) / sizeof(arr[0]);
    // Element x to be search in the array
    int x = 11;
    int pos = linearSearch(arr, size, x);
    if (pos == -1)
    {
        cout << "Element " << x << " is not present in the given array." << endl;
    }
    else
    {
        cout << "Element " << x << " is present at index " << pos << endl;
    }
}

Output:

Element 11 is present at index 4
  • Time Complexity: O(n).
  • Space Complexity: O(1).
Mostly in real-life applications, we rarely use a Linear search algorithm. We mostly use a Binary search algorithm with time complexity O(log n) which is more efficient than this linear search.

How To Enable Auto Format On Save in VS Code?

Whenever we write some code in our Visual Studio Code, we have to spend our precious time formatting the code for better readability and understanding. Any code with poor formatting is hard to understand and debug. Proper positioning of curly brackets and indentation is very important because it helps us to understand which part of the code is ending where.

It is okay to format a few lines of code manually but imagine if we are writing 1000 lines of code and we are spending a lot of our time in formating them correctly. But many Visual Studio Code users don't know about the auto-formatting feature that is available in VS Code. 

Today we are going to save a lot of your precious time by letting you know how you can enable this feature on VS Code. 

Step 1: Open your Visual Studio Code and click on the Settings icon from the lower-left corner and then select Settings.

Enable auto format code

Step 2: Now, inside the User section, select Text Editors and expand this section. You can see a setting option name "Formatting" select that option.

step 2 of Auto Formatting Code in VS Code

Step 3: Inside Formatting, select the check box with the name "Format On Save" and that's it. 

Step 3 of Auto Formatting Code in VS Code

Now you will observe that whenever you write and piece of code and click on Save, your code will automatically get formatted. Now you just enjoy writing beautiful code without worrying about formatting them. 

ASP.NET Core Tutorial

In this course of ASP.NET Core, we will cover all the basic, intermediate, and advanced ASP.NET core concepts that help you build data-driven web applications by the end of this course you will be able to perform all the CRUD operations that are Create, Read, Update and Delete using Sequal server as our database. 

The topics which we are going to cover in detail are-

  • ASP.NET Core.
  • ASP.NET Core MVC.
  • ASP.NET Core Identity.
  • Entity Framework Core.

What is ASP.NET Core?

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, Internet-connected applications. ASP.NET Core is a redesign of ASP.NET 4.x and earlier it was named ASP.NET 5 and later is renamed ASP.NET Core.

Few benefits and features of ASP.NET Core.

Cross-Platform: ASP.NET Core applications can be developed and run across different platforms like Windows, macOS, Linux. ASP.NET Core applications can be hosted on IIS, Apache, Docker, and even Self-host in your own process.

Because of One Unified Programming Model for MVC and Web API, both the MVC Controller class and the ASP.NET Web API Controller class inherit from the same Controller base class and returns IActionResult.

ASP.NET Core has great build-in support for Dependency Injection which is a very great feature to learn.

ASP.NET Core Testability feature makes unit testing easy for developers.

It is an Open Source technology so it is continuously growing and improving with the support of developers from the open-source community.

Modular: ASP.NET Core provides modularity with Middleware Components. Both the request and response pipelines are composed using the middleware components. A rich set of built-in middleware components are provided out of the box. Custom Middleware Components can also be created.

Middleware - Is a piece of software that can handle HTTP request or response

Prerequisites for this course:

  • Basic understanding of HTML, CSS, and C#.
  • Prior MVC knowledge is helpful but not required. 

ASP.NET Core Project File.

.csproj or .vbproj depending on the programming language used.
No need to unload the project to edit the project file.
File or Folder references are no longer included in the project file.
The File System determines what files and folders belong to the project.

TargetFramework.
Specifies the target framework for the application.
To specify a target framework we used Target Framework Moniker (TFM)

AspNetCoreHostingModel.
Specifies how the application should be hosted.
InProcess or OutofProcess.
InProcess hosts the app inside of the IIS working process (w3wp.exe)
OutProcess hosting model forward web requests to a backend ASP.NET Core app running the Kestrel server. The default is OutofProcess hosting.

PackageReference.
Used to Include a reference to the NuGet package that is installed for the application.
Merapackage - Microsoft.AspNetCore.App
A metapackage has no content of its own. It just contains a list of dependencies (other packages).
When the version is not specified, an implicit version is specified by the SDK. Rely on the implicit version rather than explicitly setting the version number on the package reference. 

Main method in ASP.NET Core.
A Console application usually has a Main() method.
Why do we have a Main() method in ASP.NET Core Web Application?
ASP.NET Core application initially starts as a Console application.
This Main() method configures ASP.NET Core and starts it and at that point it becomes an ASP.NET Core web application.


The Main() method called "CreateWebHostBuilder" and we are passing the command line argument to it. We can notice that "
CreateWebHostBuilder" return "IWebHostBuilder" and "Build()" is called on that which build the webhost on which ASP.NET Core Application and on this we add "Run()" and start listening the incoming Http request.

We are also configuring the "Startup" class using the extension method named ".UseStartup"
Going to the definition of "Startup" class we find two important method "ConfigureService" configure the service required for our application and "Configure" configure our application request processing pipeline 

Some of the Tasks that CreateDefaultBuilder() performs.
Setting up the web server. Loading the host and application configuration from various configuration sources and Configuring logging.

An ASP.NET Core application can be hosted.
  • InProcess or 
  • OutofProcess.

ASP.NET Core InProcess Hosting.

To configure InProcess hosting.
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>

CreateDefaultBuilder() method calls UseIIS() method and host the app inside of the IIS worker process (w3wp.exe or iisexpress.exe)

InProcess hosting delivers significantly higher request throughput than OutOfProcess hosting 

To get the process name executing the app.
System.Diagnostics.Process.GetCurrentProcess().ProcessName

With out-of-process hosting.
2 Web Servers - Internal and External Web Server.
The internal web server is Kestrel.
The external web server can be IIS, Nginx, or Apache.

What is Kestrel?
Cross-Platform Web Server for ASP.NET Core.
Kestrel can be used, by itself as an edge server.
The process used to host the app is dotnet.exe.


Dependency Injection in ASP.NET Core.

What is Dependency Injection?
Dependency Injection (DI) is the technique to achieve IOC (Inversion of Control). Inversion of Control means we need to make our code loosely coupled so in the future if there are any changes then there should not be any tight coupling between any two classes of object.


This is the basic structure of our project when we are not using Dependency Injection and we are using some service(class) inside one or more Controller then we create an object of the service using the "new" keyword and suppose in the future if we make any changes like changing the name of the service then we have to make those changes inside all Controllers. This is an example of tightly coupling.


Now let's understand what happens when we work with Dependency Injection, suppose I have only one service so to work with dependency injection I need to create one interface of my service. Now I will not work directly with the service I will use an interface to create this field and to store the object of this particular service. Now if we are making any changes in service then we don't have to make any changes in the control which is using it.

Now one important question that may come to our mind that where I will create the instance of the service and how the application will come to know that this interface is resolved by using this particular class. ???

In the concept of dependency injection, we generally create a container, and inside that container, we define some settings. 

How to configure Dependency Injection in ASP.NET Core?


ASP.NET Core provides the built-in support for DI. Dependencies are registered in containers and the container in ASP.NET core is IServiceProvider. Services are typically registered in the application's Startup.ConfigureService method.

Service Lifetime.
Service can be registered with following lifetimes-
  • Transient (AddTransient<>) - A  new instance of the service will be created every time it is requested.
  • Scoped (AddScoped<>) - These are created once per client request. For each HTTP request
  • Singleton (AddSingleton<>) - Same instance for the application.

Structure Query Language (SQL) | RDBMS

There are many DBMSs present in the market. Do we have to learn all the languages to manipulate the data? The answer to this question is NO! We don't have to learn all the languages. We have a common language named SQL (Structure Query Language). RDBMS also uses SQL to access the database. Users use many applications and those applications use SQL to interact with DBMS to manipulate the data. 
 
Structure Query Language

What is SQL (Structured Query Language)?

SQL is an ANSI (American National Standard Institute) standard computer language for accessing and manipulating database systems. SQL statements are used to retrieve and update the data in the database. They are not case-sensitive in nature. 

Some key points to write better SQL queries:
  • Use pascal notation for object name. Example: Products, Customers
  • Use the singular form of nouns for the Column name. Example: FirstName, Address
  • Each table must have a primary key. 
  • Use upper case for all SQL keywords. Example: SELECT, UPDATE, INSERT, DELETE
  • Do not use white space in identifiers.
  • Use parentheses to increase readability.
  • Indent code to improve readability.
  • Use ANSI joins instead of old-style joins.
  • Do not use SELECT *
  • Always use table aliases when your SQL statement involves more than one table.
  • Do not use column numbers in the ORDER BY clause.
  • Always use column list in INSERT statements.
These key points might be confusing for you because we have not started learning how to write SQL queries access and insert data in our database. But before moving to that, it is important for us to understand components of SQL

Components of SQL.

SQL is divided into four different components. Let us understand each of them one by one:

DDL (Data Definition Language).
Data Definition Language deals with the structure of Database objects and commands are CREATE, ALERT, TRUNCATE, DROP.
  • CREATE: used to create new Database objects like table, view, and stored procedure.
  • ALERT: used to modify the existing structure of the database objects.
  • TRUNCATE: used to remove all the data from database objects.
  • DROP: used to remove the database object from the database.
  • RENAME: used to change the name of the existing object.

DML (Data Manipulation Language).
Data Manipulation Language deals with the manipulation of the data in the Database objects and the commands are SELECT, INSERT, UPDATE.
  • INSERT: used to insert data into a table.
  • UPDATE: used to update existing data within a table.
  • DELETE: used to delete records from the table.

TCL (Transaction Control Language).
Transaction Control Language deals with transaction management and the commands are COMMIT, ROLLBACK.
  • COMMIT: used to end the current transaction by making all pending data changes permanent. 
  • ROLLBACK: used to ends the current transaction by discarding all pending data changes.
  • SAVEPOINT: used to mark a savepoint within the current transaction.

DCL (Data Control Language).
Data Control Language deals with providing access privilege of the data by using command GRANT, REVOKE.
  • GRANT: used to give user access privilege to the database.
  • REVOKE: used to revert back the user access privilege to the database.
DQL (Data Query Language).
DQL command is used to perform quarries to fetch the data from the database within the schema object. We can use the DQL command with JOIN to get the data from multiple tables at one time using Primary key and Foreign key relations. Example: SELECT

So these are the few important components of SQL and in our further articles, we are going to learn the syntax of all the SQL commands with their practical examples. 

Relational Data Model and Its Properties.

In a relational data model, the data is stored in the form of tables with rows and columns. There are a few important terminologies that we all should know before moving forward with the relational data model. 

Let's look at the terminologies used in Relational Data Model:
  • Relation refers to the table and Cardinality refers to the number of rows in the table.
  • Tuples refer to the row of the table.
  • Attributes refer to the column of the table.
  • Degree refers to the number of columns in the table.
  • Domain refers to the range of values that can be stored for an attribute.
Relational Data Model Terminologies

Now the most important thing to understand in Relational Data Model is how we are going to establish a relationship between one table with one or more other tables? The two keys which play a very important role in building a relationship are the primary key and the foreign key. Let us understand these two important terms in more detail.

To build a relation of one table with another table, the table must contain one column which contains a unique key for each row of the table called the primary key. This primary key column must be present in another table as a foreign key column. We can use different kinds of JOIN operations to get the data from more than one table. 
The primary key column cannot hold null values and there should be only one primary key column in each table. 
The foreign key column may contain null values and there can be more than one foreign key column in a single table.(alert-passed)
Primary Key Foreign Key

There are a few important properties of the Relational Data Model that we should kind in mind before we start working with the Relational Database.

  • No duplicate Tuples are allowed.
  • Tuples are unordered.
  • Attributes are unordered.
  • Attributes values are atomic.

Relational Database Management System.

A Relational Database Management System is system software that lets us Create, Update and Administer a Relational Database. RDBMS uses SQL (Structured Query Language) to access the database. The few best examples of RDBMS are Oracle, DB2, MYSQL, etc. 

We will learn more about RDBMS and SQL in our next article. You can add your valuable feedback in the comment section below.

RDBMS Introduction | RDBMS Tutorial

RDBMS Intro

RDBMS stands for Relational Database Management System. It is a system that is used by software to store, manage, query, or retrieve data from the database in which data is stored in the form of tables and one table might be connected with many other tables using primary and foreign key relations. RDBMS provides us the interface between software and database to manage and perform the required operations on the database. Before starting with RDBMS concepts, it is important to understand a few important terms.

What is Information System?

Data with its meaning is referred to as information, where the data means raw fact. In specific, an information system is an organized collection of hardware, software, supplies, and procedures and people who store, process and provide access to information.

What is File Based System?

When information is stored in flat files, which are maintained by the file system under the operating system control. Application programs go through the file system in order to access these flat files. Records consist of various fields, which are delimited by a space, comma, pipe, or any special character, etc.

Maintaining records in a File based system is great and we are able to free up all that space by moving all the data on the computer.(alert-success) 

There are many disadvantages of using the traditional file-based system like:

  • The application develops in an ad-hoc manner.
  • Data redundancy, because data can be duplicated in two or more files.
  • Data isolation, which means all the related data are scattered in various files having a different file format, and hence, writing a new application becomes difficult in retrieving data.
  • In File Based System it is difficult to produce reports across sales, product, and customer data because they are maintained on a separate file system. (alert-error)

What is Database?

A database is a shared collection of logically related data and the description of this data, designed to meet the needs of an organization. 

Advantages of Database Approach:

  • Centralization of Information Management.
  • Data is shared by different groups of users and application programs.
  • Representation of complex relationship between data.
  • Integrity Constraint handling.
  • Advanced facility for backup and recovery.

What is Database Management System?

Database Management System (DBMS) is software that helps in defining, creating, and maintaining the database that provides controlled access to the database.

Advantages of Database Management System:

  • Shared file system.
  • Enforcement of Security. 
  • Enforcement of development and maintaining standards.
  • Reduction of redundancy.
  • Avoidance of inconsistency across files.
  • Maintenance of integrity.
  • Data Independence. 
  • Authentication- Whether the right user has the right to access the database.
  • Authorization- Whether the right user has the right to access the database.
DBMS System

We can categorize database users as follows:

Application programmers or Ordinary users: Developer who writes application programs to interact with the database. Application programs can be written in many programming languages like C++, JAVA, C#, or any high-level programming language. Such a program access the database by issuing the appropriate request like SQL statement to DBMS.

Sophisticated users: Users who interact with the system by forming their requests in a database query language. Each such query is submitted to a query processor whose function is to break down the DML statement into instructions that the storage management understands.

End Users: Users who interact with the system by invoking one of the permanent application programs that have been written previously. 
 
DBA(Database Administer): User who manages the database like installation of DB, managing user and DB performance. 

Data Model.

A Data Model is a way of explaining the logical layout of the data and the relationship of various parts to each other on the whole. Different types of Data Models are:
  • Hierarchical models refer to storing the data by a tree structure. This model handles only parent-child relationships which are one-to-many relationships. It is not easy to perform, insert, update and delete operations in this model.
  • In-Network models data is represented as a graph which Nodes and Edges. It addresses many to many relationships. It has a very complex design.
  • Relational Data Model is a widely used data model. The data is stored in the form of tables with rows and columns and it is easy to use because there is no usage of a pointer. Data access is faster than other models. This data model uses the relational algebra concept. 
So this was the basic introduction of database and its type and why do we need a Relational Database Management System. You can add more value to this post by giving your valuable feedback in the comment section below.

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by templateszoo