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
Posted in Home

String

String Class in C++

There is no native โ€œstringโ€ data type in C++ but its <string> library class provides a string object that emulates a string data type. To make this available to a program, the library must be added with an #include <string> directive at the start of the program.

#include<iostream>
#include<string.h>using namespace std;
int main()
{
char str[50];
int len;
cout << "Enter an array or string : ":
gets(str);
len = strlen(str);
cout << "Length of the string is : " << len;
return 0;
}

Like the <iostream> class library, the <string> library is part of the std namespace that is used by the C++ standard library classes. That means that a string object can be referred to as std::string, or more simply as string when using namespace std; again the directive must be at the start of the program.

Initializing Strings

A string โ€œvariableโ€ can be declared in the same way as other variables. The declaration may optionally initialized the variable using the = assignment operator, or it may be initialized later in the programAdditionally a string variable may be initialized by including a text string between parentheses after the variable name.

Text strings in C++ must always be enclosed with double quotes(โ€œโ€).
Single quotes (โ€˜โ€™) are only used for character values of the char data type.

Any numeric values that are assigned to a string variable, are no longer a numeric data type, so attempting to add string values of โ€œ4โ€ and โ€œ5โ€ with the addition operator(+) would add up to โ€œ45โ€ instead of 9.

Converting Strings to other Data Types

Arithmetic cannot be performed on numeric values assigned to string variables until they are converted to a numeric data type. Luckily, there is a C++ย <sstream>ย library provides a โ€œstringstreamโ€ object that acts as an intermediary to convert strings to other data types.

Other features of a string variable can be revealed by calling its size()capacity(), and empty() functions. Written below is short summary of other features.

  • string variable can be emptied by assigning it an empty string (=โ€œโ€) or by calling its clear() function.
  • Multiple string values can be concatenated by the + operator
  • string can be can be appended to another string by the += operator or by calling its append() function.
  • string can be compared to another string by the == operator or by calling its append() function.
  • string can be assigned to a string variable using the = operator or by calling its assign() function.
  • The swap() function swaps the values of two string variables.
  • Substrings of a string can be sought with the find() function, or specialized functions such as find_first_of(), and a character retrieved from a specified index position by the at() function.

Next we will be focusing more on control structure of the flow such as while loops, do-while loops, and for loops in addition to using the switch case for complex conditional tests.

Posted in Home

Array

Whatโ€™s in an Array?

An array is a variable that can store multiple items of data unlike a regular variable that stores one pierce of data. Just like any variable, arrays must be declared before they can be accessed.

Initializing Arrays

You can initialize a simple array of built-in types, like integers (int) or characters (char), when you first declare the array. After the array name, put an equal sign and a list of comma separated values enclosed in the braces.

int nums[10] = { 0, 10, 20, 30, 40, 50, 60 ,70, 80, 90 }; 

This declared nums to be an array of 10 integers. Remember that the data are stored sequentially in array are elements that are numbered starting at zero. So nums[0] equals to 0, nums[1] equals to 10, and so on.

Arrays can be created for any data type but each element may only contain data of the same data type.

Inserting and Printing Elements

int mike[5] = {19, 10, 8, 17, 9}// change 4th element to 9
mike[3] = 9;// take input from the user and insert in third element
cin >> mike[2];// take input from the user and insert in (i+1)th element
cin >> mike[i];// print first element of the array
cout << mike[0];// print ith element of the array
cout >> mike[i-1];

Character Arrays

An array of characters can be used to store a string of text if the final elements contains the special \0 null character. For example:

char name[5] = {'p', 'n', 'o', 'p', '\0'};

Because this character-by-character approach is difficult to type and admits too many opportunities for error, C++ enables a shorthand form of string initialization using a literal:

char name[] = "pnop";

This form of initialization doesnโ€™t require the null character; the compiler adds it automatically. The string โ€œpnopโ€ is 5 bytes including null.

Multidimensial Arrays

Collectively elements in an array is known as an index. Arrays can have more than one index. Arrays are suitable for data that consists of a known number of elements like a chessboard or coordinates which would be good examples in need of a two dimensional array.

