Basic programming, .NET technology.

DATA STRUCTURES - 1


Data structures and algorithms – the nightmare of most IT students. After finishing school, I, as well as my fellow students, confidently declared that: He knows us, and we don't know them. Therefore, this series of articles on "Data Structures and Algorithms" was born, the purpose is to help me review my knowledge of data structures and algorithms.

What is data structure? It is a technique for organizing and arranging data in a computer's memory. How data is sorted and organized affects how it is retrieved and used. Imagine that the memory of your computer is just your tiny attic… and the data is the items in your home, how you organize those items will affect how you find them and use them. they.

In this article, we will learn about: Arrays (Array). Shall we know what they are? Performance and how to use them?

     1. Array
A collection of data elements stored contiguously in a memory area. The elements of a must have the same data type (data type). Array elements can be accessed directly based on the index. In .Net Framework, the index starts from 0.

Consider the following example:

Statement 1: We declare an array of type integer
Statement 2: We initialize the array with 4 elements.
The allocation and initialization of memory to store the array will happen as shown below.

To work with arrays we need to know 2 types of common operations: Allocate and access.
- Allocate: this is the declaration and initialization of the array, it will allocate a memory area on the stack when we declare the array and a memory area on the heap when we initialize the size of the array.
- Access: to access any element of the array, we use index. As said .Net Framework starts from 0. With the following code, we assign the value to the 2nd element and retrieve its value to use.

The elements of the array are stored contiguously in a block of memory, and it is accessed directly through the index of the array. That's why reading and writing arrays is fast. However, the array requires a size declaration when initialized, and its elements must be of the same data type.

To decide whether to use arrays in programming or not, we need to consider three issues: do we require fast data access or do we need to be fast? Is it possible to know in advance the number of elements in a data set? And is the data type of the elements the same?

However, we can use ArrayList to replace Array in case the size of the array cannot be fixed or the datatype of the element is different.

Share:

Lập trình hướng đối tượng – OOP (2)

In my previous article, I shared some of its basic concepts: what is an object? What are classes? How is the constructor defined and used?

Next, in this article, I will present the basic features of object-oriented programming. Everyone knows when it comes to object-oriented programming, any coder, from amateur to professional, must master these characteristics. It's like the inner gong of a sect. Referring to that type of martial arts, one must immediately remember its inner gong and know how to use it. So what is the inner work of the mind of OPP? These are Abstraction, Inheritance, Encapsulation, Polymorphism.

Here we go.

First, Abstraction: It is a feature, an object-oriented principle, used to describe and display the necessary features of an object for other objects. This feature allows hiding the details of the object. It focuses on what the object does rather than how the object does it.

You can picture it like this: We have a dog, it is an object. It has action: go and eat. Dogs also have a way of walking, a dog's way of eating is different from a cat's. Abstraction, describing to the surrounding, the dog has the act of eating and walking. But how to eat, how to walk it is the dog's business, not to be described to the surroundings.
See the following code for more clarity.


Second, Encapsulation.
This means that the details of an object are restricted from being accessed by other objects, or hidden from view by other objects.
Speaking of closures, we need to know a concept called access modifier. It controls access to member data in a class. We have access modifiers: private, public, internal, protected, protected internal.

- Private: only members of the same class can access it.
- Public: unlimited access.
- Protected: only members of the class and the derived class have access.
- Internal: only members in the same assembly.
- Protected internal: members in the same assembly or inherited class are accessible.




Next, let's learn the third, Inheritance.
Defining inheritance in the object-oriented direction is the same as in social inheritance. Everyone must know who inherits, inherits from whom, and inherits what characteristics?
In object-oriented, the class to be inherited is called “superclass” or “base class”, in this class we define common features that will be inherited from subclasses. Subclasses that inherit from the parent class are called "derived classes".
The benefit of inheritance is that it can reuse code, increase system maintainability, as well as reduce the cost of system development. C# does not support multiple inheritances, to do that, we can use an interface.
An example of inheritance: We have a superclass animal: has a name property, a constructor, a move and eat method. Subclasses: dog, cat inherit from an animal class.



Implement base class



Implement derived class: Dog



Use derived class:

                



Finally Polymorphism.
Polymorphism means many forms. When a problem is handled in different ways, we call it polymorphism. We have two types of polymorphism: Compile polymorphism, or overloading, and run-time polymorphism, or overriding.
-  Overloading: a method has many different forms based on its own parameters.



- Overriding by using the keyword: virtual and override
-        



Above, you and I have gone through the 4 main slogans in object-oriented programming. Hopefully, we will memorize and use it in the best way in the Kung-fu code.

Related posts:
Share:

Lập trình hướng đối tượng - OOP 1


If you are a student or a professional coder, you must have heard many times about OPP or object-oriented programming.
In my series of 2 articles, I will review the basic concepts of object-oriented programming. What is it? What are its characteristics?

