Sunday, July 2, 2017

Interview question asked in Pitney Bowls for C++ developer

Interview @ Pitney Bowls, Noida


1st Round:- Coding Round Online::
Three questions where asked. All need to be programmed with production level code.
It was in Hackerrank.com


2nd Round:Technical (SQL + Unix)
-------------------------------
*****Unix*********
How to check version of linux?
How to check shell of putty(ksh,?
How to check terminal of putty?
What is the meaning of writing #bash bla bla in first line of shell scrip? It is necessary?
awk,find,grep,sed, command?
In a file there is multiple columns. A column may have repeated data. How do you print unique elements of the nth column?
How to memory taken by a process while execution.
*******sql*******
How do you connect database in C++? Write the command?
Questions on join?
Given a problem o multiple tables and asked to write select query.
Importance of Indexes?
How a searching is performed in database, which algorithm is used?
While doing database search operation from multiple tables temporary table is created. How do you access that temporary table.
How do you optimize the sql query?
How to use show plan for sql?

3rd Round (C++,Data Structure)
-----------------------------
1. Asked about the questions in coding round. :: I was not able to recall even one problem.. :(
2. Gave one of the problem from coding round. (There is file containing n statements, two set of words for Apple company and another for Apple fruit. Now you have check each statement/line is concerned with Apple Company or Fruit and print either "Company" or "Fruit" for each line.)
3. What is Binary Search Tree?
4. In a binary tree there comes a situation that we can not add an item at some specific node due to left-right restriction. You need to find that kind node in binary tree.
Example:-
6
2 8
7 13
We can not add anything in the node 7. You need to find this kind of node in any binary tree.
4th Round (Design)
-----------------
1. Is there a way to print Binary tree in the sequence in which its elements are added in the tree.
2. There is three set of texts, set A,B and C. Each set is having size of 1024KB. There are some words that are repeated in the texts. You need to list down the repeated words from each set. If one asks for the result in the mod of processing the file then give only the list of previously performed text set(Not the output list of current processing set.)

How to change time format from 24 hour to 12 hour (AM/PM) format

There is only 3 steps to change time time format from 24 hour to 12 hour.

Step 1:
Right Click on Window start (i.e. default at down left most corner) of screen. Then choose "control Panel".
Step 2:
Once Control Panel is opened select "Change, date, time, or number formats".
As shown in picture below.
Step 3:
A new window will be opened as below. Now choose from the drop down list in front of "Short time", from "HH:mm" or "H:mm" to "hh:mm tt".
The "hh:mm tt" format is used for AM/PM format. Here tt denotes AM/PM.
Select the format and click on apply.
The final screen will look like as below.

Please post comment if you have any query.

Monday, June 19, 2017

C++ Multi-Threading program to print odd and even numbers in sequence from two functions

C++ Multi-Threading program to print odd and even numbers in sequence from two functions.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

int MAX = 10;
int count = 0;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *even(void *arg)
{
    while(count < MAX) {
        pthread_mutex_lock(&mutex);
        while(count % 2 != 0) {
            pthread_cond_wait(&cond, &mutex);
        }
        printf("%d ", count++);
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond);
    }
    pthread_exit(0);
}

void *odd(void *arg)
{
    while(count < MAX) {
        pthread_mutex_lock(&mutex);
        while(count % 2 != 1) {
            pthread_cond_wait(&cond, &mutex);
        }
        printf("%d ", count++);
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond);
    }
    pthread_exit(0);
}

int main()
{
    pthread_t t1;
    pthread_t t2;

    pthread_mutex_init(&mutex, 0);
    pthread_cond_init(&cond, 0);

    pthread_create(&t1, 0, &even, NULL);
    pthread_create(&t2, 0, &odd, NULL);

    pthread_join(t1, 0);
    pthread_join(t2, 0);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return  0;
}

Output::
0 1 2 3 4 5 6 7 8 9 10  

C++ program to play music and compile in GCC compiler

Here is the simplest program to play music in C++.

Here you have to do a setting if you are using and UI based IDE like code block or Dev C++. You have to go to setting and add  lwinmm in linker setting. lwinmm is a linker used while compilation of program containing sound.
with this program only wav music file format can be played. You can convert the music file to wav format online by vising this link -- http://media.io/

The code goes as below::