For example:

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

A three-dimensional array has three subscripts:

int cube[5,13,8];

Run the program below to see the output.

https://repl.it/join/hxlyjcst-thanhnguyen91

C-Style Character String

C++ supports a wide range of functions that can manipulate null-terminated strings. The header file <cstring> defines several functions to manipulate C strings and arrays.

โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฆโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘ Keyword โ•‘ Functions and Purpose โ•‘
โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฌโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ
โ•‘ strcpy(s1,s2) โ•‘ copies string s2 into string s1. โ•‘ โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฌโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ
โ•‘ strcat(s1,s2) โ•‘ concatenates string s2 onto the end of โ•‘
โ•‘ โ•‘ string s1. โ•‘
โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฌโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ
โ•‘ strlen(s1) โ•‘ Returns the length of string s1; โ•‘ โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฌโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ
โ•‘ strcmp(s1,s2) โ•‘ Returns 0 if s1 and s2 are the same; โ•‘
โ•‘ โ•‘ less than 0 if s1<s2; greater than 0 if โ•‘ โ•‘ โ•‘ if s1>s2. โ•‘
โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฌโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ
โ•‘ strchr(s1,ch) โ•‘ Returns a pointer to the first occurrence โ•‘ โ•‘ โ•‘ of character ch in string s1. โ•‘
โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฌโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ
โ•‘ strstr(s1,s2) โ•‘ Returns a pointer to the first string s2 โ•‘
โ•‘ โ•‘ in string s1. โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฉโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

The header file <cstring> defines several functions to manipulateย C stringsย and arrays.

Posted in C++/Python

Operator

Operators are the foundation of any programming language. Thus the functionality of C/C++ programming language is incomplete without the use of operators. We can define operators as symbols that help us to perform specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands.
For example, consider the below statement:

c = a + b;

Here, โ€˜+โ€™ is the operator known as addition operator and โ€˜aโ€™ and โ€˜bโ€™ are operands. The addition operator tells the compiler to add both of the operands โ€˜aโ€™ and โ€˜bโ€™.