OPP stands for Object oriented programming. It is a programming paradigm that is based on objects. It models real-world objects into programming objects. Those objects have the same properties and actions as in the real world. 

For example, A student is a real-world object. Student attributes height, weight, age, name... Actions: eat, sleep, walk, study. When modeled in programming, we also have an object that holds the data of student information and actions.
So each student object we create a student object in programming? It's not like that: We have concepts: object and class
What are classes?
It is a prototype of objects. It has variables that store data as well as methods of an object

We have a student class as follows


Object là gì?
Object là một thể hiện cụ thể của một đối tượng thực tế thông qua bản mẫu là một class. Khi một object được tạo thì nó sẽ được cấp phát một vùng nhớ trên heap để lưu trữ thông tin của nó.
Ví dụ: Ta có đối tượng sinh viên 1 là một thể hiện cụ thể của một sinh viên trong thực tế, qua bản mẫu là class sinh viên ta vừa tạo ở trên.

What are Objects?
The object is a concrete instance of an actual object through the template is a class. When an object is created, it will be allocated a memory area on the heap to store its information.

For example, We have student object 1 which is a specific instance of a student in reality, through the template is the student class we just created above.



Here we create a constructor with 2 variables passed in, name and age. This constructor will assign values to the member variables of the class.
When we initialize the student object with this constructor, we will pass the value of name, age.



Example: 

Using the student class creates a student object, and calls the object's self-introduction function.


Results: Just like in the real world, students use their own information to introduce others, in programming when abstracting an object, it also has the same behavior: using the information to self-identify. introduce yourself


Through this example, we can better understand: what is a class? What is an object? What is Constructor? And how to use them. In the following article, I will present the basic properties of OPP.

Related posts:
Share:

CÁC CẤU TRÚC LẶP - Repetition structures


    Hoang Phi Hong, you must have heard a lot about this name, especially those who have a bit of blood in fighting and kicking will know very well. This master has a technique called Shadowless Kick. Roughly it is a series of consecutive kicks. It is repetition. In programming we also have a similar technique, also performing the repetition of a certain piece of code. That's the charge loop, oh my…the loop structures.

In C#, we have loop types like while loop, do-while loop, for loop, and foreach loop. Within the scope of this article, I only present the concept, structure, block diagram, and usage (just at a simple level) of each of the above iterations.

First, we need to understand iteration constructs that will allow us to execute a statement or group of statements n times when the loop condition is true.


1. While loop
    Is a simple loop structure, allowing statements to be executed until the value of the conditional expression is still true (condition expression = true).

Syntax:
      While (condition)
     {
            Statement(s);
     }

For example:

Run the above code, will print the screen values the values of n from 0 -> 6.

We see the structure of the while loop that will consider the value of n before executing the code inside the loop. With the while loop structure, we do not specify the number of iterations, the number of iterations depends on the value of the conditional expression. So it is very likely that the statements inside the loop will not be executed at all.

The flowchart diagram, which can be represented as follows:



       2. Do-while loop
     The do-while construct is similar to the while construct. It allows executing statements when the value of the conditional expression is true. It also cannot know the exact number of iterations in advance, it depends on the value of the conditional expression. But the difference from the while structure is that the conditional expression is placed at the bottom of the loop. This means that even if the conditional expression is false, the loop will be executed at least once. You can think of it as something like Better a glorious minute than a hundred years.

The structure of do-while is as simple as while:
      do
     {
            Statement(s);  
     }
     while(condition)

Let see the below code:

Here's the result


   Even though the conditional expression is false, the loop's code is still executed once. It is a remarkable feature when we use the do-while structure.



When studying the two structures above, we see that they are both structures with an indefinite number of iterations. Next, we will learn two iterative constructs, which we can predetermine the number of iterations.

       3. For loop
   This structure, allows statements to be executed when the value of the conditional expression is still true.

The difference with the above two structures is that the for loop has 3 components: the initialization expression for the loop, the conditional expression, and the counter variable. This helps fraternal coders completely determine the exact number of iterations they want.

Its structure is as follows
     for(init-expr; cond-expr; count-expr)
    {
            Statement(s);
    }

Example: 

Here's what we got

Here's the flowchart:

                 
The for construct is very useful in case we need to iterate a certain number of times.

       4. Foreach loop:
We have a collection of type arrays or any kind of collection. The usual way we use for traverses from 0 -> array.length; There is nothing wrong with this, but in C# there is a loop type that helps us iterate through the elements of an array or any type of collection. It's foreach.

We have a syntax:
   foreach(elementtype element in collection)
  {
            Statement(s);  
  }

   For example, we have an array of list of courses, we want to go through this list and print the name of each element in the list, we can use this trick as follows:



