Posted in Home

Live*

This is a page to share my thoughts and feelings about new events, happening live today or in the near future, all I share is my personal thoughts, looking forward to discussing with everyone.

VIDEO] Live Stream Best Practices (1/2) | Believe

ฤรขy lร  chuyรชn mแปฅc cแบญp nhแบญt thฦฐแปng ngร y, nฦกi mรฌnh ฤ‘ฦฐa ra nhแปฏng bร i viแบฟt vแป nhแปฏng vแบฅn ฤ‘แป nแป•i cแป™m hiแป‡n nay, tแบฅt nhiรชn lร  dฦฐแป›i gรณc nhรฌn cแปงa mแป™t lแบญp trรฌnh viรชn kinh nghiแป‡m ฤ‘ang lร m viแป‡c tแบกi 1 trong nhแปฏng cรดng ty vแบญn tแบฃi lแป›n nhแบฅt thแบฟ giแป›i:

Nแป™i dung chia sแบป bao gแป“m:

Lแบญp trรฌnh

Khoa hแปc mรกy tรญnh

Thรดng tin kinh tแบฟ, chรญnh trแป‹ xรฃ hแป™i

Hoแบทc cรกc chแปง ฤ‘แป khรกc nแบฟu nhiแปu bแบกn thรญch nรณi vแป nรณ thรฌ mรฌnh sแบฝ viแบฟt bร i trรชn nร y hoแบทc lร  lร m vlog youtube ฤ‘แปƒ nรณi vแป vแบฅn ฤ‘แป ฤ‘รณ , cรกc bแบกn theo dรตi kรชnh cแปงa mรฌnh tแบกi ฤ‘รขy nhรฉ:

How to build Robot Project in Frankfurt University Germany – YouTube

Posted in Docker

Docker & Kubernetes- Helm chart repository

Creating a Helm chart repository

In this post, we’ll learn how to create and work with Helm chart repositories.

A chart repository is an HTTP server that houses an index.yaml file and optionally some packaged charts. Because a chart repository can be any HTTP server that can serve YAML and tar files and can answer GET requests, we have a plethora of options when it comes down to hosting our own chart repository. For example, we can use a Google Cloud Storage (GCS) bucket, Amazon S3 bucket, GitHub Pages, or even create our own web server.

Once the charts are ready and we need to share them, the easiest way to do so is by uploading them to a chart repository. However, Helm does not come with a chart repository while Helm can serve the local repository via “helm serve”.

Github Pages

We can create charts repository using GitHub Pages. It allows us to serve static web pages.

All we need is to host a single index.yaml file along with a bunch of .tgz files.

Create a new Github repositoryCreate-a-new-Github-Repo.png

Though it’s empty repo, let’s just clone it for now:

$ git clone https://github.com/Einsteinish/dummy-helm-charts.git    

Create a helm chart

We need to have the Helm CLI installed and initialized:

$ helm version
Client: &version.Version{SemVer:"v2.16.10", GitCommit:"bceca24a91639f045f22ab0f41e47589a932cf5e", GitTreeState:"clean"}
Server: &version.Version{SemVer:"v2.16.10", GitCommit:"bceca24a91639f045f22ab0f41e47589a932cf5e", GitTreeState:"clean"}

$ helm3 version
version.BuildInfo{Version:"v3.3.1", GitCommit:"249e5215cde0c3fa72e27eb7a30e8d55c9696144", GitTreeState:"dirty", GoVersion:"go1.15"}    

We’re going to use the directory ./sources/ for the sources of our charts. We need to create charts and copy them into the ./sources/:

$ cd dummy-helm-charts/
$ mkdir sources  

$ tree
.
โ””โ”€โ”€ dummy-helm-charts
    โ”œโ”€โ”€ README.md
    โ””โ”€โ”€ sources
    
$ helm create sources/dummy-chart
Creating sources/dummy-chart

$ tree
.
โ”œโ”€โ”€ README.md
โ””โ”€โ”€ sources
    โ””โ”€โ”€ dummy-chart
        โ”œโ”€โ”€ Chart.yaml
        โ”œโ”€โ”€ charts
        โ”œโ”€โ”€ templates
        โ”‚   โ”œโ”€โ”€ NOTES.txt
        โ”‚   โ”œโ”€โ”€ _helpers.tpl
        โ”‚   โ”œโ”€โ”€ deployment.yaml
        โ”‚   โ”œโ”€โ”€ ingress.yaml
        โ”‚   โ”œโ”€โ”€ service.yaml
        โ”‚   โ”œโ”€โ”€ serviceaccount.yaml
        โ”‚   โ””โ”€โ”€ tests
        โ”‚       โ””โ”€โ”€ test-connection.yaml
        โ””โ”€โ”€ values.yaml
        