C/C++ has many built-in operator types and they are classified as follows:

  1. Arithmetic Operators: These are the operators used to perform arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %,++,โ€“). Arithmetic operator are of two types:
    1. Unary Operators: Operators that operates or works with a single operand are unary operators. For example: (++ , โ€“)
    2. Binary Operators: Operators that operates or works with two operands are binary operators. For example: (+ , โ€“ , * , /)
    To learn Arithmetic Operators in details visit this link.
  2. Relational Operators: These are used for comparison of the values of two operands. For example, checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not etc. Some of the relational operators are (==, >= , <= ). To learn about each of these operators in details go to this link.
  3. Logical Operators:  Logical Operators are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a boolean value either true or false. For example, the logical AND represented as โ€˜&&โ€™ operator in C or C++ returns true when both the conditions under consideration are satisfied. Otherwise it returns false. Therfore, a && b returns true when both a and b are true (i.e. non-zero). To learn about different logical operators in details please visit this link.
  4. Bitwise Operators: The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. The mathematical operations such as addition, subtraction, multiplication etc. can be performed at bit-level for faster processing. For example, the bitwise AND represented as & operator in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. To learn bitwise operators in details, visit this link.
  5. Assignment Operators: Assignment operators are used to assign value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of variable on the left side otherwise the compiler will raise an error.
    Different types of assignment operators are shown below:
    1. โ€œ=โ€: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.
      For example:a = 10; b = 20; ch = ‘y’;
    2. โ€œ+=โ€: This operator is combination of โ€˜+โ€™ and โ€˜=โ€™ operators. This operator first adds the current value of the variable on left to the value on right and then assigns the result to the variable on the left.
      Example:(a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11.
    3. โ€œ-=โ€: This operator is combination of โ€˜-โ€˜ and โ€˜=โ€™ operators. This operator first subtracts the value on right from the current value of the variable on left and then assigns the result to the variable on the left.
      Example:(a -= b) can be written as (a = a – b) If initially value stored in a is 8. Then (a -= 6) = 2.
    4. โ€œ*=โ€: This operator is combination of โ€˜*โ€™ and โ€˜=โ€™ operators. This operator first multiplies the current value of the variable on left to the value on right and then assigns the result to the variable on the left.
      Example:(a *= b) can be written as (a = a * b) If initially value stored in a is 5. Then (a *= 6) = 30.
    5. โ€œ/=โ€: This operator is combination of โ€˜/โ€™ and โ€˜=โ€™ operators. This operator first divides the current value of the variable on left by the value on right and then assigns the result to the variable on the left.
      Example:(a /= b) can be written as (a = a / b) If initially value stored in a is 6. Then (a /= 2) = 3.
  6. Other Operators: Apart from the above operators there are some other operators available in C or C++ used to perform some specific task. Some of them are discussed here:
    1. sizeof operator: sizeof is a much used in the C/C++ programming language. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t. Basically, sizeof operator is used to compute the size of the variable. To learn about sizeof operator in details you may visit this link.
    2. Comma Operator: The comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator. Comma acts as both operator and separator. To learn about comma in details visit this link.
    3. Conditional Operator: Conditional operator is of the form Expression1 ? Expression2 : Expression3 . Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the result of Expression2 otherwise if the condition(Expression1) is false then we will execute and return the result of Expression3. We may replace the use of if..else statements by conditional operators. To learn about conditional operators in details, visit this link.

Operator precedence chart

The below table describes the precedence order and associativity of operators in C / C++ . Precedence of operator decreases from top to bottom.

OPERATORDESCRIPTIONASSOCIATIVITY
()Parentheses (function call)left-to-right
[]Brackets (array subscript)
.Member selection via object name
->Member selection via pointer
++/โ€“Postfix increment/decrement
++/โ€“Prefix increment/decrementright-to-left
+/-Unary plus/minus
!~Logical negation/bitwise complement
(type)Cast (convert value to temporary value of type)
*Dereference
&Address (of operand)
sizeofDetermine size in bytes on this implementation
*,/,%Multiplication/division/modulusleft-to-right
+/-Addition/subtractionleft-to-right
<< , >>Bitwise shift left, Bitwise shift rightleft-to-right
< , <=Relational less than/less than or equal toleft-to-right
> , >=Relational greater than/greater than or equal toleft-to-right
== , !=Relational is equal to/is not equal toleft-to-right
&Bitwise ANDleft-to-right
^Bitwise exclusive ORleft-to-right
|Bitwise inclusive ORleft-to-right
&&Logical ANDleft-to-right
||Logical ORleft-to-right
?:Ternary conditionalright-to-left
=Assignmentright-to-left
+= , -=Addition/subtraction assignment
*= , /=Multiplication/division assignment
%= , &=Modulus/bitwise AND assignment
^= , |=Bitwise exclusive/inclusive OR assignment
<>=Bitwise shift left/right assignment
,expression separatorleft-to-right
Posted in C++/Python

Basic Input/Output

In C, we could use the function freopen() to redirect an existing FILE pointer to another stream. The prototype for freopen() is given as

FILE * freopen ( const char * filename, const char * mode, FILE * stream );

For Example to redirect the stdout to say a textfile, we could write

freopen ("text_file.txt", "w", stdout);

While this method is still supported in C++, this article discusses another way to redirect I/O streams.

C++ being an object-oriented programming language gives us the ability to not only define our own streams but also redirect standard streams. Thus in C++, a stream is an object whose behavior is defined by a class. Thus anything that behaves like a stream is also a stream.

Streams Objects in C++ are mainly of three types :

  • istream : Stream object of this type can only perform input operations from the stream
  • ostream : These objects can only be used for output operations.
  • iostream : Can be used for both input and output operations

All these classes, as well as file stream classes, derive from the classes: ios and streambuf. Thus filestream and IO stream objects behave similarly.

All stream objects also have an associated data member of class streambuf. Simply put streambuf object is the buffer for the stream. When we read data from a stream, we donโ€™t read it directly from the source, but instead, we read it from the buffer which is linked to the source. Similarly, output operations are first performed on the buffer, and then the buffer is flushed (written to the physical device) when needed.

C++ allows us to set the stream buffer for any stream. So the task of redirecting the stream simply reduces to changing the stream buffer associated with the stream. Thus the to redirect a Stream A to Stream B we need to do

  1. Get the stream buffer of A and store it somewhere
  2. Set the stream buffer of A to the stream buffer of B
  3. If needed reset the stream buffer of A to its previous stream buffer

We can use the function ios::rdbuf() to perform two opeations.

1) stream_object.rdbuf(): Returns pointer to the stream buffer of stream_object
2) stream_object.rdbuf(streambuf * p): Sets the stream buffer to the object pointed by p

