Saturday, July 9, 2016

Binary inversion of number and converting decimal to Binary in C++

Code to do binary inversion of a number in C++

#include <iostream>
using namespace std;
int main() {
    unsigned int ip_num,op_num,i=0,tmp;
    cin>>ip_num;
    tmp = ip_num;
    while(tmp!=0)
    {
        tmp = tmp>>1;
        i++;
    }
    //i = 8-i;
    //i = 16 -i;
    i = 32-i;
    op_num = ~ip_num;
    op_num = op_num<<i;
/* Any bit value right shifted should be re-initialised to zero */
    //op_num = op_num&255;
    //op_num = op_num&65535;
    op_num = op_num&4294967295;
    op_num = op_num>>i;
    cout<<op_num;
return 0;
}


Code to display Binary value of a number in C++ upto 16 binary digit.

void toBin(unsigned int n){
    int i=0;
    //while(n && i!=16){

       // int res = n&32768;
        if(res)
            cout<<1;
        else
            cout<<0;
        n = n<<1;
        i++;
    }
    cout<<endl;
}

Sunday, June 19, 2016

deprecated conversion from string constant to ‘char*’

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);

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Memory Padding

Memory Padding
Lets understand Memory padding by an example.

#include <iostream>
using std::cout;
struct checkSize
{
    int a;
    char b;
    short int c;
    int d;
    char e;
};
int main()
{
  cout <<"Size of structure::"<<sizeof(checkSize);
  return 0;
}
Given Condition:: System is 32 bit. Size of int = 4 bytes, char = 1 byte and short int = 2 bytes.
As we expect the output of this as 12 bytes. But the actual answer is 16 bytes.
Reason:; Memory Padding is used in this.
In a 32 bit system, the bus have limit carry only 32 bits or 4 bytes of data in one time. Or in other word we can say system bus carry data in a group of 4 bytes. Through memory padding technique system tries to group the data in size of 4 bytes in this case also.
int a; 4 byte           -- group 1
char b; 1 byte        -- group 2
short int c; 2 byte  -- group 2
int d; 4 byte           -- group 3
char e;  1 byte       -- group 4
The memory is grouped in the sequence of initialization of the variable.
Group 1 and 3 will contain 4 bytes while group 2 contains 3 bytes and group 4 contains only 1 byte.
If we would have initialized like below, if would have took only 12 bytes of memory.
struct checkSize
{
    char e;
    char b;
    short int c;
    int d;
    int a;
};
Memory padding technique is not used in Class in C++.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Friday, May 20, 2016

Basic puzzle questions in C/C++ :: MUST KNOWN concepts to every programmers :: SET-3

Q1.
string str;
int ii; double dd;
cin>>ii;
cout<<ii+i<<endl;
cin>>dd;
cout<<dd+d<<endl;
getline(cin,str);
cout<<str<<endl;


Q2.
double d=4;
cout<<d<<endl;

Q3.
double d=4;
cout<<setprecision(1)<<fixed<<d<<endl;

Q4.
Which one is suitable syntax for function template?
a. template< class T> return_type Function_Name(parameters)
b. template< typename T> return_type Function_Name(parameters)
c. both and b
d. None of these

Q5.
In CPP, the size of the character array should be one larger than the number of characters in the string.
a. True
b. False

Q6.
A class can contain objects of other classes and this phenomenon is called__________
a. Relationship
b. Object Association
c. Containership
d. None of these

-----------------------------------------------------------------------------------------------------------------
Answers:::
1)
It will take input in str. We need to use cin.ignore();
cin.ignore();  ----cin.ignore() is used to ignore previous cin values. string takes \n(new line) as input.
Correct program:-
string str;
int ii; double dd;
cin>>ii;
cout<<ii+i<<endl;
cin>>dd;
cout<<dd+d<<endl;
cin.ignore();
getline(cin,str);
cout<<str<<endl;

2)
O/P-  4

3)
O/P-  4.0

4)
Answer:: c (both a and b)

