You are reading the article Data Types In R With Example updated in December 2023 on the website Hatcungthantuong.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Data Types In R With Example
In this tutorial, you will learn:
What are the Data Types in R?
Following are the Data Types or Data Structures in R Programming:
Scalars
Vectors (numerical, character, logical)
Matrices
Data frames
Lists
Basics types
4.5 is a decimal value called numerics.
4 is a natural value called integers. Integers are also numerics.
TRUE or FALSE is a Boolean value called logical binary operators in R.
The value inside ” ” or ‘ ‘ are text (string). They are called characters.
We can check the type of a variable with the class function
Example 1: # Declare variables of different types # Numeric x < 28 class(x)Output:
## [1] "numeric" Example 2: # String y < "R is Fantastic" class(y)Output:
## [1] "character" Example 3: # Boolean z < TRUE class(z)Output:
## [1] "logical" VariablesVariables are one of the basic data types in R that store values and are an important component in R programming, especially for a data scientist. A variable in R data types can store a number, an object, a statistical result, vector, dataset, a model prediction basically anything R outputs. We can use that variable later simply by calling the name of the variable.
To declare variable data structures in R, we need to assign a variable name. The name should not have space. We can use _ to connect to words.
To add a value to the variable in data types in R programming, use < or =.
Here is the syntax:
# First way to declare a variable: use the `<` name_of_variable < value # Second way to declare a variable: use the `=` name_of_variable = valueIn the command line, we can write the following codes to see what happens:
Example 1: # Print variable x x < 42 xOutput:
## [1] 42 Example 2: y < 10 yOutput:
## [1] 10 Example 3: # We call x and y and apply a subtraction xyOutput:
## [1] 32 VectorsA vector is a onedimensional array. We can create a vector with all the basic R data types we learnt before. The simplest way to build vector data structures in R, is to use the c command.
Example 1: # Numerical vec_num < c(1, 10, 49) vec_numOutput:
## [1] 1 10 49 Example 2: # Character vec_chr < c("a", "b", "c") vec_chrOutput:
## [1] "a" "b" "c" Example 3: # Boolean vec_bool < c(TRUE, FALSE, TRUE) vec_boolOutput:
##[1] TRUE FALSE TRUEWe can do arithmetic calculations on vector binary operators in R.
Example 4: # Create the vectors vect_1 < c(1, 3, 5) vect_2 < c(2, 4, 6) # Take the sum of A_vector and B_vector sum_vect < vect_1 + vect_2 # Print out total_vector sum_vectOutput:
[1] 3 7 11 Example 5:In R, it is possible to slice a vector. In some occasion, we are interested in only the first five rows of a vector. We can use the [1:5] command to extract the value 1 to 5.
# Slice the first five rows of the vector slice_vector < c(1,2,3,4,5,6,7,8,9,10) slice_vector[1:5]Output:
## [1] 1 2 3 4 5 Example 6:The shortest way to create a range of values is to use the: between two numbers. For instance, from the above example, we can write c(1:10) to create a vector of value from one to ten.
# Faster way to create adjacent values c(1:10)Output:
## [1] 1 2 3 4 5 6 7 8 9 10 R Arithmetic OperatorsWe will first see the basic arithmetic operators in R data types. Following are the arithmetic and boolean operators in R programming which stand for:
Operator Description
+ Addition
– Subtraction
* Multiplication
/ Division
^ or ** Exponentiation
Example 1: # An addition 3 + 4Output:
## [1] 7You can easily copy and paste the above R code into Rstudio Console. The output is displayed after the character #. For instance, we write the code print(‘Guru99’) the output will be ##[1] Guru99.
The ## means we print output and the number in the square bracket ([1]) is the number of the display
Example 2: # A multiplication 3*5Output:
## [1] 15 Example 3: # A division (5+5)/2Output:
## [1] 5 Example 4: # Exponentiation 2^5Output:
Example 5: ## [1] 32 # Modulo 28%%6Output:
## [1] 4 R Logical OperatorsWith logical operators, we want to return values inside the vector based on logical conditions. Following is a detailed list of logical operators of data types in R programming
Logical Operators in R
The logical statements in R are wrapped inside the []. We can add as many conditional statements as we like but we need to include them in a parenthesis. We can follow this structure to create a conditional statement:
variable_name[(conditional_statement)] Example 1: # Create a vector from 1 to 10 logical_vector < c(1:10)Output:
## [1]FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE Example 2:In the example below, we want to extract the values that only meet the condition ‘is strictly superior to five’. For that, we can wrap the condition inside a square bracket precede by the vector containing the values.
# Print value strictly above 5Output:
## [1] 6 7 8 9 10 Example 3: # Print 5 and 6 logical_vector < c(1:10)Output:
## [1] 5 6You're reading Data Types In R With Example
What Is Data Analysis? Research, Types & Example
What is Data Analysis?
Data analysis is defined as a process of cleaning, transforming, and modeling data to discover useful information for business decisionmaking. The purpose of Data Analysis is to extract useful information from data and taking the decision based upon the data analysis.
A simple example of Data analysis is whenever we take any decision in our daytoday life is by thinking about what happened last time or what will happen by choosing that particular decision. This is nothing but analyzing our past or future and making decisions based on it. For that, we gather memories of our past or dreams of our future. So that is nothing but data analysis. Now same thing analyst does for business purposes, is called Data Analysis.
In this Data Science Tutorial, you will learn:
Why Data Analysis?To grow your business even to grow in your life, sometimes all you need to do is Analysis!
If your business is not growing, then you have to look back and acknowledge your mistakes and make a plan again without repeating those mistakes. And even if your business is growing, then you have to look forward to making the business to grow more. All you need to do is analyze your business data and business processes.
Data Analysis ToolsData Analysis Tools
Data analysis tools make it easier for users to process and manipulate data, analyze the relationships and correlations between data sets, and it also helps to identify patterns and trends for interpretation. Here is a complete list of
Types of Data Analysis: Techniques and MethodsThere are several types of Data Analysis techniques that exist based on business and technology. However, the major Data Analysis methods are:
Text Analysis
Statistical Analysis
Diagnostic Analysis
Predictive Analysis
Prescriptive Analysis
Text AnalysisData analysis tools make it easier for users to process and manipulate data, analyze the relationships and correlations between data sets, and it also helps to identify patterns and trends for interpretation. Here is a complete list of tools used for data analysis in research.
Text Analysis is also referred to as Data Mining. It is one of the methods of data analysis to discover a pattern in large data sets using databases or data mining tools. It used to transform raw data into business information. Business Intelligence tools are present in the market which is used to take strategic business decisions. Overall it offers a way to extract and examine data and deriving patterns and finally interpretation of the data.
Statistical AnalysisStatistical Analysis shows “What happen?” by using past data in the form of dashboards. Statistical Analysis includes collection, Analysis, interpretation, presentation, and modeling of data. It analyses a set of data or a sample of data. There are two categories of this type of Analysis – Descriptive Analysis and Inferential Analysis.
Descriptive Analysisanalyses complete data or a sample of summarized numerical data. It shows mean and deviation for continuous data whereas percentage and frequency for categorical data.
Inferential Analysis Diagnostic AnalysisDiagnostic Analysis shows “Why did it happen?” by finding the cause from the insight found in Statistical Analysis. This Analysis is useful to identify behavior patterns of data. If a new problem arrives in your business process, then you can look into this Analysis to find similar patterns of that problem. And it may have chances to use similar prescriptions for the new problems.
Predictive AnalysisPredictive Analysis shows “what is likely to happen” by using previous data. The simplest data analysis example is like if last year I bought two dresses based on my savings and if this year my salary is increasing double then I can buy four dresses. But of course it’s not easy like this because you have to think about other circumstances like chances of prices of clothes is increased this year or maybe instead of dresses you want to buy a new bike, or you need to buy a house!
So here, this Analysis makes predictions about future outcomes based on current or past data. Forecasting is just an estimate. Its accuracy is based on how much detailed information you have and how much you dig in it.
Prescriptive AnalysisPrescriptive Analysis combines the insight from all previous Analysis to determine which action to take in a current problem or decision. Most datadriven companies are utilizing Prescriptive Analysis because predictive and descriptive Analysis are not enough to improve data performance. Based on current situations and problems, they analyze the data and make decisions.
Data Analysis ProcessThe Data Analysis Process is nothing but gathering information by using a proper application or tool which allows you to explore the data and find a pattern in it. Based on that information and data, you can make decisions, or you can get ultimate conclusions.
Data Analysis consists of the following phases:
Data Requirement Gathering
Data Collection
Data Cleaning
Data Analysis
Data Interpretation
Data Visualization
Data Requirement GatheringFirst of all, you have to think about why do you want to do this data analysis? All you need to find out the purpose or aim of doing the Analysis of data. You have to decide which type of data analysis you wanted to do! In this phase, you have to decide what to analyze and how to measure it, you have to understand why you are investigating and what measures you have to use to do this Analysis.
Data CollectionAfter requirement gathering, you will get a clear idea about what things you have to measure and what should be your findings. Now it’s time to collect your data based on requirements. Once you collect your data, remember that the collected data must be processed or organized for Analysis. As you collected data from various sources, you must have to keep a log with a collection date and source of the data.
Data CleaningNow whatever data is collected may not be useful or irrelevant to your aim of Analysis, hence it should be cleaned. The data which is collected may contain duplicate records, white spaces or errors. The data should be cleaned and error free. This phase must be done before Analysis because based on data cleaning, your output of Analysis will be closer to your expected outcome.
Data AnalysisOnce the data is collected, cleaned, and processed, it is ready for Analysis. As you manipulate data, you may find you have the exact information you need, or you might need to collect more data. During this phase, you can use data analysis tools and software which will help you to understand, interpret, and derive conclusions based on the requirements.
Data Interpretation Data VisualizationData visualization is very common in your day to day life; they often appear in the form of charts and graphs. In other words, data shown graphically so that it will be easier for the human brain to understand and process it. Data visualization often used to discover unknown facts and trends. By observing relationships and comparing datasets, you can find a way to find out meaningful information.
Summary:
Data analysis means a process of cleaning, transforming and modeling data to discover useful information for business decisionmaking
Types of Data Analysis are Text, Statistical, Diagnostic, Predictive, Prescriptive Analysis
Data Analysis consists of Data Requirement Gathering, Data Collection, Data Cleaning, Data Analysis, Data Interpretation, Data Visualization
Scalable Data Processing In R
Most of the time, the R programmers encounter large data that causes problems as by default variables are stored in the memory. The R language doesn’t work well with a huge amount of data larger than 10% of the computer’s RAM. But data processing should be scalable if we want to excel in the field of data science. So, we will discuss how we can apply certain operations and use scalable data processing easily when the data is sufficiently larger than the computer’s RAM. The discussion would also be focussed on dealing with “out of core” objects.
What is Scalable data processing?Scalability is a very important aspect when big data comes into the picture. As we know, it takes more time to read and write data into a disk than to read and write data into RAM. Because of this, it takes a lot of time when we need to retrieve some data from a hard disk as compared to RAM. The computer’s resources like RAM, processors, and hard drives play a major role in deciding how fast our R code executes. As we know that we cannot change such resources (except replacing them with new hardware) but we can make use of these resources in an efficient way.
For example, let us consider that we have a dataset that is equal to the size of the RAM. The cost could be cut by loading only the part of the dataset that we actually require at the moment.
Relationship between processing time and the data sizeThe processing time depends upon the size of the dataset. The larger dataset generally takes a longer time to process. But it is important to note that the processing time is not directly proportional to the size of the dataset.
Let us understand in simple words by taking an example. Suppose we have two datasets out of which one is twice the size of the other. So, the time taken to process the larger dataset is not twice the time taken to process the other dataset.
The processing time for the larger dataset would obviously be more than the smaller one but we cannot clearly say that it would be twice the smaller one or three times etc. It totally depends upon the operations being performed on the dataset elements.
R provides us a microbenchmark package that can be used to compare the timing of two or more operations. We can also plot the difference using plot() function in R.
ExampleFor example, consider the following program that sorts random arrays of different sizes −
#
Load
the microbenchmarkpackage
library
(
microbenchmark)
#Time
comparison between sorting vectors of # different sizes microbenchmarkObject<