Posted in Robotics

Humanoid Robot

Changing the Face of Education, Here and NAO.

According to inventor and artist Leonardo Da Vinci โ€˜Learning Never Exhausts the Mindโ€™ and over the past decade here at SoftBank Robotics we have found that to be consistently true.

NAO History

Image for post

In 2004 Aldebaran Robotics (Now SoftBank Robotics) launched project NAO which over time has come to revolutionize the way humans and robots interact with each other. NAO is a 58cm tall humanoid robot that is continuously evolving to help support humans in all their endeavors.

Capabilities

NAOโ€™s abilities range from facial recognition, learning from past conversations to automated movement. NAO has already shown his more advanced capabilities through concierging at hotels, aided researchers in over 70 different institutions.

In Education

Image for post

Most recently, NAO has been put to use in multiple South Australian schools; there NAO supports teachers, challenges students and is changing the way they interact. Monica Williams, a researcher from The Association of Independent Schools of South Australia noted that โ€œWhat surprised the director was the depth of the studentsโ€™ understanding and that once the teachers opened up to working with the students on the robot they continually saw things that surprised all of us as to what students were capable ofโ€. Additionally, these schools found that both boys and girls were equally captivated by NAO and even began learning how to code for NAO using Python, an industry standard. Similarly, with the help of Choreographe and multiple licenses provided for schools, students can work with a virtual NAO as they take turns working with the actual NAO which encourages each student to learn at their own pace.

NAO has also been hard at work in the special education field, supporting students in developing skills like turn taking, spontaneous communication and social interaction with NAO and others.

Through the years, NAO has proven that whether you are a teacher wanting to empower your students, a hotel in need of a concierge or a student who could use a helping hand, NAO will be there for you, with capabilities that surprise and engage people.

NAO is more than just a robot, NAO can connect with real people and has the ability to become a core part of a community. Like us, NAO will keep developing and learning and if his time in Australia shows us anything, it is that NAOโ€™s mind is far from exhausted.

Posted in DevOps

Ansible/Chef

Up till now, we have looked in Terraform for infrastructure provisioning and initial setup using provisioners. Now letโ€™s look at ansible which is an open source automation platform. Ansible does configuration management, application deployment, along with infrastructure orchestration. Ansible is procedural rather than declarative. In ansible, we define what we want to do and ansible go through each and every step for that. In terraform, we specify what state we want to achieve and it makes sure we are at that state by creating, modifying or destroying needed resources. Ansible doesnโ€™t manage any state so we need to define how we want to keep track of created resources using tags or other properties while terraform keeps the state of infrastructure so we donโ€™t need to worry about duplicate resource creation. Personally, I recommend terraform for provisioning the infrastructure, and Ansible for configuring the software as terraform is much more intuitive for infrastructure orchestration.