5)
Answer:: a ::True
void main()
{ char name[5] = “INDIA”; //This is invalid and cause error
  char x_name[6]=”INDIA” // This is valid, one extra byte required for \0 character
}

6)
Answer:: Containership


Structure in C vs Structure in C++ :: Can we define function in structure

Structure in C vs Structure in C++ :: Can we define function structure

There are few major difference between structure in C and C++. While I was studying I always remains confused if structure can have function or not, if yes then whether in C or in C++.
Because I have studied that structure can not have function as member function. But in internet in many places I have seen function inside structure by searching many websites I found yes structure can also have member function but only in C++ not in C.
I have written a short program to understand it.

The important difference between class and structure is that by default in class member remains in Private while in structure it remain in public.

In C we can not define function inside structure but we can use pointer to function here.

In C++
We can do all things as we do in Class in C++ except the members of structure always remain public.
We can define function,constructor,destuctor in Structure also in C++.

See the below code of structure written in C++ for better understanding. It explains how we can define function,constructor and de-structure in structure in C++.

#include<iostream>
#include<cstring>
using namespace std;
struct student
{
    int roll_no;
    char *name;
    student()
    {
        roll_no=0;
        name = new char[100];
        }
    student(int rn,const char* name1)
    {
        roll_no=rn;
        name = new char[strlen(name1)+1];
        strcpy(name,name1);
    }
    void getData()
    {cout<<"Enter Roll number::";
        cin>>roll_no;
        cout<<"\nEnter name::";
        cin.ignore();
        cin.getline(name,100);
    }
    void display()
    {
        cout<<"\nRoll Number::"<<roll_no;
        cout<<"\nName::"<<name;
    }
    ~student()
    {
        cout<<"\nDestructor called for"<<this;
    }
};
int main( )
{
    student s1;
    s1.getData();
    s1.display();
    student s2;
    s2=s1;
    s2.display();
    student s3(226,"Mukesh Kumar");
    s3.display();
    return 1;
}












Please share your views and knowledge. Please comment below for any more information and also if you find any thing wrong in this post.

Friday, May 13, 2016

Basic puzzle questions in C :: MUST KNOWN concepts to every programmers :: SET-2

Basic puzzle questions in C :: MUST KNOWN concepts to every programmers

Q1) What will be output of the program below?
void print (int n)
{
if (n>0)
{
printf(“hello”);
print(n-1);
}
printf(“world”);
}


Q2) Which statement will cause problem?
int main()
{
Statement 1-> const char *p1=”hello world”;
Statement 2-> char *const p2=”hello world”;
Statement 3-> p1=”welcome”;
Statement 4-> p2=”good bye”;
Statement 5-> *(p1+3) = ‘A’;
Statement 6­-> *(p2+3) = ‘A’;
return 0;
}

Q3)  What will be output ?
int function()
{   static int a=0;
    a=a+1;
    return a;
}
main()
{   function();
    function();
    printf("%d", function());
}

Q4)  What will be output ?
int main(){
    int x=5;
    printf("%d %d %d\n",x,x<<2,x>>2);
}

Q5)
int main(){
 int i=5;
 printf("%f",i);
    return 0;
}

Q6) What is the Error?
main()
{ int x=3;
return;
}

Q7) What will be output ?
struct ABC
{
    int var1,var2;
    void (*func);
};
int max (int x, int y)
{
     return (x>y)?x:y;
}
int main () {
   struct ABC abc;
   abc.var1=5; abc.var2=8;
   abc.func = max(abc.var1,abc.var2);
   printf("%d",abc.func);
   return 0;
}


---------------------------------------------------------------------------------------------------------
ANSWERS::
1)
It will print, N times “hello” and then by N+1 times “world”.
First it will call print function recursively N times and will print world after it comes out of the if block. “world” is printed N+1 times since when n ==0, it will not go inside if block and will print world and return.

2)
Answer:: Statement 4 and 6

3)
Answer::3

4)
Answer:: 5 20 1

5)
Answer::0.0033 or any decimal value