Here we got

      
   One thing worth noting about foreach is that we traverse the array sequentially, using only the element in question, and don't care about the number of elements currently in the array. In contrast, with for, we can do random access while traversing the array, but need to know the number of elements in the array.

      Each iterative structure has its own advantages and disadvantages, and how to use it to achieve the desired results is up to each coder. But first, having a good understanding of iterative constructs, and practicing it in specific situations over and over again, will help us to use them more effectively.



Share:

CẤU TRÚC RẼ NHÁNH - Decision structures


In this section, I will review with you the basics of branching. It is a fundamental part of any programming language. It is similar to the basic martial arts in Kung-fu.

What is a branching structure? Attack or defend, attack, wait, no no… defend. The boxer is wondering whether to attack or defend in this case. Don't worry, the branching structure will help the boxer decide which option. I've rambled on about fighting again. But hopefully easy to understand branching structure. The branching structure helps to make a decision, no matter what the situation, fighting or coding. I will go deeper into the field of coding. J)

In C# we have branching structures: If, If-else, switch.

1. If, If - else
Form: If(Boolean expression)
            {
                        //Code
    }

Code is executed only when the Boolean expression is true.

For example

Here is the result:

If the statement flow chart



Here, the resulting output to the screen will be executed, when the condition i < j is true.

Try to guess the result of the following code:


Let see the if-else construct. The if-else construct will allow the program to execute a piece of code when the Boolean expression is false.

For instance:

In this case, it is easy to see that i is not greater than j. So the code in the else part will be executed and output to the output screen:




2. Switch 
It allows multiple branches like if-else, in which there must be one or more cases and a default case is required. 
Form:

Switch(expression)
Case1: Code block 1
Case2: Code block 2
Default:

Let see the below example


Result is:


The above constructs all help the program to make a decision about which code to execute. The question is when to use which structure? This requires each coder to practice a lot, and accumulate more experience for themselves. Personally, when deciding to branch based on a constant value, I would use a switch, it makes the code easy to read, and easy to debug.


Share:

DATA TYPE 2: Reference type


In the previous post, I introduced the basics of value types. In today's post, I continue to introduce you to reference types. What is a reference type? What types are there? Is it possible to convert from a reference type to a value type?

As we know the value type will store the value of a variable directly, and that value is stored on the stack. Unlike the value type, the reference type does not store the value directly, but it does contain a pointer to the memory area where the value is stored. The value of the reference type is stored on the heap.

To understand better, we can consider the following illustrative example:



In the above example, I create a variable name with a data type string and do not initialize it. I then assign a value to the variable name. The name variable will store in allocated memory "M100" and the M100 will point to the actual value I assigned to the variable name = “Victor”.


Could I convert a value from Reference type to Value type??
  
Definitely yes, and that conversion technique in the coding world they call "boxing and unboxing".

Boxing is a conversion from a value type to a reference type. Boxing is also known as implicit conversion. During conversion, the CLR will convert the value type to System. Object and store it on the Heap.

Let check this example:



In the above example, the CLR will create a variable int i = 10 and store it on the stack. Then will create a variable "o" on the heap and copy its value to the corresponding allocated memory for the object "o".



Unboxing will convert from a reference type to a value type. Unboxing is also understood as converting the data type explicitly.



In the first two lines, the CLR will convert from value type to reference type. The next line will perform the conversion from a reference type to a value type, which also includes checking if object o is holding a value of type int?

Let see this example:


Here is the result:



The reason, during unboxing, the CLR will perform checks to make sure the boxed object is of the correct type given.

Thus, we have understood the basic concept of value types and reference types, as well as understand their conversion using boxing and unboxing techniques.

Related Posts:

Share:

Data type 1 - Value type



When you work with any programming language, you will hear the phrase "Data type". So what is the data type? And is it important? How to use it? And in C# language, what data types are there? Those are definitely the questions that anyone new to programming asks.

When you declare a variable, make sure you declare a data type to store the data in an area of RAM. Based on the data type that you declare, the system will allocate a memory area and decide what information and domain values can be stored in that memory area.

(Pic 1: Illustrate data type – source: Internet)

In C# there are the following data types: Value type (Value type), reference type (Reference type), and pointer type (Pointer type). In this article, I only show the Value type.
Value Type is inherited from the System.ValueType class, which stores a value of a type that directly transforms the value.


(Pic 2: Illustrate Value Type.)


When knowing the data types, programmers will easily use them to declare variables in a reasonable way to avoid wasting memory resources, as well as avoid errors in the process of using variables.

For example, We need 1 variable to store a person's age, you just need to declare the byte type is enough. Because the value range of byte type is 0 – 255.



In short, understanding and knowing how to use data types is important in programming. It is the most basic. If you compare programming as an elaborate discipline, then understanding the data types in a programming language, and mastering it is like doing basic exercises. Without it, you can hardly reach a higher realm in programming.

Related Post:



Share:

Featured Posts

Data type 3 - string type