Showing posts with label what. Show all posts
Showing posts with label what. Show all posts

Monday, February 4, 2013

Escape Sequences in c++

#include <cstdio>
#include <iostream>

int main()
{
    // escape sequence covered - \' \" \? \\ \0 \a \b \n \r \t
    printf("\n 1. sandeep \t dheeraj\n");

    printf("\n 2. sandeep \v dheeraj\n");
 
    printf("\n 3. sandeep \r dheeraj\n");
 
    printf("\n 4. sandeep \a\a\a dheeraj\n");
 
    printf("\n 5. sandeep\b dhe\0eraj extra\n");
 
    printf("\n 6. \'sandeep\' \\ \n");  // used \' \" \\
 
    printf("\n 7. Ram? \n");
 
    printf("\n 8. Ram\? \n");    //why we use \? this escape sequence
 
    printf("\n 9. \"dheeraj\" \n");
}

OUTPUT:

Friday, January 25, 2013

A note on Command line argument

Arguments can be passed to any function in a program, including the main() function.

Arguments passed to main(), must be declared as part of the function’s definition. To standardize passing arguments to a main() function, only two  items are allowed: a number and an array. The number is an integer variable, typically named argc (short for argument counter), and the array is a one-dimensional list, which is, by convention, named argv (short for argument values). Figure D.3 illustrates these two arguments.
----------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    int i;
   
    cout << "\n The number of items on the command line is "
         << argc << endl << endl;
       
    for(i = 0; i < argc; i++)
    {
        cout << "the address stored in argv[" << i << "] is "
             << int (argv[i]) << endl; //dispaly address as an integer number
           
        cout << "the character pointed to is " << *argv[i] << endl;
    }
   
    return 0;
}

OUTPUT:
 ____________________________________________________________

 // A program that displays its command-line arguments

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
    int i;
    cout << "\nThe following arguments were passed to main(): ";
   
    for (i = 0; i < argc; i++)
    {
        cout << argv[i] << " ";
    }
   
    cout << endl;
    return 0;
}

OUTPUT:
 

Tuesday, January 1, 2013

What is threading

What is a thread:
  • A thread is the entity with in a process that can be scheduled for execution.
  • Threads are much like lightweight processes.
  • Allow the program to execute sequential actions or many actions at once.
  • All the threads in a process share the same address space.
  • It's a small independent chunk of code that can run concurrently with other threads.
  • Each thread runs independently of the others.
  • Each thread may run a different sequence of instructions.
  • A thread isn't a whole program.
  • Each process has atleast one thread.
Note: It’s important to note that a thread can do anything a process can do. But since a process can consist of multiple threads, a thread could be considered a ‘lightweight’ process.

What is a process:
  • An executing instance of a program is called a process.
  • Program under execution is known as process.
  • A process is always stored in the main memory also termed as the primary memory or random access memory.
  • Therefore, a process is termed as an active entity. It disappears if the machine is rebooted.
  • Each process provides the resources needed to execute a program.
  • Several process may be associated with a same program.
  • A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution.
  • Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.

What is the difference between Process and Thread :
  1. Threads are easier to create than processes since they don't require a separate address space.  
  2. Multithreading requires careful programming since threads share data strucures that should only be modified by one thread at a time. Unlike threads, processes don't share the same address space.
  3. Threads are considered lightweight because they use far less resources than processes.
  4. Processes are independent of each other. Threads, since they share the same address space are interdependent, so caution must be taken so that different threads don't step on each other. This is really another way of stating 2 above.
  5. A process can consist of multiple threads.
  6. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
  7. Both threads and processes are atomic units of OS resource allocation.

What is Threading (or multithreading):
  • Multithreading is the ability of a program or process to manage multiple requesets by the same user at same time without having to have multiple copies of the program (that is running).
  • If a program have multiple thread that kind of program known as multithreading program.
  • Threads allows for multithreading.

Advantage of threading:
There are 2 main reasons to use threading in an application.
  • Multithreading improve application performance.
  • Separation of concerns.

When not to use multithreading:
  • The only reason not to use threading is when the benefit is not worth the cost.
  • The performance gain might not be as large as expected.

Disadvantage of threading:
  • It can complicate the code, making it harder to understand and more prone to bugs. Therefore it’s only worth doing for those performance-critical parts of the application where there’s the potential for measurable gain.

Why we use Threading:
  • In simple, to achieve concurrency.

What is concurrency:
  • Concurrency is about two or more separate activities happening at the same time.
  • In term of computers, a single system performing multiple independent activities in parallel, rather than sequentially, or one after the other.
  • Concurrency meaning in plain English -->Acting together, as agents, circumstances or events.