$ helm lint sources/*
==> Linting sources/dummy-chart
[INFO] Chart.yaml: icon is recommended

1 chart(s) linted, no failures

Create the Helm chart package

$ helm package sources/*
Successfully packaged chart and saved it to: 
/Users/kihyuckhong/Documents/Minikube/Helm/DUMMY/dummy-helm-charts/dummy-chart-0.1.0.tgz

Create the repository index

A chart repository is an HTTP server that houses an index.yaml file.

The index file contains information about each chart and provides the download URL, for example, https://example.com/charts/alpine-0.1.2.tgz for that chart.

The index file is a yaml file called index.yaml. It contains some metadata about the package, including the contents of a chart’s Chart.yaml file. A valid chart repository must have an index file. The helm repo index command will generate an index file based on a given local directory that contains packaged charts.

$ helm repo index --url https://einsteinish.github.io/helm-chart/ . 

$ tree
.
โ”œโ”€โ”€ README.md
โ”œโ”€โ”€ dummy-chart-0.1.0.tgz
โ”œโ”€โ”€ index.yaml
โ””โ”€โ”€ sources
    โ””โ”€โ”€ dummy-chart
        โ”œโ”€โ”€ Chart.yaml
        โ”œโ”€โ”€ charts
        โ”œโ”€โ”€ templates
        โ”‚   โ”œโ”€โ”€ NOTES.txt
        โ”‚   โ”œโ”€โ”€ _helpers.tpl
        โ”‚   โ”œโ”€โ”€ deployment.yaml
        โ”‚   โ”œโ”€โ”€ ingress.yaml
        โ”‚   โ”œโ”€โ”€ service.yaml
        โ”‚   โ”œโ”€โ”€ serviceaccount.yaml
        โ”‚   โ””โ”€โ”€ tests
        โ”‚       โ””โ”€โ”€ test-connection.yaml
        โ””โ”€โ”€ values.yaml


$ cat index.yaml
apiVersion: v1
entries:
  dummy-chart:
  - apiVersion: v1
    appVersion: "1.0"
    created: "2020-10-22T13:11:36.940863-07:00"
    description: A Helm chart for Kubernetes
    digest: c8d82f24fc29d40693a608a1fd8db1c2596a8325ecae62529502a1cbae8677a2
    name: dummy-chart
    urls:
    - https://einsteinish.github.io/helm-chart/dummy-chart-0.1.0.tgz
    version: 0.1.0
generated: "2020-10-22T13:11:36.935738-07:00"

Pushing to Github repository

$ git add .

$ git commit -m "initial commit"
[main 4006e22] initial commit
 12 files changed, 322 insertions(+)
 create mode 100644 dummy-chart-0.1.0.tgz
 create mode 100644 index.yaml
 create mode 100644 sources/dummy-chart/.helmignore
 create mode 100644 sources/dummy-chart/Chart.yaml
 create mode 100644 sources/dummy-chart/templates/NOTES.txt
 create mode 100644 sources/dummy-chart/templates/_helpers.tpl
 create mode 100644 sources/dummy-chart/templates/deployment.yaml
 create mode 100644 sources/dummy-chart/templates/ingress.yaml
 create mode 100644 sources/dummy-chart/templates/service.yaml
 create mode 100644 sources/dummy-chart/templates/serviceaccount.yaml
 create mode 100644 sources/dummy-chart/templates/tests/test-connection.yaml
 create mode 100644 sources/dummy-chart/values.yaml

$ git push origin main
...
To https://github.com/Einsteinish/dummy-helm-charts.git
   9d23dff..4006e22  main -> main    

Setting up Github Pages as a helm chart repository

From “settings” of git repository, scroll down to Github Pages section and configure it as follow:Github-Pages-save.png

Click “Save”:Github-Pages-saved.png

Helm client configuration

To use the charts on the repository, we need to configure their own Helm client using helm repo command:

$ helm repo add dummy https://einsteinish.github.io/dummy-helm-charts
"dummy" has been added to your repositories
~/Documents/Minikube/Helm/DUMMY/dummy-helm-charts $ helm repo list
NAME  	URL                                             
stable	https://kubernetes-charts.storage.googleapis.com
local 	http://127.0.0.1:8879/charts                    
dummy 	https://einsteinish.github.io/dummy-helm-charts

$ helm search dummy
NAME             	CHART VERSION	APP VERSION	DESCRIPTION                
dummy/dummy-chart	0.1.0        	1.0        	A Helm chart for Kubernetes
local/dummy-chart	0.1.0        	1.0        	A Helm chart for Kubernetes

Chart repository updates

Whenever we want to add a new chart to the Helm chart repository, we should regenerate the index.yaml file. The helm repo index command will rebuild the index.yaml file including only the charts that it finds locally. Note that we can use the –merge flag to incrementally add new charts to an existing index.yaml:

$ helm repo index --url https://einsteinish.github.io/dummy-helm-charts/ --merge index
Posted in Docker

More about Docker run command

Docker run command

The basic syntax for the Docker run command looks like this:

k@laptop:~$ docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Run a command in a new container

We’re going to use very tiny linux distribution called busybox which has several stripped-down Unix tools in a single executable file and runs in a variety of POSIX environments such as Linux, Android, FreeBSD, etc. It’s going to execute a shell command in a newly created container, then it will put us on a shell prompt:

k@laptop:~$ docker run -it busybox sh
/ # echo 'bogotobogo'
bogotobogo
/ # exit
k@laptop:~$

The docker ps shows us containers:

k@laptop:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

But right now, we don’t have any containers running. If we use docker ps -a, it will display all containers even if it’s not running:

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
4d673944ec59        busybox:latest      "sh"                13 minutes ago      Exited (0) 12 minutes ago                       trusting_mccarthy   

When we execute run command, it will create a new container and execute a command within that container. The container will remain until it is explicitly deleted. We can restart the container:

k@laptop:~$ docker restart 4d673944ec59
4d673944ec59   

We can attach to that container. The usage looks like this:

docker attach [OPTIONS] CONTAINER

Let’s attach to the container. It will put us back on the shell where we were before:

k@laptop:~$ docker attach 4d673944ec59

/ # ls
bin      etc      lib      linuxrc  mnt      proc     run      sys      usr
dev      home     lib64    media    opt      root     sbin     tmp      var
/ # exit

The docker attach command allows us to attach to a running container using the container’s ID or name, either to view its ongoing output or to control it interactively.

Now, we know that a container can be restarted, attached, or even be killed!

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                          PORTS               NAMES
4d673944ec59        busybox:latest      "sh"                21 minutes ago      Exited (0) About a minute ago                       trusting_mccarthy  

But the one thing we can’t do changing the command that’s been executed. So, once we have created a container and it has a command associated with it, that command will always get run when we restart the container. We can restart and attached to it because it has shell command. But if we’re running something else, like an echo command:

k@laptop:~$ docker run -it busybox echo 'bogotobogo'
bogotobogo

Now, we’ve created another container which does echo:

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                          PORTS               NAMES
849975841b4e        busybox:latest      "echo bogotobogo"   About a minute ago   Exited (0) About a minute ago                       elegant_goldstine   
4d673944ec59        busybox:latest      "sh"                29 minutes ago       Exited (0) 9 minutes ago                            trusting_mccarthy

It executed “echo bogotobogo”, and then exited. But it still hanging around. Even if we restart it:

k@laptop:~$ docker restart 849975841b4e
849975841b4e

It run in background and we don’t see any output. All it did “echo bogotobogo” again. I can remove this container:

k@laptop:~$ docker rm 849975841b4e
849975841b4e

Now it’s been removed from our list of containers:

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
4d673944ec59        busybox:latest      "sh"                35 minutes ago      Exited (0) 14 minutes ago                       trusting_mccarthy   

We want this one to be removed as well:

k@laptop:~$ docker rm 4d673944ec59
4d673944ec59
k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
k@laptop:~$ 

docker run -it

Let’s look at the -it in docker run -it.

k@laptop:~$ docker run --help

Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

  -i, --interactive=false    Keep STDIN open even if not attached

  -t, --tty=false            Allocate a pseudo-TTY
...

If we run with t:

k@laptop:~$ docker run -i busybox sh

ls
bin
dev
etc
home
lib
lib64
linuxrc
media
mnt
opt
proc
root
run
sbin
sys
tmp
usr
var

cd home

cd /home

ls
default
ftp

exit
k@laptop:~$

It is interactive mode, and we can do whatever we want: “ls”, “cd /home” etc, however, it does not give us console, tty.

If we issue the docker run with just t:

k@laptop:~$ docker run -t busybox sh
/ #

We get a terminal we can work on. But we can’t do anything because it cannot get any input from us. We can execute anything since it’s not getting what we’re passing in.

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                        PORTS               NAMES
3bcaa1d57ac0        busybox:latest      "sh"                15 seconds ago       Up 14 seconds                                     dreamy_yonath           
ac53c2a81ebe        busybox:latest      "sh"                About a minute ago   Exited (127) 55 seconds ago                       condescending_galileo   
497be20f5d7e        busybox:latest      "sh"                3 minutes ago        Exited (-1) 2 minutes ago                         nostalgic_wilson  

Docker run –rm

We need to kill the container run with only “t”:

      
k@laptop:~$ docker kill 3bcaa1d57ac0
3bcaa1d57ac0

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                       PORTS               NAMES
3bcaa1d57ac0        busybox:latest      "sh"                3 minutes ago       Exited (-1) 2 minutes ago                        dreamy_yonath           
ac53c2a81ebe        busybox:latest      "sh"                3 minutes ago       Exited (127) 3 minutes ago                       condescending_galileo   
497be20f5d7e        busybox:latest      "sh"                6 minutes ago       Exited (-1) 4 minutes ago                        nostalgic_wilson        

Then, we want to remove all containers:

 
k@laptop:~$ docker rm $(docker ps -aq)
3bcaa1d57ac0
ac53c2a81ebe
497be20f5d7e

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
k@laptop:~$ 

The argument q in docker ps -aq gives us id of all containers.

The next thing to do here is that we don’t want remove the containers every time we execute a shell command:

 
k@laptop:~$ docker run -it --rm busybox sh
/ # echo Hello
Hello
/ # exit

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
k@laptop:~$ 

Notice that we don’t have any container. By passing in --rm, the container is automatically deleted once the container exited.

 
k@laptop:~$ docker run -it --rm busybox echo "I will not staying around forever"
I will not staying around forever
k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
k@laptop:~$ 

Docker rmi – deleting local images

To remove all images from our local machine:

k@laptop:~$ docker rmi $(docker images -q)

Saving container – docker commit

As we work with a container and continue to perform actions on it (install software, configure files etc.), to have it keep its state, we need to commit. Committing makes sure that everything continues from where they left next time.

Exit docker container:

root@f510d7bb05af:/# exit
exit

Then, we can save the image:

# Usage: sudo docker commit [container ID] [image name]
$ sudo docker commit f510d7bb05af my_image

Running CentOS on Ubuntu 14.04

As an exercise, we now want to run CentOS on Ubuntu 14.04.

Before running it, check if we have have any Docker container including running ones:

k@laptop:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

OK. There is no running Docker. How about any exited containers:

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

Nothings there!

Let’s search Docker registry:

k@laptop:~$ docker search centos
NAME                            DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
centos                          The official build of CentOS.                   1223      [OK]       
ansible/centos7-ansible         Ansible on Centos7                              50                   [OK]
jdeathe/centos-ssh-apache-php   CentOS-6 6.6 x86_64 / Apache / PHP / PHP m...   11                   [OK]
blalor/centos                   Bare-bones base CentOS 6.5 image                9                    [OK]
...

We can download the image using docker pull command. The command find the image by name on Docker Hub and download it from Docker Hub to a local image cache.

k@laptop:~$ docker pull centos
latest: Pulling from centos
c852f6d61e65: Pull complete 
7322fbe74aa5: Pull complete 
f1b10cd84249: Already exists 
Digest: sha256:90305c9112250c7e3746425477f1c4ef112b03b4abe78c612e092037bfecc3b7
Status: Downloaded newer image for centos:latest

Note that when the image is successfully downloaded, we see a 12 character hash: Download complete which is the short form of the image ID. These short image IDs are the first 12 characters of the full image ID – which can be found using docker inspect or docker images –no-trunc=true:

k@laptop:~$ docker inspect centos:latest
[
{
    "Id": "7322fbe74aa5632b33a400959867c8ac4290e9c5112877a7754be70cfe5d66e9",
    "Parent": "c852f6d61e65cddf1e8af1f6cd7db78543bfb83cdcd36845541cf6d9dfef20a0",
    "Comment": "",
    "Created": "2015-06-18T17:28:29.311137972Z",
    "Container": "d6b8ab6e62ce7fa9516cff5e3c83db40287dc61b5c229e0c190749b1fbaeba3f",
    "ContainerConfig": {
        "Hostname": "545cb0ebeb25",
        "Domainname": "",
        "User": "",
        "AttachStdin": false,
        "AttachStdout": false,
        "AttachStderr": false,
        "PortSpecs": null,
        "ExposedPorts": null,
        "Tty": false,
        "OpenStdin": false,
        "StdinOnce": false,
        "Env": null,
        "Cmd": [
            "/bin/sh",
            "-c",
            "#(nop) CMD [\"/bin/bash\"]"
        ],
        "Image": "c852f6d61e65cddf1e8af1f6cd7db78543bfb83cdcd36845541cf6d9dfef20a0",
        "Volumes": null,
        "VolumeDriver": "",
        "WorkingDir": "",
        "Entrypoint": null,
        "NetworkDisabled": false,
        "MacAddress": "",
        "OnBuild": null,
        "Labels": {}
    },
    "DockerVersion": "1.6.2",
    "Author": "The CentOS Project \u003ccloud-ops@centos.org\u003e - ami_creator",
    "Config": {
        "Hostname": "545cb0ebeb25",
        "Domainname": "",
        "User": "",
        "AttachStdin": false,
        "AttachStdout": false,
        "AttachStderr": false,
        "PortSpecs": null,
        "ExposedPorts": null,
        "Tty": false,
        "OpenStdin": false,
        "StdinOnce": false,
        "Env": null,
        "Cmd": [
            "/bin/bash"
        ],
        "Image": "c852f6d61e65cddf1e8af1f6cd7db78543bfb83cdcd36845541cf6d9dfef20a0",
        "Volumes": null,
        "VolumeDriver": "",
        "WorkingDir": "",
        "Entrypoint": null,
        "NetworkDisabled": false,
        "MacAddress": "",
        "OnBuild": null,
        "Labels": {}
    },
    "Architecture": "amd64",
    "Os": "linux",
    "Size": 0,
    "VirtualSize": 172237380
}
]

Or:

k@laptop:~$ docker images --no-trunc=true
REPOSITORY          TAG                 IMAGE ID                                                           CREATED             VIRTUAL SIZE
centos              latest              7322fbe74aa5632b33a400959867c8ac4290e9c5112877a7754be70cfe5d66e9   8 weeks ago         172.2 MB

k@laptop:~$ docker images --no-trunc=false

Or:

k@laptop:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
centos              latest              7322fbe74aa5        8 weeks ago         172.2 MB

Let’s run Docker with the image:

k@laptop:~$ docker run -it centos:latest /bin/bash
[root@33b55acb4814 /]# 

Now, we are on CentOS. Let’s make a file, and then just exit:

[root@33b55acb4814 /]# cd /home

[root@33b55acb4814 home]# touch bogo.txt

[root@33b55acb4814 home]# ls
bogo.txt

[root@33b55acb4814 home]# exit
exit

k@laptop:~$

Check if there is any running container:

k@laptop:~$ docker ps 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

Nothings’ there. The docker ps command shows only the running containers. So, if we want to see all containers, we need to add -a flag to the command:

k@laptop:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
33b55acb4814        centos:latest       "/bin/bash"         2 minutes ago       Exited (0) 51 seconds ago                       grave_jang          

We do not have any Docker process that’s actively running. But we can restart the one that we’ve just exited from.

$ docker restart 33b55acb4814
33b55acb4814

k@laptop:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
33b55acb4814        centos:latest       "/bin/bash"         4 minutes ago       Up 4 seconds                            grave_jang          

Note that the container is now running, and it actually executed the /bin/bash command.

We can go back to where we left by executing docker attach ContainerID command:

k@laptop:~$ docker attach 33b55acb4814

[root@33b55acb4814 /]# 

Now, we’re back. To make sure, we can check if there is the file we created:

[root@33b55acb4814 /]# cd /home
[root@33b55acb4814 home]# ls
bogo.txt
Posted in C++/Python

Standard Template Library (STL)

The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. A working knowledge of template classes is a prerequisite for working with STL.

STL has four components

  • Algorithms
  • Containers
  • Functions
  • Iterators

Algorithms

The header algorithm defines a collection of functions especially designed to be used on ranges of elements.They act on containers and provide means for various operations for the contents of the containers.

Containers

Containers or container classes store objects and data. There are in total seven standard โ€œfirst-classโ€ container classes and three container adaptor classes and only seven header files that provide access to these containers or container adaptors.

Functions

The STL includes classes that overload the function call operator. Instances of such classes are called function objects or functors. Functors allow the working of the associated function to be customized with the help of parameters to be passed.

Iterators

As the name suggests, iterators are used for working upon a sequence of values. They are the major feature that allow generality in STL.

Posted in C++/Python

File Handling

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.

Now the first step to open the particular file for read or write operation. We can open file by
1. passing file name in constructor at the time of object creation
2. using the open method
For e.g.

Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(โ€œfilenameโ€);

Open File by using open method
Calling of default constructor
ifstream fin;

fin.open(filename, openmode)
fin.open(โ€œfilenameโ€);

Modes :

MEMBER CONSTANTSTANDS FORACCESS
in *inputFile open for reading: the internal stream buffer supports input operations.
outoutputFile open for writing: the internal stream buffer supports output operations.
binarybinaryOperations are performed in binary mode rather than text.
ateat endThe output position starts at the end of the file.
appappendAll output operations happen at the end of the file, appending to its existing contents.
trunctruncateAny contents that existed in the file before it is open are discarded.

Default Open Modes :

ifstreamios::in
ofstreamios::out
fstreamios::in | ios::out

Below is the implementation by using fstream class.:

/* File Handling with C++ using ifstream & ofstream class object*/
/* To write the Content in File*/
/* Then to read the content of file*
#include <iostream>
/* fstream header file for ifstream, ofstream,  
fstream classes */
#include <fstream> 
using namespace std;