Once upon a time, managing servers reliably and efficiently was a challenge. System administrators managed server by hand, installing software manually, changing configuration and managing services on servers. As managed servers grew and managed services become more complex, scaling manual process was time-consuming and hard. Then came Ansible which is helpful in creating the group of machines, define how to configure them, what action to be taken on them. All these configurations and actions can be triggered from a central location which can be your local system (named controller machine). Ansible uses SSH to connect to remote hosts and do the setup, no software needed to be installed beforehand on a remote host. Itโ€™s simple, agentless, powerful and flexible. It uses YAML in form of ansible playbook. Playbook is a file where automation is defined through tasks. A task is a single step to be performed like installing a package.

Ansible works by connecting to remote hosts (using SSH) defined in inventory file, which contains information about servers to be managed. Ansible then executes defined modules or tasks inside a playbook. Execution of playbook which is called the play. We can use predefined organised playbook called roles, which are used for sharing and reusing a provisioning.

Letโ€™s have a look at some of the terminology used in ansible:

  1. Controller Machine: Machine where Ansible is installed
  2. Inventory: Information regarding servers to be managed
  3. Playbook: Automation is defined using tasks defined in YAML format
  4. Task: Procedure to be executed
  5. Module: Predefined commands executed directly on remote hosts
  6. Play: Execution of a playbook
  7. Role: a Pre-defined way for organizing playbooks
  8. Handlers: Tasks with unique names that will only be executed if notified by another task

As I am using Mac OS, so will be installing pip first using easy_install and then ansible using pip. Please look here to install for other platforms.

sudo easy_install pipsudo pip install ansible

Once above command executed, run command below to make sure that ansible is installed properly.

ansible --version

The output should be something like below.

ansible 2.5.3
config file = None
configured module search path = [u'/Users/mitesh/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /Library/Python/2.7/site-packages/ansible
executable location = /usr/local/bin/ansible
python version = 2.7.10 (default, Oct 6 2017, 22:29:07) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)]

Ansible reads the ssh keys form ~/.ssh/id_rsa. We need to make sure we have public key setup on all remote hosts as we already done using terraform while creation of a remote EC2 instance.

For running ansible command, we need inventory file which is expected to be at a specified path: โ€œ/etc/ansible/hostsโ€. We can change its path using ansible config file (ansible.cfg file) in ansible workspace and define inventory file path there. We need to define username which we are going to use during ssh in ansible config file.

File: ansible.cfg
[defaults]
inventory = ./inventory
remote_user = ec2-user

Create an inventory file and add the IP address (dummy)of a remote host.

File: inventory
[all]
18.191.176.209[server]
18.191.176.209

Once this is done, letโ€™s execute below command to ping all given remote host.

ansible all -m ping

Ansible executes ping command to a remote host and gives below output:

18.191.176.209 | SUCCESS => {
"changed": false,
"ping": "pong"
}

We can even create groups in the inventory file and execute ansible commands by replacing all with a group name. In below example, the server is our group name specified in the inventory file.

ansible server -m ping

Letโ€™s look at playbooks to execute a series of actions. We need to make sure we define playbooks as idempotent so that they can run more than once without having any side effects. Ansible executes playbook in a sequential manner from top to bottom.

Sample playbook is like:

---
- hosts: [hosts]
tasks:
- [first task]
- [second task]

We are going to create a directory on our remote node using playbook for all hosts. Below mentioned playbook will create test directory in /home/ec2-user path.

---
- hosts: all
tasks:
โ€” name: Creates directory
file: path=/home/ec2-user/test state=directory

When we execute above playbook using command โ€œansible-playbook playbook.ymlโ€ we get below result. In this, the first result is gathering facts. This happens as ansible executes a special module named โ€œsetupโ€ before executing any task. This module connects to a remote host and gathers all kinds of information like IP address, disk space, CPU etc. Once this is done, our create directory task is executed to create the test directory.

PLAY [all] ***************************************************************************************************************************************************TASK [Gathering Facts] ***************************************************************************************************************************************
ok: [18.191.176.209]TASK [Creates directory] *************************************************************************************************************************************
changed: [18.191.176.209]PLAY RECAP ***************************************************************************************************************************************************
18.191.176.209 : ok=2 changed=1 unreachable=0 failed=0