microbenchmark
(
#Sort
a random normal vector length5e5
"5e5"
=
sort
(
rnorm
(
5e5
)
)
,
#Sort
a random normal vector length4e5
"4e5"
=
sort
(
rnorm
(
4e5
)
)
,
#Sort
a random normal vector length3e5
"3e5"
=
sort
(
rnorm
(
3e5
)
)
,
#Sort
a random normal vector length2e5
"2e5"
=
sort
(
rnorm
(
2e5
)
)
,
#Sort
a random normal vector length1e6
"1e6"
=
sort
(
rnorm
(
1e6
)
)
,
times=
15
)
#Plot
the resulting benchmark objectplot
(
microbenchmarkObject)
As you can see in the output, the execution time does not come out to be the same every time. The reason for this is that while the system is executing the R code, other things are also going under the hood.
Note that it is also a good practice to keep the track of the operations using the microbenchmark library while evaluating the execution time of R code.
Working with “out of core” ObjectsIn this section, we will discuss the big.matrix object. The big.matrix comprises an object in R that does more or less the same as the data structure in C++. This object seems like a generic R matrix but prevents developers from memoryconsuming problems of a generic R matrix.
Now we will create our own big.matrix object using the read.big.matrix() function.
The function is also quite similar to read.table() but it requires us to specify the type of value we want to read i.e, “char”, “short”, “integer”, “double”. The name of the file must be given to hold the matrix’s data (the backing file), and it needs the name of the file to hold information about the matrix (a descriptor file). The outcome will be stored in a file on the disk that keeps the value read with a descriptor file that keeps more description about the resulting big.matrix object.
Installing bigmemory libraryBefore moving further, we need to install the “bigmemory” library. You can download this library using the following command in CRAN −
install.packages("bigmemory") Importing bigmemoryThe first step is to import the bigmemory library. Import the library using the following command −
library(bigmemory) Downloading the FileNow download a sample csv file “mortgagesample.csv” −
# Download file using URL Creating big.matrix objectWe will now create an object of big.matrix. For this purpose, the argument passed is going to be “mortgagesample.desc”. The dimension of the object can be extracted using dim() function −
Example#
Create
an object of object<