// Creation of ofstream class object
int main()
string line; 
ofstream fout;
// by default ios::out mode, automatically deletes 
// the content of file. To append the content, open in ios:app 
// fout.open("sample.txt", ios::app) 
fout.open("sample.txt"); 

// Execute a loop If file successfully opened 
while (fout) { 

    // Read a Line from standard input 
    getline(cin, line); 

    // Press -1 to exit 
    if (line == "-1") 
        break; 

    // Write line in file 
    fout << line << endl; 
} 

// Close the File 
fout.close(); 

// Creation of ifstream class object to read the file 
ifstream fin; 

// by default open mode = ios::in mode 
fin.open("sample.txt"); 

// Execute a loop until EOF (End of File) 
while (fin) { 

    // Read a Line from File 
    getline(fin, line); 

    // Print line in Console 
    cout << line << endl; 
} 

// Close the file 
fin.close(); 

return 0; 
Posted in Home

Exception Handling

Exception Handling in C++

One of the advantages of C++ over C is Exception Handling. Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. There are two types of exceptions: a)Synchronous, b)Asynchronous(Ex:which are beyond the programโ€™s control, Disc failure etc). C++ provides following specialized keywords for this purpose.
try: represents a block of code that can throw an exception.
catch: represents a block of code that is executed when a particular exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesnโ€™t handle itself.