There are many modules and commands available to be executed on remote hosts. With ansible, we can do a server setup, software installation and lot more tasks.

Posted in DevOps

Terraform

Introduction to Terraform

Welcome to the intro guide to Terraform! This guide is the best place to start with Terraform. We cover what Terraform is, what problems it can solve, how it compares to existing software, and contains a quick start for using Terraform.

If you are already familiar with the basics of Terraform, the documentation provides a better reference guide for all available features as well as internals.

What is Terraform?

Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions.

Configuration files describe to Terraform the components needed to run a single application or your entire datacenter. Terraform generates an execution plan describing what it will do to reach the desired state, and then executes it to build the described infrastructure. As the configuration changes, Terraform is able to determine what changed and create incremental execution plans which can be applied.

The infrastructure Terraform can manage includes low-level components such as compute instances, storage, and networking, as well as high-level components such as DNS entries, SaaS features, etc…

Examples work best to showcase Terraform. Please see the use cases.

The key features of Terraform are:

Infrastructure as Code

Infrastructure is described using a high-level configuration syntax. This allows a blueprint of your datacenter to be versioned and treated as you would any other code. Additionally, infrastructure can be shared and re-used.

Execution Plans

Terraform has a “planning” step where it generates an execution plan. The execution plan shows what Terraform will do when you call apply. This lets you avoid any surprises when Terraform manipulates infrastructure.

Resource Graph

Terraform builds a graph of all your resources, and parallelizes the creation and modification of any non-dependent resources. Because of this, Terraform builds infrastructure as efficiently as possible, and operators get insight into dependencies in their infrastructure.

Change Automation

Complex changesets can be applied to your infrastructure with minimal human interaction. With the previously mentioned execution plan and resource graph, you know exactly what Terraform will change and in what order, avoiding many possible human errors.

Posted in Self-Driving Car

Program an Autonomous Vehicle

