Wednesday, 15 April 2015

Contents

CONTENTS

PROGRAMS IN C


        Programs on arrays



     
       Programs on linked list





Tips & Tricks in C language




NUMBERS 



      The 0's story

      Beauty of maths

Interview Experiences




Interesting facts 


     
     Why GOOGLE used specific colors in its logo

     How to watch youtube videos without ads

     Access your WhatsApp from your Desktop Browser

Securuty


Famous quotes




Tuesday, 14 April 2015

Bit Fields in C Language

Bit Fields allow the packing of data in a structure or a Union with specified number of bits. This is especially useful when memory or data storage is at a premium or you have data with sizes different from normal datatypes

Example:
IP header can be declared as follows

typedef struct
{
      unsigned Vers                              : 4  ;/* Version number.*/
      unsigned IHL                               : 4  ;/* ethernet Header Length*/
      unsigned TOS                             : 8  ;/* Type of Service.*/
      unsigned TotalLength                  : 16 ;/* Total Length is the length of the datagram.*/
      unsigned Identification                 : 16 ;/* identifying fragments of a datagram.*/
      unsigned Flags                            : 3  ;/* Control Flags (Bit0:res,Bit1:1 = Don't Fragment,Bit2:0 = Last Fragment)*/
      unsigned FragmentOffset             : 13 ;/* Indicates where in the datagram this fragment belongs */
      unsigned TimeToLive                  : 8  ;/* Time to Live */
      unsigned Protocol                       : 8  ;/* Indicates the next level protocol used*/
      unsigned HeaderChecksum         : 16 ;/* checksum on the header only*/
      unsigned SourceAddress            : 32 ;/* Source address*/
      unsigned DestinationAddress      : 32 ;/* Destination address*/
} S_IPv4Header;


the above code will create a structure IPv4Header  which will contain elements
ver                             whose size is 4  bits,
IHL                           whose size is 4  bits,
TOS                          whose size is 8  bits,
TotalLength               whose size is 16 bits,
Identification              whose size is 16 bits,
Flags                         whose size is 3  bits,
Flags                         whose size is 3  bits,
FragmentOffset          whose size is 13 bits,
TimeToLive               whose size is 8  bits,
Protocol                    whose size is 8  bits,
HeaderChecksum      whose size is 16 bits,
SourceAddress          whose size is 32 bits,
DestinationAddress    whose size is 32 bits,

Monday, 13 April 2015

Write a C macro PRINT(x) which prints x , where x can be of any data type (string or char or int etc..)


At the first look, it seems that writing a C macro which prints its argument is very easy  Following program should work i.e. it should print x

#include<stdio.h>
#define PRINT(x) printf("%s",(x));
main()
{
PRINT(x);
}

OR

#include<stdio.h>
#define PRINT(x) (x)
int main()
  printf("%s",PRINT(x));
  return 0;
}


But it would issue compile error because the data type of x, which is taken as variable by the compiler, is unknown. Now it doesn’t look so obvious. Isn’t it? 

Guess what, the followings also won’t work
#define PRINT(x) ('x')
#define PRINT(x) ("x")

magic of Stringizing Operator

But if we know one of lesser known traits of C language, writing such a macro is really simple. In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string. Voila! it is so simple to do the rest. So the above program can be modified as below.


#include<stdio.h>
#define PRINT(x) printf("%s",(x));
main()
{
PRINT(x);
}

OR 

#include<stdio.h>
#define PRINT(x) (#x)
int main()
  printf("%s",PRINT(x));
  return 0;
}
or 

Now if the input is PRINT(x), it will print x and PRINT(aravind) will print aravind

Wednesday, 8 April 2015

How to read a string with spaces using scanf

How to read a string with spaces using scanf

#include<stdio.h>
void main()
{
char str[100];
printf("Enter any string\n");
scanf("%[^\n]s",str);         //<----- Imp step--------
printf("\n You entered string %s \n",str);

}

Tuesday, 7 April 2015

COMMA operator


// PROGRAM 1

#include<stdio.h>


int main(void)

{

    int a = 1, 2, 3;

    printf("%d", a);

    return 0;

}
The above program fails in compilation, but the following program compiles fine and prints 1.

// PROGRAM 2

#include<stdio.h>


int main(void)

{

    int a;

    a = 1, 2, 3;

    printf("%d", a);

    return 0;

}
And the following program prints 3, why?

// PROGRAM 3

#include<stdio.h>


int main(void)