Why Exception Handling? 
Following are main advantages of exception handling over traditional error handling.

1) Separation of Error Handling code from Normal Code: In traditional error handling codes, there are always if else conditions to handle errors. These conditions and the code to handle errors get mixed up with the normal flow. This makes the code less readable and maintainable. With try catch blocks, the code for error handling becomes separate from the normal flow.

2) Functions/Methods can handle any exceptions they choose: A function can throw many exceptions, but may choose to handle some of them. The other exceptions which are thrown, but not caught can be handled by caller. If the caller chooses not to catch them, then the exceptions are handled by caller of the caller. 
In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it)

Xแปญ lรฝ ngoแบกi lแป‡ trong C ++

Mแป™t trong nhแปฏng ฦฐu ฤ‘iแปƒm cแปงa C ++ so vแป›i C lร  Xแปญ lรฝ ngoแบกi lแป‡. Cรกc trฦฐแปng hแปฃp ngoแบกi lแป‡ lร  cรกc bแบฅt thฦฐแปng vแป thแปi gian chแบกy hoแบทc cรกc ฤ‘iแปu kiแป‡n bแบฅt thฦฐแปng mร  mแป™t chฦฐฦกng trรฌnh gแบทp phแบฃi trong quรก trรฌnh thแปฑc thi. Cรณ hai loแบกi ngoแบกi lแป‡: a) ฤแป“ng bแป™, b) Khรดng ฤ‘แป“ng bแป™ (Vรญ dแปฅ: nแบฑm ngoร i tแบงm kiแปƒm soรกt cแปงa chฦฐฦกng trรฌnh, Lแป—i ฤ‘ฤฉa, v.v.). C ++ cung cแบฅp cรกc tแปซ khรณa chuyรชn dแปฅng sau ฤ‘รขy cho mแปฅc ฤ‘รญch nร y.
try: ฤ‘แบกi diแป‡n cho mแป™t khแป‘i mรฃ cรณ thแปƒ nรฉm mแป™t ngoแบกi lแป‡.
catch: ฤ‘แบกi diแป‡n cho mแป™t khแป‘i mรฃ ฤ‘ฦฐแปฃc thแปฑc thi khi mแป™t ngoแบกi lแป‡ cแปฅ thแปƒ ฤ‘ฦฐแปฃc nรฉm ra.
nรฉm: Dรนng ฤ‘แปƒ nรฉm mแป™t ngoแบกi lแป‡. Cลฉng ฤ‘ฦฐแปฃc sแปญ dแปฅng ฤ‘แปƒ liแป‡t kรช cรกc ngoแบกi lแป‡ mร  mแป™t hร m nรฉm ra, nhฦฐng khรดng tแปฑ xแปญ lรฝ.