#include <windows.h>
#include <iostream>
#include <mmsystem.h>
using namespace std;
int main()
{
  system("clear");
  cout<<"Sound playing... enjoy....!!!"<<endl;
  PlaySound("C://music1.wav", NULL, SND_SYNC); //SND_FILENAME or SND_LOOP
  return 0;
}

If you are using gcc compiler and compiling using command line then your life will be easy. you need you write below command for compilation. 


Let say I have saved my program as sound.cpp. So command to compile will be-

$ g++ sound.cpp -lwinmm -o sound

After successful compilation to execute the file, write as below-
$ ./sound

Sunday, June 18, 2017

Forward declaration:: used in friend function of two class.
E Balagurusamy page 128

* Do not confuse between
void fun1(int & a)
{
.....
......
}
and
void fun1(int * a)
{
....
....
}
Both are pass by reference.

Copy constructor::
Program to illustrate the copy constructor.
#include<iostream>
using namespace std;
class ABC
{
    int a,b;
public:
    //int c;
    void show()
    {
        cout<<"a="<<a<<" and b="<<b<<endl;
    }
    ABC(){a=0;b=0;}
    ABC(int x,int y){a=x;b=y;}
    ABC(ABC& obj){ a=obj.a; }
};
int main()
{
    int a=2,b=3;
    ABC obj1,obj2(2,3);
    ABC obj3(obj2);            //Copy constructor called (copy only a, as defined in the constructor)
    ABC obj4 = obj2;          //Copy constructor called (copy only a, as defined in the constructor)
    obj1=obj2;         //default assignment operator of the system called, copy all elements one by one.
    cout<<"obj1(2,3)";
    obj1.show();
    cout<<"\nobj2(2,3)";
    obj2.show();
    cout<<"\nobj3(2,lets see)";
    obj3.show();
    cout<<"\nobj4(2,lets see)";
    obj4.show();

}

Output::
    obj1(2,3) a=2 and b=3
    nobj2(2,3) a=2 and b=3
    obj3(2,lets see) a=2 and b=2293456
    obj4(2,lets see) a=2 and b=0

Shallow Copy and Deep Copy --http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/

-------------------------------------------------------------------------------
How to get rid of compiler error-
deprecated conversion from string constant to ‘char*’
I got this compilation error while compiling the below code.

void ABC(char *strng) {};
ABC("Hello World");
or
void ABC(char *strng){};               //This code may compile but the window will crash on execution
char *strng1="Hellow World";
ABC(strng1);

I find two solution for this...
1.
void ABC(char *strng){};
char strng1[] ="Hellow World";
ABC(strng1);

2. define const every where if the sting does no changes.
void ABC(const char *strng){};
const char *strng1 ="Hellow World";
ABC(strng1);


---------------------------------------------------------------------------
Access the private data member variables of the class without friend function.
#include <iostream>
#include <string>
using namespace std;
class ABC
{ private:
   int a,b;
  public:
  void show() {
      cout<<"a="<<a<<"and b="<<b; }
};
int main()
{
    ABC obj;
    int *p_obj=(int*)&obj;
    *p_obj=10;                           // It will set the value of a to 10;
     *(p_obj+1) = 20;                 //It will set the value of b to 20.
    obj.show();
}

Sunday, March 5, 2017

Python Cheat sheet

Recently I started to learn Python and found it very interesting and easy as well. I stated to learn python from level 0 and now I learned core Python in 10 days. Studied mostly from python.org, courcera.com and udemy.com.

python.org is official website of Python. Here I am sharing my digital Cheat Sheet on python which I have studied till now. Still I am continuing this. I will share the further notes soon.

Please provide comments and queries if you have.
---------------------------------------------- Python Notes ---------------------------------------------------------
Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum in the Netherlands as a successor of a language called ABC.
According to the principal author (Guido van Rossum), he chose the name "Python" because he is a big fan of the British comedy movie - 'Monty Python's Flying Circus'.

Salient features of Python:-
*  Python is a case sensitive programming language.
*  It supports functional and structured programming methods as well as OOP.
*  It can be used as a scripting language or can be compiled to byte-code for building large applications.
*  It provides very high-level dynamic data types and supports dynamic type checking.
*  It supports automatic garbage collection.
*  It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Type Conversion:-
str(x) − Converts object x to a string representation.
float(x) − Converts x to a floating-point number.
tuple(s) − Converts s to a tuple.
list(s) − Converts s to a list.
set(s) − Converts s to a set.
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.
chr(x) − Converts an integer to a character.
hex(x) − Converts an integer to a hexadecimal string.
oct(x) − Converts an integer to an octal string.
round(x) - Round a float number to integer either to base or to floor according to float value.


isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
isdigit() − Returns true if string contains only digits and false otherwise.
islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
lower() − Converts all uppercase letters in string to lowercase.
upper() − Converts all lowercase letters in string to uppercase.
swapcase() − Inverts case for all letters in string.
capitalize() − Capitalizes first letter of string.
title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.
istitle() − Returns true if string is properly "titlecased" and false otherwise.
isspace() − Returns true if string contains only whitespace characters and false otherwise.
lstrip() − Removes all leading whitespace in string.
rstrip() - Removes all the whitespace after the string.
strip([chars]) − Performs both lstrip() and rstrip() on string.
len(string) − Returns the length of the string.
random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.
str.rjust(width,'fillchar') -- print the string right justified.
str.rjust(width) -- we can use it simply like this.
str.center()  -- center justified
str.ljust() -- left justified

List:-
cmp(list1, list2) − Compares elements of both lists.
len(list) − Gives the total length of the list.
max(list) − Returns item from the list with max value. --all elements must be of same data type
min(list) − Returns item from the list with min value.  -- all elements must be of same data type
list.index(obj) − Returns the lowest index in list that obj appears.
list.insert(index, obj) − Inserts object obj into list at offset index.
list.append(obj) - Append obj in the list.
list.remove(obj) − Removes object obj from list.
list.reverse() − Reverses objects of list in place i.e. first index value goes to last and last to first.
example:- list=['abc', 454, 2.23, 'john', 70.2]  then output of list.reverse() is [70.2, 'john', 2.23, 454, 'abc']
list.sort([func]) − Sorts objects of list, use compare func if given.
list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

**help(print) -- it displays help regarding parameter passed
**dir(<argument>) -- it displays help, what are function we can use with the argument

What is IDLE?
IDE - Integrated Development Environment.
IDLE - is IDE for Python.

We can use commands like -- 3+4,8-4,6/2,(2*4)+3/2 in python shell.
printing string in- >>> "Hello" or 'Hello' , x='dog'
print('Hello'),print('dog',5,4,'cat'),print(x)
Python remembers all the variables until is not restarted or deleted.
delete variable command: del <variable name/s>

Variable naming convention is same as C/C++. It contains letters,numbers and underscore.
Reserved identifiers in Python-


Variable tyes in Python
1. integer(int) (All integer type is long int)
2. float
3. Comples
4. string(str)
5. boolean(bool)
6. list
7. Tuple
8. Dictionaries
str = 'Hello World!'

print (str)               # Prints complete stringprint -- Hello World!
(str[0])                  # Prints first character of the stringprint -- H
(str[2:5])               # Prints characters starting from 3rd to 5th print -- llo
(str[2:])                 # Prints string starting from 3rd characterprint -- llo World!
(str * 2)                 # Prints string two timesprint -- Hello World!Hello World!
(str + "TEST")        # Prints concatenated string -- Hello World!TEST


The main differences between lists and tuples are −
* Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.
Example :- list1= ['abcd', 786, 2.23, 'john', 70.2]  ::: tuple1=('abcd', 786, 2.23, 'john', 70.2)

Dictionary defined in curly braces while value can be assigned and accessed by square braces [] .
dict1 = {'name': 'john','code':6734, 'dept': 'sales'}
dict1['one'] = 'Hello'
dict1[2] = 10

e.g. -
print (dict1['one'])              # Prints value for 'one' key
print (dict1[2])                   # Prints value for 2 key
print (dict1)                  # Prints complete dictionary
print (dict1.keys())        # Prints all the keys
print (dict1.values())     # Prints all the values

Operator types in Python:-
1. mathematical   2. Relational   3. Logical    4. Bitwise
5. Membership (in,not in)  e.g. 2 in [3,2,6]  Result:: True
6. Identity  (is,is not)   e.g. a is b -- Result will be True or False


Arithmatic operator othe then C++ --
//  -- Floor division >>>9//2  will give o/p 4 not 4.5 but 9/2 -> 4.5

** Exponent e.g. x**y means x to the power y.


Operator Precedence - **>~>unary operator(-,+)>*>/>%>//
x=3+4
y=5/2
print(type(x))   --- this gives the type of the variable x
output-
<class 'int'>