{

    int a;

    a = (1, 2, 3);

    printf("%d", a);

    return 0;

}
In a C/C++ program, comma is used in two contexts:
                           (1) A separator
                           (2) An Operator.
Comma works just as a separator in PROGRAM 1 and we get compilation error in this program.
Comma works as an operator in PROGRAM 2. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3″ becomes equivalent to “(a = 1), 2, 3″. That is why we get output as 1 in the second program.
Comma works as an operator in PROGRAM 3. Precedence of comma operator is least in operator
precedence table, but as we applied ( for comma operator, So the comma operator takes precedence over assignment and the expression “1, 2, 3″  is calculated first (result of this is 3 ) then that result is assigned to a . That is why we get output as 3 in the third program.

PLEASE WRITE COMMENT WHERE I AM WRONG   OR ANY NEW IDEA IN YOUR MIND.......!!!!!

Wednesday, 1 April 2015

Interesting facts about betwise operators in C

There are 6 types bitwise operators in C which will work at bit-level:

& (bitwise AND)  This operator will take two numbers as operand and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.

| (bitwise OR)  This operator will take two numbers as operand and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.

^ (bitwise XOR) This operator will take two numbers as operand and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.

<< (left shift) This operator will take two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.

>> (right shift) This operator will take two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.

~ (bitwise NOT) This operator will take one number and inverts all bits of it.

Now look at the example which demonstrate the use of all bitwise operators

/* C Program to demonstrate use of bitwise operators */
#include<stdio.h>
int main()
{
    unsigned char a = 5, b = 9; // a = 4(00000101), b = 8(00001001)
    printf("a = %d, b = %d\n", a, b);
    printf("a&b = %d\n", a&b); // The result is 00000001
    printf("a|b = %d\n", a|b);  // The result is 00001101
    printf("a^b = %d\n", a^b); // The result is 00001100
    printf("~a = %d\n", a = ~a);   // The result is 11111010
    printf("b<<1 = %d\n", b<<1);  // The result is 00010010
    printf("b>>1 = %d\n", b>>1);  // The result is 00000100
    return 0;
}

Facts about bitwise operator: 
No negative number should be used for the left shift and right shift operators We will get an undefined result if we take negative operands for << and >>. For example, results of both -3 << 3 and 3 << -3 are undefined.

The most useful operator from technical interview is  the bitwise XOR operator Wheniniagven set of numbers where all elements occur even number of times except one number, finds the odd occurring number, this problemcanbeefficientlysolvedbyjustdoingXOR of all numbers.
// Function to return the only odd occurring element

int findOdd(int arr[], int n){
   int res = 0, i;
   for (i = 0; i < n; i++)
     res ^= arr[i];
   return res;
}
int main(void) {
int arr[] = {12, 12, 14, 90, 14, 14, 14};
int n = sizeof(arr)/sizeof(arr[0]);
printf (“The odd occurring element is %d “, findOdd(arr, n));
return 0;
}
// Output: The odd occurring element is 90

Bitwise operators should not be interchanged with logical operators Because bitwise operators return an integer value and result of logical operators (&&, || and !) is either 0 or 1, Also the logical operators consider any non-zero operand as 1.

int main()
{
   int x = 2, y = 5;
   (x & y)? printf("True ") : printf("False ");
   (x && y)? printf("True ") : printf("False ");
   return 0;
}
// Output: False True
The left-shift and right-shift operators are equivalent to multiplication and division by 2 respectively.
As mentioned in point 1, it works only if the numbers are positive.
int main()
{
   int x = 19;
   printf ("x << 1 = %d\n", x << 1);
   printf ("x >> 1 = %d\n", x >> 1);
   return 0;
}
// Output: 38 9

We can check whether the number is odd or even with bitwise operators The number is odd if the value of expression (x & 1) would be non-zero, otherwise the value would be zero.

// Note that the output of following program is compiler dependent
int main()
{
   unsigned int x = 1;
   printf("Signed Result %d \n", ~x);
   printf("Unsigned Result %ud \n", ~x);
   return 0;
}
/* Output:
Signed Result -2
Unsigned Result 4294967294d */


Carefully use the ~ operator The result of ~ operator can  be a negative number if the result is stored in a signed variable (assuming that the negative numbers are stored in 2’s complement form where leftmost bit is the sign bit) and result on a small number can be a big number if the result is stored in a unsigned variable.

Program to print File name, Date, Time, and line number in C

There are some standard macros which can be used to print program file (__FILE__), Date of compilation (__DATE__), Time of compilation (__TIME__) and Line Number in C code (__LINE__)
#include <stdio.h>

int main()
{
   printf("Current File :%s\n", __FILE__ );
   printf("Current Date :%s\n", __DATE__ );
   printf("Current Time :%s\n", __TIME__ );
   printf("Line Number :%d\n", __LINE__ );
   return 0;
}
/* Output:
Current File :C:\Users\GfG\Downloads\deleteBST.c
Current Date :Feb 15 2014
Current Time :07:04:25
Line Number :8 */

Thursday, 5 March 2015

“FREAK” Security Flaw Discovered Lurking In Many Computers For Decades

Ugh — another week, another nasty widespread security bug to worry about. The twist this time: this one has apparently been around since the 90s.
Dubbed “FREAK” by the researchers who discovered it, the exploit allowed researchers (and potentially hackers) to sniff traffic going to and from many otherwise encrypted websites — including some government sites — thanks to some stuff left behind from the 90s.
Here’s the issue, as I understand it:
  • Up until 1999 or so, the US government forbade companies from shipping any products overseas that contained strong encryption. “Export-grade” (that is, weak and breakable) encryption was okay, though.
  • In the 90s, this encryption was more than enough to evade anyone who didn’t have access to a supercomputer. Nowadays, as Ed Felten points out, that’s anyone who knows their way around Amazon’s EC2.
  • These restrictions were lifted around 1999 — but somehow these weaker “export-grade” encryption modes were left in “many Google and Apple” devices (and other devices that use unpatched OpenSSL), unused and mostly forgotten… until now
  • With a cleverly executed man-in-the-middle attack, researchers were able to force a victim’s connection to use this now quite-crackable weaker encryption cipher.
  • Once the connection is on that weaker cipher, any “encrypted” communication the attacker can sniff out — passwords, messages, etc. — can be decrypted in a matter of hours.
The short version: hackers force a victim’s connection to use long-forgotten encryption ciphers left behind in popular products (Android, Apple’s Safari) instead of today’s stronger stuff, then decrypt the data.
As of this morning at 1 a.m., researchers were able to coax a good chunk of the web’s most popular sites into accepting the now-obsolete encryption request.
They’ve put up a list of some of the sites here, and it’s a doozy. Banking sites, quite a few retail sites, and even a few U.S. government sites make an appearance.
Named by the researchers as one of the larger parties at risk here, Apple was quick to respond with a promise to fix things on their end. Writes an Apple spokesperson: “We have a fix in iOS and OS X that will be available in software updates next week.”
We’ve reached out to other companies involved for comment.
Update: Google says it has made a patch that has been “provided to partners”. That likely means it’s on device manufacturers to patch this on a phone-by-phone basis.

Monday, 23 February 2015

Covert floating point number to IEEE754 format

/* prints a lot of information about floating-point numbers */

#include <stdio.h>
#include <math.h>
#include <values.h>

/* endianness testing */
const int EndianTest = 0x04030201;

#define LITTLE_ENDIAN() (*((const char *) &EndianTest) == 0x01)

/* extract nth LSB from object stored in lvalue x */
#define GET_BIT(x, n) ((((const char *) &x)[LITTLE_ENDIAN() ? (n) / CHARBITS : sizeof(x) - (n) / CHARBITS - 1] >> ((n) % CHARBITS)) & 0x01)

#define PUT_BIT(x, n) (putchar(GET_BIT((x), (n)) ? '1' : '0'))

void
print_float_bits(float f)
{
    int i;

    i = FLOATBITS - 1;
    PUT_BIT(f, i);
    putchar(' ');
    for(i--; i >= 23; i--) {
        PUT_BIT(f, i);
    }
    putchar(' ');
    for(; i >= 0; i--) {
        PUT_BIT(f, i);
    }
}

int
main(int argc, char **argv)
{
    float f;

    while(scanf("%f", &f) == 1) {
        printf("%10g = %24.17g = ", f, f);
        print_float_bits(f);
        putchar('\n');
    }

    return 0;
}

Thursday, 12 February 2015

Access your WhatsApp from your Desktop Browser

Did you ever feel that your mobile screen or your mobile keypad is too small for you to use watsapp comfortably...

Now you can easily switch on to your PC for watsapp.

Many of you might have heard of watsapp for PC and some of you might have even given a try.

It involves a tedious process of installing an emulator and then using the watsapp.

If your motto is to have a larger screen for your conversation or to use your PC keyboard for typing fast, you need not go for installing the emulators now.

There is a wonderful feature on watsapp latest versions known aswatsapp web.

This feature helps you to connect your mobile watsapp account on to your PC.

But this works only on your CHROME browser.

Just follow this simple steps and enjoy watsapp on your PC without any emulators

STEP 1: open https://web.whatsapp.com/ in your chrome browser

STEP 2: Do the following in your phone



STEP 3: scan the QR code shown in chrome browser from your whatsApp app on your phone

STEP 4: Access your whatsApp account from your Browser

PS: don't forgot to logout your account once you are done

Tuesday, 27 January 2015

Incredible Google V/S North Korea (A story about google maps)

● North Korea is so paranoid about its citizen accessing the Internet that merely owning a computer requires permission from local government authorities.

● All personal computers are registered with the Police .

● Private Ownership of fax  machines is banned outright and sending even asingle fax requires high-level authorization .

● Pirated DVD's of South-Korean Dramas are so illegal that North Koreans caught red-handed can be sentenced upto 10 years in labour camps.

Therefore, It's quite easy to estimate the number of beltings one would get for breaking an Internet law in North Korea.

Still, North Korea does have Internet -

● There is a group of privileged elites in North Korea who can access the real Internet, which is forbidden to everyone else.

● North Korea's circle of internet users is so small that country has only 1024 IP addresses for 25 million people (US has billions of IP addresses for 316 million people)  

Now, Coming to your actual question.
Here's how Google did it !


The goal of Google Maps is to provide people with the most comprehensive, accurate and easy-to-use modern map of the world.
But For a long time, North Korea was  robbed of this privilige owing to lack of data and low internet penetration.
But Google is Google.They're uber cool and had to get this done at any cost -

● A Community of citizen, Cartographers spent years using Google Map Maker to contribute to the draft.

● It commonly takes Map Maker Community a few years to generate enough high quality data to make something that works in Google Maps.

● It was only after proper collection of high quality data like - Name of Streets, Points of Interest ,Monuments, Nuclear Complexes, Prison Camps etc that the Map went live in the month of January, 2013.

This way, Google is giving the world a never-before-seen, detailed view of one of the most secretive countries in the world.
Let us all thank Google for being Super Cool because Cool nowadays is  too mainstream .

Monday, 19 January 2015

How to avoid "assignment instead of comparison "

Almost every beginning C programmer independently rediscovers
the mistake of writing:

if (i=3)

instead of:

if (i==3)

Once experienced, this painful error (doing an assignment where comparison was intended) is rarely
repeated. Some programmers have developed the habit of writing the literal first, like this:

 if (3==i)

Then, if an equal sign is accidentally left out, the compiler will complain about an
"attempted assignment to literal." This won't protect you when comparing two variables, but every

little bit helps.

Tuesday, 6 January 2015

The 0's (zeros) story

It might seem like an obvious piece of any numerical system, but the zero is a surprisingly recent development in human history. In fact, this ubiquitous symbol for “nothing” didn’t even find its way to Europe until as late as the 12th century. Zero’s origins most likely date back to the “fertile crescent” of ancient Mesopotamia. Sumerian scribes used spaces to denote absences in number columns as early as 4,000 years ago, but the first recorded use of a zero-like symbol dates to sometime around the third century B.C. in ancient Babylon. The Babylonians employed a number system based around values of 60, and they developed a specific sign—two small wedges—to differentiate between magnitudes in the same way that modern decimal-based systems use zeros to distinguish between tenths, hundreds and thousandths. A similar type of symbol cropped up independently in the Americas sometime around 350 A.D., when the Mayans began using a zero marker in their calendars.
These early counting systems only saw the zero as a placeholder—not a number with its own unique value or properties. A full grasp of zero’s importance would not arrive until the seventh century A.D. in India. There, the mathematician Brahmagupta and others used small dots under numbers to show a zero placeholder, but they also viewed the zero as having a null value, called “sunya.” Brahmagupta was also the first to show that subtracting a number from itself results in zero. From India, the zero made its way to China and back to the Middle East, where it was taken up by the mathematician Mohammed ibn-Musa al-Khowarizmi around 773. It was al-Khowarizmi who first synthesized Indian arithmetic and showed how the zero could function in algebraic equations, and by the ninth century the zero had entered the Arabic numeral system in a form resembling the oval shape we use today.

The zero continued to migrate for another few centuries before finally reaching Europe sometime around the 1100s. Thinkers like the Italian mathematician Fibonacci helped introduce zero to the mainstream, and it later figured prominently in the work of Rene Descartes along with Sir Isaac Newton and Gottfried Leibniz’s invention of calculus. Since then, the concept of “nothing” has continued to play a role in the development of everything from physics and economics to engineerin