Tแบกi sao phแบฃi xแปญ lรฝ ngoแบกi lแป‡?
Sau ฤ‘รขy lร  nhแปฏng ฦฐu ฤ‘iแปƒm chรญnh cแปงa xแปญ lรฝ ngoแบกi lแป‡ so vแป›i xแปญ lรฝ lแป—i truyแปn thแป‘ng.

1) Tรกch mรฃ Xแปญ lรฝ lแป—i khแปi Mรฃ Thรดng thฦฐแปng: Trong cรกc mรฃ xแปญ lรฝ lแป—i truyแปn thแป‘ng, luรดn cรณ cรกc ฤ‘iแปu kiแป‡n nแบฟu khรกc ฤ‘แปƒ xแปญ lรฝ lแป—i. Cรกc ฤ‘iแปu kiแป‡n nร y vร  mรฃ ฤ‘แปƒ xแปญ lรฝ lแป—i bแป‹ trแป™n lแบซn vแป›i quy trรฌnh bรฌnh thฦฐแปng. ฤiแปu nร y lร m cho mรฃ รญt dแป… ฤ‘แปc vร  dแป… bแบฃo trรฌ hฦกn. Vแป›i khแป‘i try catch, mรฃ ฤ‘แปƒ xแปญ lรฝ lแป—i trแปŸ nรชn tรกch biแป‡t vแป›i quy trรฌnh bรฌnh thฦฐแปng.

2) Cรกc hร m / phฦฐฦกng thแปฉc cรณ thแปƒ xแปญ lรฝ bแบฅt kแปณ ngoแบกi lแป‡ nร o mร  chรบng chแปn: Mแป™t hร m cรณ thแปƒ ฤ‘ฦฐa ra nhiแปu ngoแบกi lแป‡, nhฦฐng cรณ thแปƒ chแปn xแปญ lรฝ mแป™t sแป‘ ngoแบกi lแป‡. Ngฦฐแปi gแปi cรณ thแปƒ xแปญ lรฝ cรกc trฦฐแปng hแปฃp ngoแบกi lแป‡ khรกc ฤ‘ฦฐแปฃc nรฉm nhฦฐng khรดng bแบฏt ฤ‘ฦฐแปฃc. Nแบฟu ngฦฐแปi gแปi chแปn khรดng bแบฏt chรบng, thรฌ cรกc trฦฐแปng hแปฃp ngoแบกi lแป‡ sแบฝ ฤ‘ฦฐแปฃc xแปญ lรฝ bแปŸi ngฦฐแปi gแปi cแปงa ngฦฐแปi gแปi.
Trong C ++, mแป™t hร m cรณ thแปƒ chแป‰ ฤ‘แป‹nh cรกc ngoแบกi lแป‡ mร  nรณ nรฉm bแบฑng tแปซ khรณa nรฉm. Ngฦฐแปi gแปi hร m nร y phแบฃi xแปญ lรฝ ngoแบกi lแป‡ theo mแป™t cรกch nร o ฤ‘รณ (bแบฑng cรกch chแป‰ ฤ‘แป‹nh lแบกi hoแบทc bแบฏt nรณ)

3) Nhรณm cรกc loแบกi lแป—i: Trong C ++, cแบฃ cรกc loแบกi cฦก bแบฃn vร  cรกc ฤ‘แป‘i tฦฐแปฃng ฤ‘แปu cรณ thแปƒ ฤ‘ฦฐแปฃc nรฉm ra nhฦฐ mแป™t ngoแบกi lแป‡. Chรบng ta cรณ thแปƒ tแบกo mแป™t hแป‡ thแป‘ng phรขn cแบฅp cรกc ฤ‘แป‘i tฦฐแปฃng ngoแบกi lแป‡, nhรณm cรกc ngoแบกi lแป‡ trong khรดng gian tรชn hoแบทc lแป›p, phรขn loแบกi chรบng theo cรกc kiแปƒu.

3) Grouping of Error Types: In C++, both basic types and objects can be thrown as exception. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.
 

Posted in C++/Python

Constructors & Destructors

What is constructor? 
A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object(instance of class) create. It is special member function of the class.
How constructors are different from a normal member function?

A constructor is different from normal functions in following ways: 

  • Constructor has same name as the class itself
  • Constructors donโ€™t have return type
  • A constructor is automatically called when an object is created.
  • If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).

Let us understand the types of constructors in C++ by taking a real-world example. Suppose you went to a shop to buy a marker. When you want to buy a marker, what are the options? The first one you go to a shop and say give me a marker. So just saying give me a marker mean that you did not set which brand name and which color, you didnโ€™t mention anything just say you want a marker. So when we said just I want a marker so whatever the frequently sold marker is there in the market or in his shop he will simply hand over that. And this is what a default constructor is! The second method you go to a shop and say I want a marker a red in color and XYZ brand. So you are mentioning this and he will give you that marker. So in this case you have given the parameters. And this is what a parameterized constructor is! Then the third one you go to a shop and say I want a marker like this(a physical marker on your hand). So the shopkeeper will see that marker. Okay, and he will give a new marker for you. So copy of that marker. And thatโ€™s what copy constructor is!
Types of Constructors

  1. Default Constructors: Default constructor is the constructor which doesnโ€™t take any argument. It has no parameters.

// Cpp program to illustrate the
// concept of Constructors