Why use concurrency:
The almost same reason that for threading.
  • Separation of concerns.
  • Performance.
           
Explaination for separation of concerns:
Separation of concerns is almost always a good idea when writing software; by grouping related bits of code together and keeping unrelated bits of code apart, you can make your programs easier to understand and test, and thus less likely to contain bugs. You can use concurrency to separate distinct areas of functionality, even when the operations in these distinct areas need to happen at the same time; without the explicit use of concurrency you either have to write a task-switching framework or actively make calls to unrelated areas of code during an operation.
Example:
A DVD player application for a desktop computer. Such an application fundamentally has two sets of responsibilities: not only does it have to read the data from the disk, decode the images and sound, and send them to the graphics and sound hardware in a timely fashion so the DVD plays without glitches, but it must also take input from the user, such as when the user clicks Pause or Return To Menu, or even Quit. In a single thread, the application has to check for user input at regular intervals during the playback, thus conflating the DVD playback code with the user interface code.

c++11 standard have the support of multithreaded programs.
c++11 standard provide components in the library for writing multithreaded application and it is known as 'thread'.
we achieve threading before c++11 standard.
what's the difference made by thread library in c++11 standard. (or why use thread library)
Well answer is: This will make it possible to write multithreaded c++ programs without relying on plateform-specific extensions and thus allow writing portable multithreaded code with guaranteed behavior.

What is Mutexes: (mighty)
  • Mutex stand for mutual exclusion and is the simple and most useful synchronization structure.
  • In essence it is a boolean that determines if an object is locked from use or not.

What is Semaphores: (super)
  • Semaphores are objects that allow a certain number of threads to access a certain object before it begins blocking it.
  • A semaphore with a value 2 will allow the first 2 threads in the queue access to it then block any threads after that.
  • A mutex is in essence just a semaphore that allows one thread at a time to access an object.

Saturday, December 29, 2012

What are the 5 uses of delegate

1. Most important use of delegates- it helps us to define an abstract pointer which can point to methods and functions. The same abstract delegate can be later used to point to that type of functions and methods.

2. Callback mechanism Many times we would like to provide a call back mechanism. Delegates can be passed to the destination and destination can use the same delegate pointer to make callbacks.

3. Asynchronous processing By using ‘BeginInvoke’ and ‘EndInvoke’ we can call delegates asynchronously.

4. Multicasting - Sequential processing Some time we would like to call some methods in a sequential manner which can be done by using multicast delegate.

5. Events - Publisher subscriber modelWe can use events to create a pure publisher / subscriber model.


Code Project uses of delegate click here

Thursday, November 22, 2012

What are Design Patterns

Design patterns are optimized, reusable solutions to the comman occouring problems in programming that we encounter every day. It’s not language-specific . Most importantly, any design pattern can be a double-edged sword— if implemented in the wrong place, it can be disastrous and create many problems for you. However, implemented in the right place, at the right time, it can be your savior.
            A design pattern is not a class or a library that we can simply plug into our system; it’s much more than that. It is a template that has to be implemented in the correct situation.

There are three basic kinds of design patterns:
  1. structural
  2. creational
  3. behavioral
Structural patterns generally deal with relationships between entities, making it easier for these entities to work together.

Creational patterns provide instantiation mechanisms, making it easier to create objects in a way that suits the situation.

Behavioral patterns are used in communications between entities and make it easier and more flexible for these entities to communicate.

Further Reading:
  1. Design Pattern at Dofactory.com
  2. Design pattern Wikipedia
  3. Design Pattern in C++
  4. Design Pattern Good Explaination 
  5. Design Pattern Another nice Examples 

Wednesday, October 31, 2012

What is Template

Template helps us to create the generic functions and classes. In the generic function or class, the type of data upon which the function or class operates and specified as a parameters.

//Function Template
#include <iostream>
using namespace std;

template <class T>
T GetMax (T a, T b)
{
    T result;
    result = (a>b)?a:b ;
    return (result);
}


int main()
{
    int i = 5, j = 6, k;
    long l = 10, m = 5, n;

    k = GetMax<int>(i,j);
    n = GetMax<long>(l,m);

   
    cout << k << endl;
    cout << n << endl;
}

OUTOUT:
6
10 

int x, y;
GetMax <int> (x,y);
when the compiler encounters this call to a template function, it uses the template to automatically generate a function replacing each appereance of mytype by the type passed as the actual template parameter (int in this case) and then calls it. this process is automatically performed by the compiler and is invisible to the programmer.
______________________________________________________________________

// function Template 2
#include <iostream>
using namespace std;

template <class T>
T GetMax(T a, T b)
{
    T result;
    result = (a>b)?a:b ;
    return (result);
}