Thiแบฟt lแบญp dแปฑ รกn Dแปฑ รกn sแบฝ yรชu cแบงu sแปญ dแปฅng Ubuntu Linux (hแป‡ ฤ‘iแปu hร nh cแปงa Carla) vร  mแป™t trรฌnh mรด phแปng mแป›i. ฤแปƒ giแบฃm bแป›t khรณ khฤƒn khi cร i ฤ‘แบทt, chรบng tรดi ฤ‘รฃ cung cแบฅp Khรดng gian lร m viแป‡c trong trรฌnh duyแป‡t ฤ‘แปƒ bแบกn lร m viแป‡c. Bแบกn cรณ thแปƒ tรฌm thแบฅy hฦฐแป›ng dแบซn cho Workspace vร  chรญnh Workspace sau trong bร i hแปc nร y. Nแบฟu bแบกn khรดng muแป‘n sแปญ dแปฅng Khรดng gian lร m viแป‡c, hรฃy lร m theo cรกc bฦฐแป›c bรชn dฦฐแป›i ฤ‘แปƒ thiแบฟt lแบญp: BแปŸi vรฌ ROS ฤ‘ฦฐแปฃc sแปญ dแปฅng, bแบกn sแบฝ cแบงn sแปญ dแปฅng Ubuntu ฤ‘แปƒ phรกt triแปƒn vร  kiแปƒm tra mรฃ dแปฑ รกn cแปงa mรฌnh. Bแบกn cรณ thแปƒ sแปญ dแปฅng Ubuntu 14.04 vแป›i ROS Indigo Ubuntu 16.04 vแป›i ROS Kinetic Bแบกn cรณ thแปƒ sแปญ dแปฅng cร i ฤ‘แบทt Ubuntu hoแบทc mรกy แบฃo cแปงa riรชng mรฌnh (khรดng ฤ‘ฦฐแปฃc hแป— trแปฃ) hoแบทc bแบกn cรณ thแปƒ sแปญ dแปฅng VM ฤ‘ฦฐแปฃc cung cแบฅp trong Mรกy แบฃo cแปงa bแบกn trong bร i hแปc “Giแป›i thiแป‡u vแป ROS”. Mรกy แบฃo ฤ‘ฦฐแปฃc cung cแบฅp ฤ‘รฃ cร i ฤ‘แบทt sแบตn ROS vร  Dataspeed DBW. Ngฦฐแปi dรนng Windows 10 – nhแปฏng sinh viรชn ฤ‘แป“ng nghiแป‡p cแปงa bแบกn ฤ‘รฃ gแปฃi รฝ rแบฑng lแปฑa chแปn cแปฅc bแป™ tแป‘t nhแบฅt lร  sแปญ dแปฅng VM cho ROS, trong khi chแบกy trรฌnh mรด phแปng nguyรชn bแบฃn (vร  ฤ‘แบฃm bแบฃo mแปŸ cรกc cแป•ng giแปฏa hai ฤ‘แปƒ giao tiแบฟp). Bแบกn cรณ thแปƒ tรฌm thแบฅy repo cแปงa dแปฑ รกn tแบกi ฤ‘รขy. Sao chรฉp hoแบทc tแบฃi xuแป‘ng mรฃ dแปฑ รกn trฦฐแป›c cรกc phแบงn tiแบฟp theo ฤ‘แปƒ bแบกn cรณ thแปƒ theo dรตi cรนng vแป›i cรกc mรด tแบฃ mรฃ! Trong README, bแบกn sแบฝ cรณ thแปƒ tรฌm thแบฅy bแบฅt kแปณ phแปฅ thuแป™c bแป• sung nร o cแบงn thiแบฟt cho dแปฑ รกn. Dแปฑ รกn tรญch hแปฃp hแป‡ thแป‘ng sแปญ dแปฅng trรฌnh mรด phแปng cแปงa riรชng nรณ sแบฝ giao diแป‡n vแป›i mรฃ ROS cแปงa bแบกn vร  cรณ tรญnh nฤƒng phรกt hiแป‡n ฤ‘รจn giao thรดng. Bแบกn cรณ thแปƒ tแบฃi xuแป‘ng trรฌnh mรด phแปng tแบกi ฤ‘รขy. ฤแปƒ cแบฃi thiแป‡n hiแป‡u suแบฅt khi sแปญ dแปฅng mรกy แบฃo, chรบng tรดi khuyรชn bแบกn nรชn tแบฃi xuแป‘ng trรฌnh mรด phแปng cho hแป‡ ฤ‘iแปu hร nh mรกy chแปง cแปงa bแบกn vร  sแปญ dแปฅng trรฌnh mรด phแปng nร y bรชn ngoร i mรกy แบฃo. Bแบกn sแบฝ cรณ thแปƒ chแบกy mรฃ dแปฑ รกn trong mรกy แบฃo trong khi chแบกy trรฌnh mรด phแปng nguyรชn bแบฃn trong mรกy chแปง sแปญ dแปฅng chuyแปƒn tiแบฟp cแป•ng trรชn cแป•ng 4567. ฤแปƒ biแบฟt thรชm thรดng tin vแป cรกch thiแบฟt lแบญp chuyแปƒn tiแบฟp cแป•ng, hรฃy xem phแบงn cuแป‘i cแปงa khรกi niแป‡m lแป›p hแปc tแบกi ฤ‘รขy. ฤiแปƒm ฤ‘รกnh giรก cho dแปฑ รกn nร y khรก ฤ‘ฦกn giแบฃn – chiแบฟc xe cรณ ฤ‘iแปu hฦฐแป›ng thร nh cรดng ฤ‘ฦฐแปng ฤ‘ua khรดng? Nแบฟu bแบกn ฤ‘ang sแปญ dแปฅng phiรชn bแบฃn ba kแปณ hแบกn, hรฃy kiแปƒm tra phiแบฟu tแปฑ ฤ‘รกnh giรก tแบกi ฤ‘รขy hoแบทc ฤ‘แป‘i vแป›i phiรชn bแบฃn hai kแปณ hแบกn, hรฃy xem phiแบฟu ฤ‘รกnh giรก tแบกi ฤ‘รขy.