6)
Answer:: Return type of main is not defined even-though return statement is used

7)
Answer::8  :: This is the way in which we can define function for structure in C. We define pointer of function pointer instead of function itself in structure.

Thursday, May 12, 2016

Basic puzzle questions in C :: MUST KNOWN concepts to every programmers

Basic puzzle questions in C :: MUST KNOWN concepts to every programmers
Please try the below puzzles, which are very basic and also very useful in clearing the concept. Find the answer of all the puzzles in last page.

What will be the output of C puzzles below :-
Q 1>
#include<stdio.h>
int main()
{
  char *p=(char *)malloc(sizeof(char)*4); p="abc";
   char q[]="abc123";
     if(p[0]=q[0])
   {
       printf("%c, %c\n",*p,*q);
   }
}

Q 2>
#include<stdio.h>
int main()
{
  char *p=(char *)malloc(sizeof(char)*4); p="abc";
   char q[]="abc123";
     if(q[0]=p[0])
   {
       printf("%c, %c\n",*p,*q);
   }
}


Q 3>
main(){
    int num[] = {1,4,8,12,16};
    int *p,*q;
    int i;
    p =  num;
    q = num+2;
    i = *p++;
    printf("%d, %d, %d\n",i, *p, *q);
}

Q 4>
main(){
char *a[4]={"jaya","mahesh","chandra","swapant"};
int i = sizeof(a)/sizeof(char *);
printf("i = %d\n", i);
}