read.
big.
matrix
(
"mortgagesample.csv"
,
header=
TRUE,
type=
"integer"
,
descriptorfile=
"mortgagesample.desc"
)
#Display
the dimensionsdim
(
object)
Output [1] 70000 16As you can see in the output, sizes of the big.matrix object have been displayed.
Display big.matrix objectTo display the first 6 rows, we can use the head() function −
Examplehead
(
object)
Output enterprise record_number msa perc_minority [1,] 1 566 1 1 [2,] 1 116 1 3 [3,] 1 239 1 2 [4,] 1 62 1 2 [5,] 1 106 1 2 [6,] 1 759 1 3 tract_income_ratio borrower_income_ratio [1,] 3 1 [2,] 2 1 [3,] 2 3 [4,] 3 3 [5,] 3 3 [6,] 3 2 loan_purpose federal_guarantee borrower_race [1,] 2 4 3 [2,] 2 4 5 [3,] 8 4 5 [4,] 2 4 5 [5,] 2 4 9 [6,] 2 4 9 co_borrower_race borrower_gender [1,] 9 2 [2,] 9 1 [3,] 5 1 [4,] 9 2 [5,] 9 3 [6,] 9 1 co_borrower_gender num_units affordability year [1,] 4 1 3 2010 [2,] 4 1 3 2008 [3,] 2 1 4 2014 [4,] 4 1 4 2009 [5,] 4 1 4 2013 [6,] 2 2 4 2010 type [1,] 1 [2,] 1 [3,] 0 [4,] 1 [5,] 1 [6,] 1 Creating TableWe can also create a table. The sample csv file contains year as the column name, so we can display the number of mortgages using the following program −
Example#
Create
a tablefor
the number # of mortagesfor
each specific year(
table
(
object[
,
"year"
]
)
)
Output 2008 2009 2010 2011 2012 2013 2014 2023 6919 8996 7269 6561 8932 8316 4687 5493As you can see in the output, the number of mortgages have been displayed for each specific year.
Data SummaryNow we have learnt how we can import a big.matrix object. We will now see how we can analyze the data stored in the object. R provides us binanalytics package using which we can create summaries. You can download biganalytics library using the following in CRAN −
install.packages("biganalytics") ExampleNow let us consider the following program that displays the summary of the mortgage −
library
(
biganalytics)
#Download
file using URL destfile=
"mortgagesample.csv"
)
#Create
an object of object<

