Operating System

Programming Language in C++

Pinterest LinkedIn Tumblr

C++ is a general-purpose object-oriented programming language. It is useful for developing resource-constrained applications. It is a platform dependent programming language. The applications should complied with all the platforms with platform specific compilers. If you develop an application on windows operating system, you can run the application on only windows operating system. You cannot run on other Linux Operating system.

Operating system

The C++ programming language requires operating system and compiler to compile the application. After compile the application, it may require additional dependent dynamic loading files. The Linux Operating system uses GCC compiler collection. The GNU Compiler Collection includes front ends for C, C++ and Objective-C. The application can build on GCC compiler for Linux operating system. Microsoft uses Microsoft C++ compiler. The Microsoft compiler can be used for building application for windows operating system.

C++ GCC compiler download location: https://gcc.gnu.org/install/binaries.html

C++ Microsoft Compiler download location: http://www.microsoft.com/en-in/download/details.aspx?id=41151

List of compilers: http://www.stroustrup.com/compilers.html

Little History

C++ has been developed by Bjarne Stroustrup, a Danish computer scientist on 1983. In 1983, it was renamed from C with Classes to C++. New features were added including virtual functions, function name and operator overloading, references, constants, type-safe free-store memory allocation (new/delete), improved type checking. In 2011, the C++11 standard was released. C++14 released in December 2014.

C++ version History: http://www.stroustrup.com/hopl-almost-final.pdf

Develop C++ program

C++ source code is a plain text file with cpp or cc extension. C++ compiler uses to compile the source code. The developer can use a plain text editor to develop C++ program. We also have an open source Integrated development environment which provide develop, build and debug the C++ program. You can also use the commercial version of IDE like visual Studio.

Download the open source development environment from the following location
http://www.bloodshed.net/devcpp.html
http://www.microsoft.com/express/downloads/

Analysis of Hello World

Each C++ source file should contain at least one main method. If you create C++ with a namespace, it should create under the namespace.

C++ program starts with the main method and each program must have one main method. “_tmain( )” is an extension of Microsoft’s C++ compiler(It equal to main method). The input argc is the number of items on the command line. The input argv is an array of strings, one string per item. So argv[0] is the command name, argv[1] is the first input, etc.

the arg1 and arg2 pass to the args array which can be used later in the c++ program.

OOPS!

C++ is an object-oriented programming. The object is software component with State and behavior. The class is a user-defined data type or the prototype which helps to create the object. Object oriented programming supports object oriented concepts.

  1. Encapsulation- hide the internal details of the class
  2. Polymorphism – gives multiple forms of the same functionality
  3. Inheritance – create the new class from existing class
  4. Abstraction-abstraction is the process hiding irrelevant details and expose only essential futures

Variables and operators

Variable names used for the memory space. Variable can change the value at any time. But the constant cannot change the value later.

Operators help to operate the variable with different values. The data structure and algorithm many uses the following operators.

Assignment Operator

Nooperdescriptionexplanation
1=Simple assignment operatorAssign value from right side to left side variable

Arithmetic Operators

Nooperdescriptionexplanation
1+Additive operatorAdd two values or variables
2Subtraction operatorSubtract two values
3*Multiplication operatorMultiply two values
4/Division operatorDivide two values
5%Remainder operatorGive the remainder of given two values

Unary Operators

Nooperdescriptionexplanation
1+Unary plus operatorShow positive number
2Unary minus operatorShow negative number
3++Increment operatorIncrement the value by 1
4Decrement operatorDecrement the value by 1
5!Logical complement operatorCheck the negative or positive value

Equality and Relational Operators

Nooperdescriptionexplanation
1==Equal tocompare two values
2!=Not equal toNot equal of two values
3>Greater thanCompare the greater than value
4>=Greater than or equal toCompare greater than or equal to value
5<Less thanCompare less than
6<=Less than or equal toCompare less than or equal to valu

Conditional Operators

Nooperdescriptionexplanation
1&&Conditional-ANDTrue only both condition is true
2||Conditional-ORTrue either one condition is true
3?:TernaryTernary operator to compare and assign value

Bitwise and Bit Shift Operators