Q 5>
void fun(int *a, int *b)
{
 int *t;
 t=a;
 a=b;
 b=t;
printf(%d, %d\n",*a, *b);
}
main()
{
     int a=2;
     int b=3;
     fun(&a,&b);
     printf(%d, %d\n",a, b);
}

Q 6>
main(){
    int i =0;
    i = 2+3, 4>3, 3;
    printf("%d", i);
}

Q 7>
main(){
    printf("%u", -1);
}

Q 8>
struct ABC{
    float a:10;
    int b:6;
    char c;
} structure;
int main(){
    int i = sizeof(struct ABC);
    printf("%d", i);
}

Q 9>
#include<stdio.h>
int main() {
    char x[] = "abc";
    char *y = x;
    *y ='1';
    printf("%s",y);
}

Q 10>
main(){
    int i =0;
    i = 4>3, 2+3, 3;
    printf("%d", i);
}

Q 11>
#include<stdio.h>
void fun(int str,...);
int main()
{
    fun(6,"Hello","World","5","6","7","8");
    return 0;
}
void fun(int str,...)
{
    int i;
    int *n=&str;
    for(i=1;i<=str;i++)
    printf("%s ",*(n+i));
    return 0;

}

ANSWERS::
1> Segmentation Fault
   Reason-> We can't assign value to pointer valriable like this.
Different ways to assign value to pointer valriable. 
char *p="Hello World";
char *p=new char[11];  p="Hello World";
Wrong ways which lead to segmentation fault::
p[0]='a'; if(p[0]=='a'){};  *p='a'; if(*p=='a'){};
2> a, a

3> 1, 4, 8

4> 4

5> 3, 2
   2, 3
6> 5
   Explanation:: It stores only the first value.

7> 4294967295   :: As the size of unsigned int is from 0 to 4,294,967,295. -1 will print the back side of zero i.e. 4294967295.

8> Compilation Error:: We cannot use but filed for Float.

9> 1bc

10> 1  ::4>3 return 1 as it is true.

11> Hello World 5 6 7 8


Please comment if you find any thing wrong also please post the questions which you feel need to be shared.

Sunday, February 21, 2016

Access the private member variables of the class without friend function and member function

We an access the private member variables of the class without friend function and member function of the class.

#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 is neither member function nor the friend function of the class ABC.
    *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();
}

Output:
a=10 and b=20

In the above example the pointer variable p_obj can access the private member variables a,b of the class ABC.
*(p_obj+1) -- It points to the next variable defined in the class. Here it points to b.
*(p_obj+n) -- By increasing the value of n we get going to access the next to next variables of the class.
p_obj will always having the base address of the class object obj.

Please let me know your comments below and correct me if you find any mistake.

Sunday, January 31, 2016

RoHS

RoHS Explained

RoHS - Restriction of Hazardous Substance

Sometimes we see RoHS in the Printed Circuit Board (PCB) and we just leave then by thinking that there may be some parameter. But today I am going to explain below about this RoHS.

RoHS is short for Directive on the restriction of the use of certain hazardous substances in electric and electronic equipment and it was adopted by European Union in February 2003.

It is an European legislation that bans six hazardous substances from manufacturing processes: cadmium (Cd), mercury (Hg), hexavalent chromium (Cr (VI)), polybrominated biphenyls (PBBs), polybrominated diphenyl ethers (PBDEs) and lead (Pb).
RoHS is also known as "Lead free Directive" but this law deals with other five substances as well.
This legislation is effective July 1st, 2006 and from this date on products using these substances cannot be sold in Europe anymore. Together with RoHS, another directive dealing with the recycling of electrical and electronic equipment, called WEEE (Waste from Electrical and Electronic Equipment), will take place.
Because of RoHS, manufacturers of electronic equipment will have to rush to deliver lead-free equipments in order to be able to sell their products in Europe.

RoHS PCB
The problem is that solder traditionally uses 60% of tin (Sn) and 40% of lead (Pb) and manufacturers will have to research other materials to make solder. As you know, solder is what “glues” all the electronic components on the printed circuit board (PCB) of an electronic product. The most common replacements for lead are silver, copper and bismuth.
These alternative materials, however, bring several challenges:
·         Higher melting temperature: traditional tin/lead solder melts at 180° C (356° F) while lead-free solder melts at 227°C (441°F). This means that the electronic components must be able to support this new soldering temperature in order to allow lead-free solder to be used.
·         Still under development: tin/lead solder is used for ages and the soldering process using this alloy is very well known. Lead-free solder is still a child and a lot of research and development is still going on with several different materials. So far there is no industry standard for lead-free solder.
·         Repair: when repairing electronic equipment, the solder used should also be lead-free. The repair technician should know exactly what kind of solder was used when the equipment was manufactured. Usually this is marked on the printed circuit board (PCB) of the equipment, but this information may not be available. But it is safe to use 99C alloy (99.7% tin, 0.3% copper) when repairing lead-free equipments.
·         Visual inspection: lead-free solder joints look a lot different to traditional tin/lead joints and an untrained eye can assume that the joint is faulty.
Of course besides the solder all other pieces of the electronic equipment – like components and the printed circuit board (PCB) – should have none of the six banned materials to be considered RoHS-compliant and allowed to be sold in Europe.

Why Lead?
The whole problem is basically with the electronic waste. A lot of electronic equipments are ending their lives in open junkyards and waste dumps all around the world – many of them with no chemicals control. The water from acid rain dissolves lead and other hazardous materials from electronic equipment, and the rainwater mixed with these materials go straight to the water table and then to the drinking water.
Lead can affect almost every organ and system in the body, especially the central nervous system. Kidneys and the reproductive system are also affected. The effects are the same, whether it is breathed or swallowed. At high levels, lead may decrease reaction time, cause weakness in fingers, wrists, or ankles, and possibly affect the memory. Lead may also cause anemia.
It is interesting to note that although the electronics industry has been directly targeted for lead removal by the European law, only a small proportion of lead is actually used in electronic equipment production: only 0.49% of all manufactured lead is used in solder and only 2% of the manufactured lead is used in all electro-electronic industry. Battery manufacturing, for example, consumes 80% of the manufactured lead.

And How About the USA?
Even though the United States have no legislation similar to RoHS or WEEE, the state of California passed a law prohibiting the sale of any electronic product that would be prohibited from sale in Europe because of the presence of heavy metals. This law, which is being called “California RoHS”, was effective September 2003, with a compliance deadline of January 2007.