include using namespace std; class construct { public: int a, b; // Default Constructor construct() { a = 10; b = 20; } }; int main() { // Default constructor called automatically // when the object is created
Posted in Home

Object Oriented Programming

What are the main principles of Object-Oriented Programming?

The four principles of object-oriented programming are encapsulationabstractioninheritance,and polymorphism.

These words may sound scary for a junior developer. And the complex, excessively long explanations in Wikipedia sometimes double the confusion.

Thatโ€™s why I want to give a simple, short, and clear explanation for each of these concepts. It may sound like something you explain to a child, but I would actually love to hear these answers when I conduct an interview.

Encapsulation

Say we have a program. It has a few logically different objects which communicate with each other โ€” according to the rules defined in the program.

Encapsulation is achieved when each object keeps its state private, inside a class. Other objects donโ€™t have direct access to this state. Instead, they can only call a list of public functions โ€” called methods.

So, the object manages its own state via methods โ€” and no other class can touch it unless explicitly allowed. If you want to communicate with the object, you should use the methods provided. But (by default), you canโ€™t change the state.

Letโ€™s say weโ€™re building a tiny Sims game. There are people and there is a cat. They communicate with each other. We want to apply encapsulation, so we encapsulate all โ€œcatโ€ logic into a Catclass. It may look like this:

You can feed the cat. But you canโ€™t directly change how hungry the cat is.

Here the โ€œstateโ€ of the cat is the private variables moodhungry and energy. It also has a private method meow()It can call it whenever it wants, the other classes canโ€™t tell the cat when to meow.

What they can do is defined in the public methods sleep()play() and feed()Each of them modifies the internal state somehow and may invoke meow()Thus, the binding between the private state and public methods is made.

This is encapsulation.

Abstraction

Abstraction can be thought of as a natural extension of encapsulation.

In object-oriented design, programs are often extremely large. And separate objects communicate with each other a lot. So maintaining a large codebase like this for years โ€” with changes along the way โ€” is difficult.

Abstraction is a concept aiming to ease this problem.

Applying abstraction means that each object should only expose a high-level mechanism for using it.

This mechanism should hide internal implementation details. It should only reveal operations relevant for the other objects.

Think โ€” a coffee machine. It does a lot of stuff and makes quirky noises under the hood. But all you have to do is put in coffee and press a button.

Preferably, this mechanism should be easy to use and should rarely change over time. Think of it as a small set of public methods which any other class can call without โ€œknowingโ€ how they work.

Another real-life example of abstraction?
Think about how you use your phone:

Cell phones are complex. But using them is simple.

You interact with your phone by using only a few buttons. Whatโ€™s going on under the hood? You donโ€™t have to know โ€” implementation details are hidden. You only need to know a short set of actions.

Implementation changes โ€” for example, a software update โ€” rarely affect the abstraction you use.

Inheritance

OK, we saw how encapsulation and abstraction can help us develop and maintain a big codebase.

But do you know what is another common problem in OOP design?

Objects are often very similar. They share common logic. But theyโ€™re not entirely the same. Ughโ€ฆ

So how do we reuse the common logic and extract the unique logic into a separate class? One way to achieve this is inheritance.

It means that you create a (child) class by deriving from another (parent) class. This way, we form a hierarchy.

The child class reuses all fields and methods of the parent class (common part) and can implement its own (unique part).

For example:

A private teacher is a type of teacher. And any teacher is a type of Person.

If our program needs to manage public and private teachers, but also other types of people like students, we can implement this class hierarchy.

This way, each class adds only what is necessary for it while reusing common logic with the parent classes.

Polymorphism

Weโ€™re down to the most complex word! Polymorphism means โ€œmany shapesโ€ in Greek.

So we already know the power of inheritance and happily use it. But there comes this problem.

Say we have a parent class and a few child classes which inherit from it. Sometimes we want to use a collection โ€” for example a list โ€” which contains a mix of all these classes. Or we have a method implemented for the parent class โ€” but weโ€™d like to use it for the children, too.

This can be solved by using polymorphism.

Simply put, polymorphism gives a way to use a class exactly like its parent so thereโ€™s no confusion with mixing types.But each child class keeps its own methods as they are.

This typically happens by defining a (parent) interface to be reused. It outlines a bunch of common methods. Then, each child class implements its own version of these methods.

Any time a collection (such as a list) or a method expects an instance of the parent (where common methods are outlined), the language takes care of evaluating the right implementation of the common method โ€” regardless of which child is passed.

Take a look at a sketch of geometric figures implementation. They reuse a common interface for calculating surface area and perimeter:

Triangle, Circle, and Rectangle now can be used in the same collection

Having these three figures inheriting the parent Figure Interface lets you create a list of mixed trianglescircles, and rectangles. And treat them like the same type of object.

Then, if this list attempts to calculate the surface for an element, the correct method is found and executed. If the element is a triangle, triangleโ€™s CalculateSurface()is called. If itโ€™s a circle โ€” then cirlceโ€™s CalculateSurface()is called. And so on.

If you have a function which operates with a figure by using its parameter, you donโ€™t have to define it three times โ€” once for a triangle, a circle, and a rectangle.

You can define it once and accept a Figureas an argument. Whether you pass a triangle, circle or a rectangle โ€” as long as they implement CalculateParamter(), their type doesnโ€™t matter.

I hope this helped. You can directly use these exact same explanations at job interviews.

If you find something still difficult to understand โ€” donโ€™t hesitate to ask in the comments below.

Whatโ€™s next?

Being prepared to answer one of the all-time interview question classics is great โ€” but sometimes you never get called for an interview.

Next, Iโ€™ll focus on what employers want to see in a junior developer and how to stand out from the crowd when job hunting.

Stay tuned.

Posted in Home

Pointers & References

Pointers store address of variables or a memory location.

// General syntax
datatype *var_name; 

// An example pointer "ptr" that holds
// address of an integer variable or holds
// address of a memory whose value(s) can
// be accessed as integer values through "ptr"
int *ptr;  

Using a Pointer:

To use pointers in C, we must understand below two operators.

  • To access address of a variable to a pointer, we use the unary operator (ampersand) that returns the address of that variable. For example &x gives us address of variable x.
// The output of this program can be different 
// in different runs. Note that the program 
// prints address of a variable and a variable 
// can be assigned different address in different 
// runs. 
#include <stdio.h> 

int main() 
// Prints address of x 
printf("%p", &x); 

return 0; 
}
  • One more operator is unary * (Asterisk) which is used for two things :
    • To declare a pointer variable: When a pointer variable is declared in C/C++, there must be a * before its name.
// C program to demonstrate declaration of 
// pointer variables. 
#include <stdio.h> 
int main() 
{ 
    int x = 10; 
// 1) Since there is * in declaration, ptr 
// becomes a pointer varaible (a variable 
// that stores address of another variable) 
// 2) Since there is int before *, ptr is 
// pointer to an integer type variable 
int *ptr; 

// & operator before x is used to get address 
// of x. The address of x is assigned to ptr. 
ptr = &x; 

return 0; 
}
  • To access the value stored in the address we use the unary operator (*) that returns the value of the variable located at the address specified by its operand. This is also called Dereferencing.
Posted in Home

Function in C++

A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is such that each function performs a specific task.

A function declaration tells the compiler about a function’s name, return type, and parameters. A function definition provides the actual body of the function.

The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.

A function is known with various names like a method or a sub-routine or a procedure etc.

Defining a Function

The general form of a C++ function definition is as follows โˆ’

return_type function_name( parameter list ) {
   body of the function
}

A C++ function definition consists of a function header and a function body. Here are all the parts of a function โˆ’

  • Return Type โˆ’ A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
  • Function Name โˆ’ This is the actual name of the function. The function name and the parameter list together constitute the function signature.
  • Parameters โˆ’ A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
  • Function Body โˆ’ The function body contains a collection of statements that define what the function does.

Example

Following is the source code for a function called max(). This function takes two parameters num1 and num2 and return the biggest of both โˆ’

// function returning the max between two numbers
 
int max(int num1, int num2) {
   // local variable declaration
   int result;
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
}

Function Declarations

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

A function declaration has the following parts โˆ’

return_type function_name( parameter list );