Nooperdescriptionexplanation
1~Unary bitwise complementinverts a bit pattern
2<<Signed left shiftshifts a bit pattern to the left
3>>Signed right shiftshifts a bit pattern to the right
4>>>Unsigned right shiftshifts a zero into the leftmost position
5&Bitwise ANDperforms a bitwise AND operation
6^Bitwise exclusive ORperforms a bitwise exclusive OR operation
7|Bitwise inclusive ORperforms a bitwise inclusive OR operation

Control flow

Control flow statement uses to control the flow of execution, make decision and branching and looping.

The following statements helps to make decision

If – If the condition is true, it execute the branch of statements

If(i < 10{
    cout << " I value is less than 10" << endl;
}

If-else – If the condition is true to execute a set of the statement from one block. Otherwise, it executes another set of the statement.

If(i < 10{
    cout << " i value is less than 10"<< endl;
}else{
    cout << " else part" << endl;
}

If-elseif-else – If the condition is true to execute the set of the statement from one block. Otherwise, it executes another set of the statement.

If(i < 10{
    cout << " I value is less than 10" << endl;
}else if( i > 10){
    cout << " I greater than 10" << endl;
 
}else if(i == 10){
    cout << " I ==10" << endl;
}else{
    cout << " else part" << endl;
}

Switch statement

Switch statement selects the appropriate value based on the month name. The break statement allows to choose the only one-month number. If we do not add break statement, it executes all the remaining switch statements.

The following example shows month number from the string description.

switch (monthNumber) {
    case 1:
        month = "January";
        break;
    case 2:
        month = "February";
        break;
    case 3:
        month = "march";
        break;
}

The following statement loop the statements.

For loop

The for loop executes from beginning to till meet the condition.

for(int i=0;i < 10;i++) {
    cout << " I value : " << i << endl;
}

For-while-dowhile

While and do-while loop are the looping statements. While loop checks the condition first before executing the code. The do-while execute the statement first and check the condition. The while loop does not execute without meet the condition. Do-while executes at least once.

while(i <10){
    cout << " i value : " << i<< endl;
 
}
do{
    cout <<" i value : " << i << endl;
} while(i <10);

Break-continue-return

The break statement breaks the current control loop and executes the next statement after the loop statement. The continue breaks the current remaining statement in the loop and continues from next iteration onwards. The return statement returns the value to callee function from the caller.

Difference between the break and continue
cout << "starting loop:" << endl;
for (int n = 0; n < 7; ++n)
{
    cout <<"in loop: " << n<< endl;
    if (n == 2) {
        continue;
    }
    cout <<"   survived first guard"<< endl;
    if (n == 4) {
        break;
    }
    cout <<"   survived second guard"<< endl;
    // continue at head of loop
}
// break out of loop
cout <<"end of loop or exit via break"<< endl;
  
  
//Return from the function
int add (int a, int b){
    return a+b;
}

Template

Template are generic programming support in C++. The compiler translates all type information into appropriate type and removes all the information related to the type parameter. Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

template < typename Type >
type max(Type a, Type b) {
    return a > b ? a : b;
}
// This will call max < int > by implicit argument deduction.
std::cout << max(3, 7) << std::endl;
 
// This will call max < double > by implicit argument deduction.
std::cout << max(3.0, 7.0) << std::endl;

More about the Templates: https://msdn.microsoft.com/en-us/library/y097fkab.aspx

Exceptions

Exceptions are abnormal conditions and C++ provide a set of API to handle the exceptional conditions. An exception is said to be thrown at the place where some error or abnormal condition is detected. The throwing will cause the normal program flow to be aborted, in a raised exception. An exception is thrown programmatic, the programmer specifies the conditions of a throw.

Unhandled exceptions on the other hand will result in a function termination and the stack will be unwound (stack allocated objects will have destructors called) as it looks for an exception handler.

#include < iostream >
#include < fstream >
using namespace std;
 
int main () {
  ifstream file;
  file.exceptions ( ifstream::failbit | ifstream::badbit );
  try {
    file.open ("test.txt");
    while (!file.eof()) file.get();
  }
  catch (ifstream::failure e) {
    cout << "Exception opening/reading file";
  }
 
  file.close();
 
  return 0;
}

File system

The file operations use to read and write the files. It supports ofstream, ifstream and fstream. ofstream represent the output file stream. ifstream represent the input file system. fstream represnt the general file system. The file system can be open with app (Append mode), ate( move control to end of the file), in (open file for reading), out (open file for writing), tran ( if file already exists, truncate the file) mode.

char buf[BUFSIZ];
size_t size;
 
int source = open("from.txt", O_RDONLY, 0);
int dest = open("to.txt", O_WRONLY | O_CREAT , 0644);
 
while ((size = read(source, buf, BUFSIZ)) > 0) {
    write(dest, buf, size);
}
 
close(source);
close(dest);

Standard Template Library (STL)

The Standard Template Library (STL) is a software library for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called algorithms, containers, functional, and iterators.

C++ tutorials explain well about the Standard Template Library classes.

https://www.sgi.com/tech/stl/table_of_contents.html

List of Standard Template Library classes

Implementations
  • Pair – Pair is container for holding two objects as single object. Pair object can be easily pass an argument
  • Bitset – Bitset is a container for storing the data at the bit level
  • Valarray – Valarray hold array of elements which used in mathematical operations.
  • String – String represent sequences of characters which can be manipulate string operations easily. String can be used to represent ASCII or wide characters.
  • Array – Array is a container that hold fixed size of arrays
  • Vector – Vector is a container that hold dynamic size of arrays
  • List – List is a container implemented on doubly linked list. It can be iterated both forwards and backwards.
  • forward_list – The forward_list is a container that implement on single linked list. The singly linked list can be iterated only forward
  • Double-ended queue – Double-ended queues or dequeue is a container with dynamic sizes. It can be expanded on both ends
  • Queue – Queue is a container which store the data in first in first out order. The items always stored in back and removed from front.
  • Priority queue – Priority queue is a container which store and remove the items basdon the priority. Priority queue does not allow the iteration trough the elements. It look up the largest item in constant time.
  • Stack – Stack is a data structure store and remove the items based on last in and first out. Priority queues are implemented based on container.
  • Set – Set is a container which contains sorted set of unique items. set is implemented as a binary search tree
  • Multiset – Multiset is an ordered collection of items where the items may occur 0 or more times. The multiset elements are always sorted in ascending order
  • map – map is an associative container that store the items by combination of key and values. The key value is unique and stored in sorted order.
  • Multimap – Multimap allows duplicate keys. Multimaps are associative container that store the elements with combination of keys and values with sorted order.
  • hashset – hashset is implemented as a hash table. Hash set is an extension which support to store and retrieve the data from collection faster.
  • hash multiset -hash multiset implemented based on hashing with multiset options. its elements are grouped into buckets based on the value of a hash function in key values.
  • hash_map – hash_map helps to store and retrieve the key and value pair elements. The elements are grouped into buckets based on the value of a hash function.
  • hash_multimap – hash_multimap helps to store and retrieve the key and value pair elements. hash_multimap class is a bidirectional iterator
  • Unordered set – Unordered sets are container that store the unique items without any order.
  • unordered_multiset – unordered_multiset are equivalent to Unordered Set with one difference. It allows different elements to have equivalent values.
  • Unordered map – Unordered maps are associative containers that store elements using key and value pair. The value retrieved based on the key.
  • Unordered multimaps – Unordered multimaps are equivalent to unordered map containers with different elements to have equivalent keys property.
Algorithms
  • sort – sort the items in the containers in ascending or descending order
  • shuffle – shuffle the element (do not maintain any order)
  • Routine Data Manipulation -the normal data manipulation like fill, addAll, reverse, copy, swap
  • search – Search particular item in the list
  • Finding Extreme Values – finding the minimum and maximum values from the list

Careerdrill explains the Standard Template Library concepts with an example.

Missing!

We didn’t cover each and every topic from C++ programming language. We didn’t cover Network programming, Interposes communication, Security, Internalization, GUI, deployment and Regular expression. We covered the basic programming language syntax which helps to understand the Data structure and algorithm point of view.

You can always learn the topics from recommended books and useful links.

Write A Comment