int main()
{
    int i = 5, j = 6, k;
    long l = 10, m = 5, n;
    k = GetMax(i,j);
    n = GetMax(l,m);
         //Notice here we don't declare the type
   
    cout << k << endl;
    cout << n << endl;
}

OUTOUT:
6
10

Notice how in this case, we called our function template Getmax() without explicitly specifying the type between angle-brackets <>. The compiler automatically determine what type is needed on each call.  

Tuesday, October 30, 2012

What is Encapsulation

Notes from my guru Sandeep Karan sir.

Encapsulation [A information(data or implementation) hiding mechanism]

capsule means in plain english

  1. A structure that encloses a body part (function or class)
  2. A small container

Encapsulation is a process of binding data members (variables, properties) and member functions (methods, operation) into a single unit”. eg. Function And Class is the best example of encapsulation.

Encapsulation is a process of hiding all the internal details of an object(real entity, not class ka object) from the outside world.

The ultimate goal of Encapsulation is to achieve SIMPLICITY in our code.
__________________________________________________________________________
In “Students” Example let's Implement Encapsulation.
class Students          //No matter there is union or struct 

{
   public double totalMarks;              //data, variable or attribute
   public double MarksScored;

   
   public double GetPercentageMarks()      //operation
   {
       double Percentage =(MarksScored /totalMarks) * 100;
       return Percentage;
   }

}

Students ComputerStd = new Students(); 

In above code we have encapsulated totalMarks, MarksScored and method GetPercentageMarks. While creating a “ComputerStd” object, the implementation of GetPercentageMarks will not be shown.

________________________________________________________________________

Encapsulation
help us to achieve a rule of software enginerring called simplicity (and by simplicity we achieve maintainability & security)

  • encapsulation is achieved by class, function, delegate, property.
________________________________________________________________________
Function is also example of Encapsulation

void add()
{
    int a = 4;
    int b = 5;          //data, variable or attribute
    int  c;

    c =  a + b;       //operation

    cout << "Addtion of 2 no is: " << c;
}   
________________________________________________________________________


Advance definition:
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. 
                                                        OR
In other words, encapsulation is the ability of an object to be a container (or capsule) for related properties (ie. data variables) and methods (ie. functions).             
                                                                                     OR
Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation                                                            (contractual--Relating to or part of a binding legal agreement)
==========================================================

Through encapsulation a class can hide the internal details of how an object does something. Encapsulation solves the problem at the implementation level.
      
    A class or structure can specify how accessible each of its members (variables, properties, and methods) is to code outside of the class or structure. Encapsulation simplifies the interaction between objects. An object can use another object without knowing all its data or how its data is maintained. For example, a Client object might have name, address, company, and department properties. If a Bank object wants to use a Client object, it can request the name and address for the bank without needing to know the company and department details of the Client object.
 
    With the help of encapsulation, a class can change the internal implementation without hurting the overall functionality of the system. Encapsulation protects abstraction.
_________________________________________________________________________
class Counter
{
    private int Count;

    public Counter()
    {
        Count = 0;
    }

    public void setCount( int newVal )
    {
        Count = newVal;
    }

    public int getCount()
    {
        return Count;
    }
}

This piece of code is also encapsulated, showing that you can have encapsulation without data hiding, but you cannot have data hiding without encapsulation.
____________________________________________________________________________ 
Now consider the function Substring() which returns the string based on the start index and length. The underlying algorithm and the internal data structures used to find the substring is specific to the String class and hidden from the external code who makes use of Substring() in which case the external code does not have previliges to modify the algorithm or the datastructures which are internal to (or encapsulated in) String class. This is known as encapsulation.
____________________________________________________________________________ 

Links to understand encapsulation: 

Sunday, October 21, 2012

Setter & Getter in c++

  1. A property, is a special sort of class member; or intermediate between a field (or data member) and a method.
  2. Properties are read and written like fields, but property reads and writes are (usually) translated to get and set method calls.
  3. Property allows us data validation.

That is, properties are intermediate between member code (methods) and member data  (instance variables) of the class, and properties provide a higher level of encapsulation than public fields.

//property in c++

#include <iostream>
using namespace std;

class student
{
    public:
        void setName(string x)
        {
            name = x;
        }
        string getName()
        {
            return name;
        }
       
    private:
        string name;
};

int main()
{
    student bio_stud;


    bio_stud.setName("sir Virender");
    cout << bio_stud.getName();   
}


OUTPUT:
sir Virender


NOTE:
  1. C++ does not have first class properties, but there exist several ways to emulate properties to a limited degree.
  2. C++ require the programmer to define a pair of accessor and mutator methods.  
Further reading property and indexer in cpp