For the above defined function max(), following is the function declaration โˆ’

int max(int num1, int num2);

Parameter names are not important in function declaration only their type is required, so following is also valid declaration โˆ’

int max(int, int);

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Calling a Function

While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.

When a program calls a function, program control is transferred to the called function. A called function performs defined task and when itโ€™s return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example โˆ’Live Demo

#include <iostream>
using namespace std;
 
// function declaration
int max(int num1, int num2);
 
int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
   int ret;
 
   // calling a function to get max value.
   ret = max(a, b);
   cout << "Max value is : " << ret << endl;
 
   return 0;
}
 
// function returning the max between two numbers
int max(int num1, int num2) {
   // local variable declaration
   int result;
 
   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
}

I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result โˆ’

Max value is : 200

Function Arguments

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function โˆ’

Sr.NoCall Type & Description
1Call by ValueThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
2Call by PointerThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
3Call by ReferenceThis method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

Default Values for Parameters

When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function.

This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead. Consider the following example โˆ’Live Demo

#include <iostream>
using namespace std;
 
int sum(int a, int b = 20) {
   int result;
   result = a + b;
  
   return (result);
}
int main () {
   // local variable declaration:
   int a = 100;
   int b = 200;
   int result;
 
   // calling a function to add the values.
   result = sum(a, b);
   cout << "Total value is :" << result << endl;

   // calling a function again as follows.
   result = sum(a);
   cout << "Total value is :" << result << endl;
 
   return 0;
}

When the above code is compiled and executed, it produces the following result โˆ’

Total value is :300
Total value is :120

Hร m trong C++

Mแป™t hร m lร  mแป™t nhรณm cรกc cรขu lแป‡nh cรนng nhau thแปฑc hiแป‡n mแป™t nhiแป‡m vแปฅ. Mแป—i chฦฐฦกng trรฌnh C++ cรณ รญt nhแบฅt mแป™t hร m, lร  hร mย main().

Bแบกn cรณ thแปƒ chia mรฃ cแปงa bแบกn thร nh cรกc hร m riรชng biแป‡t. Cรกch bแบกn phรขn chia mรฃ cแปงa bแบกn giแปฏa cรกc hร m khรกc nhau tรนy thuแป™c vร o bแบกn, nhฦฐng vแป mแบทt logic mแป—i hร m thแปฑc hiแป‡n mแป™t tรกc vแปฅ cแปฅ thแปƒ.

Mแป™t khai bรกo hร m cho trรฌnh biรชn dแป‹ch biแบฟt vแป tรชn, kiแปƒu trแบฃ vแป vร  cรกc tham sแป‘ cแปงa hร m. ฤแป‹nh nghฤฉa hร m cung cแบฅp phแบงn thรขn thแปฑc cแปงa hร m.

Thฦฐ viแป‡n chuแบฉn C++ cung cแบฅp nhiแปu hร m ฤ‘ฦฐแปฃc tรญch hแปฃp sแบตn mร  chฦฐฦกng trรฌnh cแปงa bแบกn cรณ thแปƒ gแปi. Vรญ dแปฅ, strcat() ฤ‘แปƒ nแป‘i hai chuแป—i, memcpy() ฤ‘แปƒ sao chรฉp mแป™t vแป‹ trรญ bแป™ nhแป› sang mแป™t vแป‹ trรญ khรกc vร  nhiแปu hร m khรกc.

Hร m trong C++ cรฒn ฤ‘ฦฐแปฃc gแปi lร  thแปง tแปฅc hoแบทc chฦฐฦกng trรฌnh con trong cรกc ngรดn ngแปฏ lแบญp trรฌnh khรกc.

ฤแปƒ thแปฑc hiแป‡n bแบฅt kแปณ tรกc vแปฅ nร o, chรบng ta cรณ thแปƒ tแบกo ra cรกc hร m. Mแป™t hร m cรณ thแปƒ ฤ‘ฦฐแปฃc gแปi nhiแปu lแบงn. Nรณ cung cแบฅp tรญnh mรด ฤ‘un vร  khแบฃ nฤƒng sแปญ dแปฅng lแบกi mรฃ. Hร m giรบp phรขn chia vแบฅn ฤ‘แป phแปฉc tแบกp thร nh cรกc thร nh phแบงn nhแป giรบp chฦฐฦกng trรฌnh dแป… hiแปƒu vร  dแป… sแปญ dแปฅng.


Lแปฃi thแบฟ cแปงa cรกc hร m trong C++

1. Tรกi sแปญ dแปฅng mรฃ

Bแบฑng cรกch tแบกo cรกc hร m trong C++, bแบกn cรณ thแปƒ gแปi nรณ nhiแปu lแบงn. Vรฌ vแบญy, bแบกn khรดng cแบงn phแบฃi viแบฟt cรนng mแป™t mรฃ mแป™t hoแบทc nhiแปu lแบงn nแปฏa.

2. Tแป‘i ฦฐu hรณa mรฃ

Nรณ lร m cho mรฃ ฤ‘ฦฐแปฃc tแป‘i ฦฐu hรณa, chรบng ta khรดng cแบงn phแบฃi viแบฟt nhiแปu mรฃ.

Giแบฃ sแปญ, bแบกn phแบฃi kiแปƒm tra 3 sแป‘ (531, 883 vร  781) cรณ phแบฃi lร  sแป‘ nguyรชn tแป‘ hay khรดng. Khรดng sแปญ dแปฅng hร m, bแบกn cแบงn viแบฟt logic sแป‘ nguyรชn tแป‘ 3 lแบงn. Vรฌ vแบญy, cรณ sแปฑ lแบทp lแบกi cแปงa mรฃ.

Nhฦฐng nแบฟu bแบกn sแปญ dแปฅng cรกc hร m, bแบกn chแป‰ cแบงn viแบฟt logic mแป™t lแบงn vร  bแบกn cรณ thแปƒ sแปญ dแปฅng lแบกi nรณ nhiแปu lแบงn.



ฤแป‹nh nghฤฉa mแป™t hร m

Dแบกng chung cแปงa ฤ‘แป‹nh nghฤฉa hร m trong C++ nhฦฐ sau:

return_type function_name(parameter list) {
    // code
}