print(type(y))
<class 'float'>

-------------- bool ------------------------

x=False  -- not false or FALSE

y=True  --  not true or TRUE

-------------- input/print -----------------

Get input from keyboard --- input()

input function always returns string irrespective of input provided.

name=input()
age = int(input())  -- we neet to convert string into int. Input always return the data type string.
name=input("What is your name:")  -- It prints the string (What is your name:") and store the value entered by user in the variable name.

print("Hello",name)

------------- data type conversion ----------

num=input()      --- Here num is string.

number=int(num)  --- Here num is converted to integer from string type.
number=float(num)
---------- BIFs - Built in Functions --------------
isinstance() - it returns type of the variable. E.g.- isinstance(3,int) -> True
------------------ List -----------------------
How to create list-

my_list=["hello",12.50,25,True]

print(my_list)

my_list[0]

There are two ways to access the elements of list-

1. Positive Indexing

     Index increases from 0 to n

2. Negative Indexing

     It goes from right to left. Last elemet have index -1, second lost having index of -2 and so on.
     e.g. - my_list[-1]  -- it will print True

Python have two Modules-
  1. Standard Module -- it comes installed with python. example - math module
  2. External Module -- We need to install this from external.

>>> import math
>>> math.sqrt(9)
3.0

Which of the following statements would generate the string 'fun'?
print('Python is fun'[-3:])
print('Python is fun'[-3:-1])
print('Python is fun'[-3:0]) -- this prints nothing.

--------------- If condition and Inline if --------------
x=5
if x>=0:
     print("Positive number")
else
     print("Negative number")

inline if condition:-
print("Positive number" if x>=0 else "Negative Number")  --above 4 line code is written in one line.

if x>10:
   ......
elif x==10;
   .......
else
   .....

-------------- looping condition --------------------
1. for loop
lst = ["abc@gmail.com","xyz@hotmail.com","pqr@gmail.com"]
for mail in lst:
     if "gmail" in mail:
          print(mail)
for x in range(1,10):
     print(x)

for i,j in zip(lst1,lst2):
     print(i,j)

2. while loop
password = ''
while password != 'python123':
    password = input("Enter password: ")
    if password == 'python123':
        print("You are logged in!")
    else:
        print("Please try again.")

----------- File Handling --------------------
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

Different modes to open a text file-
r = read only, File pointer is placed at the beginning of the file.         
r+ = read + over-write, file pointer is placed at the beginning of the file.       
w = write only,  If the file does not exists it creates a new file.    
w+ = read + write     It deletes the file content when opened and then used to write on the file.
a = append,    
a+=read + append (Pointer is at last of file)
b = binary mode

f.read(size) -- read a file and prints 'size' number of starting character in the file.
f.read() --  will read entire file in one shot and will will return an empty string ('').
f.readline() -- it reads a single line from the file. it adds '\n' in the end of string and if the end of the file is reached the it returns a blank line.
f.write(string) -- writes the contents of string to the file, returning the number of characters written.
f.tell() -- returns an integer giving the file object’s current position.
f.seek(offset, from_what) -- takes the file current position to offset in reference to from_what position. If from_what position is not provided then it takes default 0.
f.seek(offset) --

with statement
when file is opened with 'with' statement, the file.close() part is taken care by the with statement itself. It is always best practice to use the with statement while opening the file.
example:-
with open('example.txt','a+') as file:
     file.write("Hello Mukesh")

We need not to write the file.close(), it is taken care by the with statement itself.

Writing your own ATOI() function in C++

Checkout the below program written to convert numbers in string to integer. In C++ there is a function atoi() to convert number in character to integer. Here I am writing my own function to to do this.

//atoi() function creation.
#include<iostream>
using namespace std;
bool isNumeric(char x)
{
    return(('0'<= x && x <='9')?true:false);    
}
int myAtoi(char* str)
{
    int neg = 1, res = 0, i = 0;
    if(str[0] == '-'){    
        neg=-1; 
        i++;  
    }
    while(str[i]!='\0'){
        if(!isNumeric(str[i])){
            return(res*neg);
        }
        else
        {    res = res*10 + str[i]-'0'; i++; }
    }
    return(res*neg);
}

int main()
{
    char str[]="-90jyh8";
    int val = myAtoi(str);
    cout<<val;
    return 1;
}

Output::-90