read.
big.
matrix
(
"mortgagesample.csv"
,
header=
TRUE,
type=
"integer"
,
descriptorfile=
"mortgagesample.desc"
)
#Display
the summarysummary
(
object)
Output enterprise 1.0000000 2.0000000 1.3814571 0.0000000 record_number 0.0000000 999.0000000 499.9080571 0.0000000 msa 0.0000000 1.0000000 0.8943571 0.0000000 perc_minority 1.0000000 9.0000000 1.9701857 0.0000000 tract_income_ratio 1.0000000 9.0000000 2.3431571 0.0000000 borrower_income_ratio 1.0000000 9.0000000 2.6898857 0.0000000 loan_purpose 1.0000000 9.0000000 3.7670143 0.0000000 federal_guarantee 1.0000000 4.0000000 3.9840857 0.0000000 borrower_race 1.0000000 9.0000000 5.3572429 0.0000000 co_borrower_race 1.0000000 9.0000000 7.0002714 0.0000000 borrower_gender 1.0000000 9.0000000 1.4590714 0.0000000 co_borrower_gender 1.0000000 9.0000000 3.0494857 0.0000000 num_units 1.0000000 4.0000000 1.0398143 0.0000000 affordability 0.0000000 9.0000000 4.2863429 0.0000000 year 2008.0000000 2023.0000000 2011.2714714 0.0000000 type 0.0000000 1.0000000 0.5300429 0.0000000The output shows the summary of the object by specifying min, max, mean, and NAs values.
ConclusionIn this tutorial, we discussed scalable data processing in R. We started with how processing time is related to data size. We saw the working of “out of core” objects like big.matrix. I hope through this tutorial you would have gained the knowledge of scalable data processing in R which is important from the perspective of data science.
Binary Tree In Data Structure (Example)
What is a Binary Tree?
The word binary means two. In the tree data structure “Binary Tree”, means a tree where each node can have a maximum of two child nodes (left and right nodes). It is a simple binary tree.
However, there’s another binary tree that is used most frequently and has several use cases. It’s called the Binary Search Tree (BST). This tree can make the search algorithm way faster, precisely log(n) time complexity. In the data structure, n means the number of nodes in the binary tree.
What are the Differences Between Binary Tree and Binary Search Tree?The difference between the BST and regular Binary tree is in the BST left node has a smaller value than the root node, and the right node has a larger value than the root node. So, the left subtree will always contain a smaller value than the root, and the right subtree will always contain a larger value than the root.
In this Algorithm tutorial, you will learn:
Example of Binary Search TreesLet’s have the following example for demonstrating the concepts of the Binary Search Tree.
Here you can all the nodes follow the given discipline. There’s a formula for the maximum number of nodes in the Binary Search Tree. If we observe the above tree, we can see each node has two children except all the leaf nodes. And the height(h) of the given Binary Tree is 4. The formula is 2h – 1. So, it gives 15.
The above given image is not a complete Binary Tree or Balanced Binary Tree, is called the Complete Binary tree or Balanced Binary Tree. There’s another Data Structure called AVL (another type of Binary Tree) that optimizes the height of Binary Tree and performs search faster for the BST like in Fig 3.
Try to calculate the inorder traversal of the Binary Tree given above. You’ll find that it will give a nondecreasing sorted array, and Traversal algorithms will be the same as the Binary Tree.
Types of Binary Tree:Here are some important types of Binary Tree:
Full Binary Tree: Each node can have 0 or 2 child nodes in this binary tree. Only one child node is not allowed in this type of binary tree. So, except for the leaf node, all nodes will have 2 children.
Full Binary Tree: Each node can have 0 or 2 nodes. It seems like the Full Binary Tree, but all the leaf elements are lean to the left subtree, whereas in the full binary tree node can be in the right or left subtree.
Perfect Binary Tree: All the nodes must have 0 or 2 nodes, and all the leaf nodes should be at the same level or height. The above example of a full binary tree structure is not a Perfect Binary Tree because node 6 and node 1,2,3 are not in the same height. But the example of the Complete Binary Tree is a perfect binary tree.
Degenerate Binary Tree: Every node can have only a single child. All the operations like searching, inserting, and deleting take O(N) time.
Balanced Binary Tree: Here this binary tree, the height difference of left and right subtree is at most 1. So, while adding or deleting a node, we need to balance the tree’s height again. This type of SelfBalanced Binary Tree is called the AVL tree.
There are three basic operations of BST. Those are discussed in detail below.
Implementation of Binary Tree in C and C++:using namespace std; struct Node { int value; struct Node *left, *right; } struct Node *getEmptynode(int val) { struct Node *tempNode = (struct Node *)malloc(sizeof(struct Node)); return tempNode; } struct Node *successor(struct Node *node) { struct Node *present = node; { } return present; } struct Node *insert(struct Node *node, int value) { if (node == NULL) { return getEmptynode(value); } { } else { } return node; } int searchInBST(struct Node *node, int value) { struct Node *current = node; { { } else { } if (current == NULL) { return 0; } } return 1; } void inorder(struct Node *root) { if (root != NULL) { } } struct Node *deleteNode(struct Node *node, int value) { if (node == NULL) { return node; } { } { } else { { free(node); return temp; } { free(node); return temp; } } return node; } int main() { struct Node *root = NULL; root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 2); root = insert(root, 6); root = insert(root, 10); root = insert(root, 14); root = insert(root, 1); root = insert(root, 3); root = insert(root, 5); root = insert(root, 7); root = insert(root, 9); root = insert(root, 11); root = insert(root, 13); root = insert(root, 15);
cout << “InOrder Traversal after inserting all nodes: ” << endl; inorder(root); root = insert(root, 10); cout << “nInOrder Traversal after inserting 10 : ” << endl; inorder(root); cout << “nSearching 5 in the BST: ” << searchInBST(root, 5) << endl; cout << “Searching 10 in the BST: ” << searchInBST(root, 10) << endl; root = deleteNode(root,8); cout<<“After deleting node 8, inorder traversal: “<<endl; inorder(root); root = deleteNode(root,10); cout<<“nAfter deleting node 10, inorder traversal: “<<endl; inorder(root); }
Output:
InOrder Traversal after inserting all nodes: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 InOrder Traversal after inserting 10 : 10 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Searching 5 in the BST: 0 Searching 10 in the BST: 1 After deleting node 8, inorder traversal: 10 1 2 3 4 5 6 7 9 10 11 12 13 14 15 After deleting node 10, inorder traversal: 1 2 3 4 5 6 7 9 10 11 12 13 14 15 Implementation of Binary Tree in Python class Node: def __init__(self,value): chúng tôi = None self.right = None self.value = value def insert(root,value): if root == None: return Node(value) if value< root.value: chúng tôi = insert(root.left,value) else: root.right = insert(root.right,value) return root def searchInBST(root,value): current = root while current.value != value: current = current.left else: current = current.right if current == None: return "Not found" return "Found" def inorder(root): if root != None: inorder(root.left) print(root.value,end=" ") inorder(root.right) def successor(root): present = root while present != None and chúng tôi != None: present = present.left return present def deleteNode(root,value): if root == None: return root if value < root.value: chúng tôi = deleteNode(root.left, value) root.right = deleteNode(root.right, value) else: if chúng tôi == None: temp = root.right root = None return temp elif root.right == None: temp = root.left root = None return temp temp = successor(root.right) root.value = temp.value root.right = deleteNode(root.right, temp.value) return root root = Node(8) root = insert(root, 4) root = insert(root, 12) root = insert(root, 2) root = insert(root, 6) root = insert(root, 10) root = insert(root, 14) root = insert(root, 1) root = insert(root, 3) root = insert(root, 5) root = insert(root, 7) root = insert(root, 9) root = insert(root, 11) root = insert(root, 13) root = insert(root, 15) print("InOrder Traversal after inserting all nodes: ") inorder(root) root = insert(root, 10) print("nInOrder Traversal after inserting 10 : ") inorder(root) print("nSearching 5 in the BST: ",searchInBST(root, 5)) print("Searching 5 in the BST: ",searchInBST(root, 10)) root = deleteNode(root,8) print("After deleting node 8, inorder traversal:") inorder(root) root = deleteNode(root,10) print("nAfter deleting node 10, inorder traversal:") inorder(root)Output:
InOrder Traversal after inserting all nodes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 InOrder Traversal after inserting 10 : 10 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Searching 5 in the BST: Not found Searching 5 in the BST: Found After deleting node 8, inorder traversal: 10 1 2 3 4 5 6 7 9 10 11 12 13 14 15 After deleting node 10, inorder traversal: 1 2 3 4 5 6 7 9 10 11 12 13 14 15 Application of Binary Tree:Here are some common applications of Binary Tree:
Organizing node data in sorted order
Used in the map and set node objects in programming language libraries.
Searching for elements in the data structures
» Learn our next tutorial about Combination Algorithm
User Defined Data Types In C++
Introduction to UserDefined Data Types in C++
User Defined Data types in C++ are a type for representing data. The data type will inform the interpreter how the programmer will use the data. A data type can be predefined or userdefined. Examples of predefined data types are char, int, float, etc.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Types of UserDefined Data in C++The types of userdefined data are as follows:
1. StructureA structure is a collection of various types of related information under one name. The declaration of structure forms a template, and the variables of structures are known as members. All the members of the structure are generally related. The keyword used for the structure is “struct.”
For example, a structure for student identity having ‘name,’ ‘class,’ ‘roll_number,’ and ‘address’ as a member can be created as follows:
struct stud_id { char name[20]; int class; int roll_number; char address[30]; };This is called the declaration of the structure, and it is terminated by a semicolon (;). The memory is not allocated, while the structure declaration is delegated when specifying the same. The structure definition creates structure variables and gives storage space for them. One can define the variables of the structure as follows:
stud_id I1, I2;Where I1 and I2 are the two variables of stud_id. After defining the structure, one can access its members using the dot operator as follows:
I1.roll_number will access the roll number of I1
I2.class will access the class of I2
Example:
struct stud_id { int class, roll_number; }; int main() { struct stud_id entries[10]; // Create an array of structures entries[0].class = 4; // Access array members entries[0].roll_number = 20; cout <<entries[0].class << ", " << entries[0].roll_number; return 0; } 2. ArrayAn array is a collection of homogeneous data and must be defined before using it for the storage of information. The array can be defined as follows:
int marks[10]
The above statement defined an integertype array named “marks” that can store the marks of 10 students. After creating an array, one can access any element of an array by writing the name of an array, followed by its index. For example, to access the 5th element from marks, the syntax will be:
marks[5]It will give the marks stored at the 5th location of an array. An array can be onedimensional, twodimensional, or multidimensional, depending upon the specification of elements.
int main() { int marks[10]; marks[0] = 5; marks[2] = 10; cout<<marks[0], marks[2]); return 0; } 3. UnionJust like structures, the union also contains members of different data types. The main difference is that the union saves memory because union members share the same storage area. In contrast, members of the structure have their unique storage areas. One declares the unions with the keyword “union,” as shown below:
union employee { int id; double salary; char name[20]; }One can define the variable of the union as:
union employee E;To access the members of the union, one can use the dot operator as follows:
E.salary; 4. ClassA class is an essential feature of objectoriented programming languages like C++. A class is a group of objects with the same operations and attributes. To declare a class, use the keyword “class” and follow this syntax:
{ private: Data_members; Member_functions; public: Data_members; Member_functions; };
In this, the names of data members should be different from member functions. There are two access specifiers for classes that define the scope of the members of a class. These are private and public. The member specified as private can only be accessed by the member functions of that particular class. The members, defined as the public, have internal and external access to the class. The members with no specifier are private by default. We refer to the objects that belong to a class as instances of the class. The syntax for creating an object of a class is as follows:
Example:
class kids { public: char name[10]; int age; void print() { cout<<"name is:"<< name; } } Int main { Kids k; k.name="Eash"; k.print(); return 0; } 5. EnumerationEnumeration is specified by using the keyword “enum.” It is a set of named integer constants that define all the possible values a variable of that particular type can have. For example, the enumeration of the week can have names of all the seven days of the week as shown below:
enum week_days{sun, mon, tues, wed, thur, fri, sat}; int main() { enum week_days d; d = mon; cout << d; return 0; } 6. PointerA Pointer is a userdefined data type that creates variables for holding the memory address of other variables. If one variable holds the address of another variable, we say that the first variable is the pointer to the other variable. The syntax for the same is:
type *ptr_name;Here type is any data type of the pointer, and ptr_name is the pointer’s name.
Example:
void main() { int a = 10; int *p; // pointer variable is declared p = &a; cout<<"Value at p = ",<<p); cout<<"Value at variable a = “,<<a); cout<<"Value at *p = ",<< *p); } 7. TypedefUsing the keyword “typedef,” one can define new data type names to the existing ones. Its syntax is:
typedef float balance;
When we create a new name for the float data type, such as “balance,” we can use it to declare variables of the float type. The use of a typedef can make the code not only easy to read but also to port to a new machine as well.
Example:
typedef int score; int main() { score s1, s2; s1 = 80; cout << " " << b1; return 0; } ConclusionC++ supports different kinds of userdefined data types, as discussed above. Many other data types exist, such as functions, references, etc. Their use makes programming much easier, and they also help us to club different types of data in a single variable.
Recommended ArticlesThis is our guide to UserDefined Data Types in C++. Here are some further articles to learn more:
Example, Types And Important Of Cost Centre
Definition of Cost Centre
Start Your Free Investment Banking Course
Download Corporate Valuation, Investment Banking, Accounting, CFA Calculator & others
ExplanationCost centrecan be any department or unit if the business which is responsible only towards the costs incurred by it and it is not responsible towards generation of the revenue or the usage of the assets. They mainly focus on proper utilization of the resources of the company where performance in case of the cost centre is evaluation on the basis of the performing comparison between the budgeted costs of the company to its actual cost. The cost which these cost centres incurs are aggregated into one cost pool and then allocated to the other units of the business. In an organization, there could be multiple cost centre. Even within one department of company there could be several cost centre.
How does it Work?Costs centres are the different sub units within the organization which are created not with the motive of earning revenues or profits directly from them rather they are created to track the expenses in the company. The main focus of the management is to keep the expenditure of the company at the minimum possible level with the help of its cost centreand to ensure optimum utilization of its resources as they help in providing the better understanding about how the resources are being used in the organization.
Example of Cost CentreOther examples of Cost centre are maintenance department, customer service centre, Information technology department, Human resource department etc.
Types of Cost CentreOn the basis of nature of the business cost centrecan be categorized into six different types which are as follows:
Personal Cost Centre: The cost centre will be considered as the personal cost centre if it refers to any person or to the group of the persons. Example of this includes works manager, sales manager etc.
Impersonal Cost Centre: The cost centre will be considered as the impersonal cost centre if it refers to any equipment or to the group of the equipment or to any location.
Service Cost Center: The cost center will be considered as the service cost center if it performs any service rendering activity to its production centers or other service cost centers. Example of this includes personnel service centre which provides canteen facility to the employees of the company etc.
Production cost Centre: The cost center will be considered as the production cost center if it deals with any production activity of the company. Example of this includes assembly shop, machine shop etc.
Operation Cost Centre: The cost center will be considered as the operation cost center if itconsist of the persons or the machines that follows similar type of activities in the company.
Process Cost Centre: The cost center will be considered as the production cost center if it deals with any specific process or continuous sequence of the company’s operations.
Why are Cost Centers Important?Cost centre are very important department for the businesses as it adds value to the entity and allows the entity to make profit. Hereunder the causes why it is important for the business:
They help the company in recovering the different overhead expenses.
The client service department is used by an entity to resolve the complaints of clients regarding final products or to give an understanding of companies policies and warranties to the clients. This will enhance the goodwill of the company in the market and it helps to attract large number of customers for the company.
IT Department and maintenance staff ensure that all equipment of the company is running appropriately and proper hygiene is maintained in the organization. It helps organizations to keep their employees healthy and make a profit for the company.
It helps the company in analyzing the market and the effectiveness of their business strategies.
Cost centre help the organization in managing their office related tasks like payroll, budgeting, etc.
Benefits of Cost Centre
Cost centre monitor the efficiency and effectiveness of all business operations within the company.
It will help the company to reduce its cost related to a particular function. Cost centre tries to reduce their costs by updating the processes and make it more effective which results in the generation of revenue or prevention of losses.
To analyze the profitability of the cost centre, cost data of different period are compared with each other. It will help managers to become more productive as they are held accountable for the expenses incurred in their control
Drawbacks of Cost CentreDrawbacks of Cost centre are as follows:
Mangers of cost centers are only responsible for controlling the cost of their division or cost center. They have no control over the profit of the company.
ConclusionThus,cost centre are used by an organization for tracking all expenses related to a particular function. Their main objective is to minimize the cost. These departments does not generate revenue for the company but responsible for incurring cost for the company.
Recommended ArticlesThis is a guide to Cost Centre. Here we also discuss the definition and how does cost centre work? along with benefits and drawbacks. You may also have a look at the following articles to learn more –
Update the detailed information about Data Types In R With Example on the Hatcungthantuong.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!