ฤแป‹nh nghฤฉa hร m trong lแบญp trรฌnh C++ bao gแป“m tรชn hร m vร  phแบงn thรขn hร m . Dฦฐแป›i ฤ‘รขy lร  tแบฅt cแบฃ cรกc phแบงn cแปงa hร m:

  • Kiแปƒu trแบฃ vแป: Mแป™t hร m cรณ thแปƒ trแบฃ vแป mแป™t giรก trแป‹. Cรกc return_type lร  kiแปƒu dแปฏ liแป‡u cแปงa giรก trแป‹ hร m trแบฃ vแป. Mแป™t sแป‘ hร m thแปฑc hiแป‡n cรกc hoแบกt ฤ‘แป™ng mong muแป‘n mร  khรดng trแบฃ vแป mแป™t giรก trแป‹. Trong trฦฐแปng hแปฃp nร y, return_type lร  tแปซ khรณa void.
  • Tham sแป‘: Mแป™t tham sแป‘ giแป‘ng nhฦฐ mแป™t trรฌnh giแปฏ chแป—. Khi mแป™t hร m ฤ‘ฦฐแปฃc gแปi, bแบกn chuyแปƒn mแป™t giรก trแป‹ cho tham sแป‘. Giรก trแป‹ nร y ฤ‘ฦฐแปฃc gแปi lร  tham sแป‘ hoแบทc ฤ‘แป‘i sแป‘ thแปฑc tแบฟ. Danh sรกch tham sแป‘ tham chiแบฟu ฤ‘แบฟn loแบกi, thแปฉ tแปฑ vร  sแป‘ tham sแป‘ cแปงa hร m. Cรกc tham sแป‘ lร  tรนy chแปn; cรณ nghฤฉa lร , mแป™t hร m cรณ thแปƒ khรดng chแปฉa tham sแป‘.
  • Thรขn hร m: Phแบงn thรขn hร m chแปฉa mแป™t tแบญp hแปฃp cรกc cรขu lแป‡nh xรกc ฤ‘แป‹nh chแปฉc nฤƒng cแปงa hร m.

Vรญ dแปฅ hร m trong C++

Vรญ dแปฅ dฦฐแป›i ฤ‘รขy lร  mรฃ nguแป“n cho mแป™t hร m ฤ‘ฦฐแปฃc gแปi lร  max(). Hร m nร y truyแปn vร o hai tham sแป‘ num1 vร  num2 vร  trแบฃ vแป giรก trแป‹ lแป›n nhแบฅt giแปฏa hai tham sแป‘:

/* hร m trแบฃ vแป giรก trแป‹ lแป›n nhแบฅt giแปฏa 2 sแป‘ */
int max(int num1, int num2) {
 
   /* khai bรกo biแบฟn local */
   int result;
  
   if (num1 > num2)
      result = num1;
   else
      result = num2;
  
   return result; 
}

Khai bรกo hร m trong C++

Mแป™t khai bรกo hร m cho trรฌnh biรชn dแป‹ch biแบฟt vแป tรชn hร m vร  cรกch gแปi hร m. Cฦก thแปƒ thแปฑc tแบฟ cแปงa hร m cรณ thแปƒ ฤ‘ฦฐแปฃc ฤ‘แป‹nh nghฤฉa riรชng.

Mแป™t khai bรกo hร m cรณ cรกc phแบงn sau:

return_type function_name(parameter list);

ฤแป‘i vแป›i hร m ฤ‘ฦฐแปฃc ฤ‘แป‹nh nghฤฉa แปŸ trรชn max (), khai bรกo hร m nhฦฐ sau:

int max(int num1, int num2);

Tรชn tham sแป‘ khรดng quan trแปng trong khai bรกo hร m chแป‰ loแบกi cแปงa chรบng lร  bแบฏt buแป™c, vรฌ vแบญy sau ฤ‘รขy cลฉng lร  khai bรกo hแปฃp lแป‡:

int max(int, int);

Khai bรกo hร m lร  bแบฏt buแป™c khi bแบกn ฤ‘แป‹nh nghฤฉa mแป™t hร m trong mแป™t tแป‡p nguแป“n vร  bแบกn gแปi hร m ฤ‘รณ trong mแป™t tแป‡p khรกc. Trong trฦฐแปng hแปฃp nร y, bแบกn nรชn khai bรกo hร m แปŸ ฤ‘แบงu tแป‡p gแปi hร m.


Gแปi mแป™t hร m trong C++

Hร m trong lแบญp trรฌnh C++ hoแบกt ฤ‘แป™ng nhฦฐ thแบฟ nร o? Hรฌnh แบฃnh sau ฤ‘รขy mรด tแบฃ gแปi mแป™t hร m do ngฦฐแปi dรนng ฤ‘แป‹nh nghฤฉa bรชn trong hร m main():

Hร m trong C++

Trong khi tแบกo mแป™t hร m C, bแบกn ฤ‘ฦฐa ra mแป™t ฤ‘แป‹nh nghฤฉa vแป chแปฉc nฤƒng cแปงa hร m. ฤแปƒ sแปญ dแปฅng mแป™t hร m, bแบกn sแบฝ phแบฃi gแปi hร m ฤ‘รณ ฤ‘แปƒ thแปฑc hiแป‡n tรกc vแปฅ ฤ‘ฦฐแปฃc xรกc ฤ‘แป‹nh.

Khi mแป™t chฦฐฦกng trรฌnh gแปi mแป™t hร m, ฤ‘iแปu khiแปƒn chฦฐฦกng trรฌnh ฤ‘ฦฐแปฃc chuyแปƒn ฤ‘แบฟn hร m ฤ‘ฦฐแปฃc gแปi. Mแป™t hร m ฤ‘ฦฐแปฃc gแปi thแปฑc hiแป‡n mแป™t nhiแป‡m vแปฅ ฤ‘รฃ ฤ‘แป‹nh nghฤฉa vร  khi cรขu lแป‡nh trแบฃ vแป cแปงa nรณ ฤ‘ฦฐแปฃc thแปฑc hiแป‡n hoแบทc khi nรณ kแบฟt thรบc bแบฑng hร m ฤ‘รณng, nรณ sแบฝ trแบฃ vแป chฦฐฦกng trรฌnh ฤ‘iแปu khiแปƒn quay trแปŸ lแบกi chฦฐฦกng trรฌnh chรญnh.

ฤแปƒ gแปi mแป™t hร m, bแบกn chแป‰ cแบงn chuyแปƒn cรกc tham sแป‘ bแบฏt buแป™c cรนng vแป›i tรชn hร m vร  nแบฟu hร m trแบฃ vแป mแป™t giรก trแป‹, thรฌ bแบกn cรณ thแปƒ lฦฐu trแปฏ giรก trแป‹ trแบฃ vแป. Vรญ dแปฅ:

#include <iostream>
 
using namespace std;
  
/* khai bao ham */
int max(int num1, int num2);
  
int main () {
 
   /* dinh nghia bien local */
   int a = 100;
   int b = 200;
   int ret;
  
   /* goi mot ham de lay gia tri lon nhat */
   ret = max(a, b);
  
   cout << "Max value is: " << ret << endl;
  
   return 0;
}
  
/* ham tra ve gia tri lon nhat giua hai so */
int max(int num1, int num2) {
 
   /* dinh nghia bien local */
   int result;
  
   if (num1 > num2)
      result = num1;
   else
      result = num2;
  
   return result; 
}

Kแบฟt quแบฃ:

Max value is : 200