Monday, December 16, 2013

How to read file content with out using readline in C++!!

Below is the simple c++ program to read the whole content from file with out using readline function. The idea is, get the size of the file by moving the seek position to the end of the file and allocate the buffer space for the size and read the file content using read function into the allocated buffer.


#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
 ifstream filenumbers;

 filenumbers.open("numbers.txt");
 int length;
 //checks if input file is accessible
 if (!filenumbers) 
 {
  cout << "The input file will not open. Please restart." << endl;
  exit(1);
 }

 // move the position to end of the file
 filenumbers.seekg(0, std::ios::end);    
 // get the current position(now it is at the end of the file so length of the content)
 length = filenumbers.tellg();           
 // move the position to start of the file 
 //(coming back to start of the file)
 filenumbers.seekg(0, std::ios::beg);
 // allocate memory for a buffer of file size   
 char *buffer = new char[length];  
 // read whole content of the file into the buffer  
 filenumbers.read(buffer, length);       
 cout<<"buffer is \n"<<buffer;
 filenumbers.close();
 return 0;
}

Output:

buffer is
10
20
30
40
11 2 3 4 5

Saturday, November 23, 2013

How to access a variable from another class in CPP

How to access a variable from another class:  We can access the variable from another class by declaring the pointer variable of the class in the class where we want to access the variable.  In the below example, we tried to access the data of val which is in the class two and we are trying to set and get the value for the variable val from the class one.


Below is the code in CPP:

#include<iostream>
using namespace std;

class two{
public:
 two(){
 val=0;
 }
 ~two(){
 }
 void setVal(int x){
 val = x;
 }
 int getVal(){
 return val;
 }
private:
 int val;
};
class one{
public:
 two *b;
 one(){
 a = 0;
 b =new two();
 }
 ~one(){
 }
 void setValue(int value)
 {
  b->setVal(value);// = value;
 }
 int getValue()
 {
  return  b->getVal();
 }
private:
  int a;
};


int main()
{
 one obj;
 obj.setValue(30);
 cout<<"given value is "<<obj.getValue();
}

Output:
given value is 30

Tuesday, November 12, 2013

C program to find the Pythagorean prime!!

Below C program is to find the  Pythagorean prime of a given number. If sum of the squares of any to numbers is prime number, then that number is called Pythagorean prime.

e.g
 5 = 1*1 + 2*2.
 13 = 2*2 + 3+3

All prime numbers are not pythagorean primes. for example 7. 7 is a prime number and not pythagorean prime. So to find the pythagorean prime, first we need to the given number is prime or not. If the given number is not prime, we can stop the process there itself.

#include<stdio.h>

int fact(int x)
{
  if(x==1)
   return 1;
  fact(x*(x-1));
}
int isPrime(int x)
{
  int i;
  for(i=2;i<x;i++)
  {
    if(x%i == 0)
     return 0i;
  }
  return 1;
}
int main()
{
  int number;
  int found = 0;
  int i=0,j=0;
  printf("enter the number\n");
  scanf("%d",&number);
  if(!isPrime(number)){
   printf("To find Pythagorean prime, number should be prime \n");
   return 0;
  }
  for(i=1;i<500;i++)
  {
     for(j=1;j<500;j++)
     {
        if(i*i+j*j==number)
        {
         found = 1;
         break;
        }
     }
     if(found)
      break;
  }
  if(found)
   printf("%d is Pythagorean prime\n",number);
  else 
   printf("%d is not Pythagorean prime\n",number);
}

Output:

$ ./a.out 
enter the number
137
137 is Pythagorean prime
$ ./a.out 
enter the number
23
23 is not Pythagorean prime
$ ./a.out
enter the number
1234
To find Pythagorean prime, number should be prime

Sunday, November 10, 2013

C programs Structure union bit-fields!!

In C Programming Language, a structure is a user defined data type, which is a collection of different data types. Strutures, unions and bitfields are conceptually same, the difference in memory alignment. So defferentiate them, we need to get the size of the structure or union. Below are the sample c programs for each of them. Structures also do padding, Click here to get how padding works.

For below examples, size of int is 4 bytes(some systems allocates 2 or 8. ) and character takes 1 byte.

Structures in C: Below structure is collection of one char and one int data types. So total size should be 5 bytes(1+4). Because of memory alignment, it will allocate 4 bytes for char also, but 3 of 4 bytes in char variable or unused. So we will get the size of the structure as 8.

#include&lt;stdio.h>
struct Sample{
  char c;
  int n;
};

int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}
Output: 
$ ./a.out 
 size is 8 

Unions in C: Unions are also same as structures. But the difference in memory alignment. The size of the union is the maximum size of the data type in the union. For example in the below example, union contains one char variable and one int variable, so char takes 1 byte and int takes 4 bytes, max of (1,4) is 4 , so size of the union is 4 bytes.

#include&lt;stdio.h>
union Sample{
  char c;
  int n;
};

int main()
{
 union Sample s;
 printf("size is %u\n",sizeof(s));
}
Output: 
$ ./a.out 
 size is 4 

Bit fields in C: In the structure example we have seen, 3 bytes are unused because of memory alignment and padding. So to avoid these unused bytes, bit fields are introduced. We can specify, required bits using bitfields as shown below. We need to use colon(:) after the variable name, and specify the number of bits.

In the below example, we specified 2 bits for char and 2 bits for int, so total 4 bits (and not bytes), total size should be 4 bits, but because of memory alignment and padding, we will get 4 bytes as shown below. We will get 4 bytes until all the bits in the 4 bytes (32 bits) are used.

#include&lt;stdio.h>
struct Sample{
  char c:2;
  int n:2;
};

int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}

Output: 
$ ./a.out 
 size is 4

How structure padding works?

Structures in C programming language are collection of different data types. Click here for more details about structures.  C compiler will structure padding for the structures in the memory alignment..

Why structure padding: Structure padding will be used for fast execution. Generally memory allocation will be done basing on the size of the int for the fast execution. So to achieve this rule, if the size of the memory space is less than the size of the int (for example char it takes 1 byte), padding will be done by adding required bytes.

Lets look at the below example: In the example, structure contains char (1byte) and int(4 bytes), so total size should be 5 bytes. But because of memory alignment for fast execution, compiler will be added extra 3 bytes as a padding, and the total size of the structure will be 8 bytes.

Sample C program for Structures:
#include<stdio.h>
struct Sample{
  char c;
  int n;
};

int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}

Output:
$ ./a.out 
size is 8

Look at another example: In the below example we added extra char variable c2, still the size of the structure is same. Because char takes one byte and two chars are in sequential, so size is (1+1+2padding+4), so total size is 8 bytes.

#include<stdio.h>
struct Sample{
  char c1;
  char c2;
  int n;
};

int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}

Output:
$ ./a.out 
size is 8

Look at another example: In the below example, we added the extra char c2 after the int variable and the size of the structure is now 12 bytes. This is also due to padding. char+int+char which is equal to 1+3(padding)+4+1+3(padding).

In the above example, two chars and int takes 8 bytes, but here two chars and int takes 12 bytes. This is because of order of the variables used in the structure. For structure padding, order of the variables are  also very important.

So in the below example, first char 1byte and no chars are there after it, so 3bytes for padding, for int b bytes and for another char c2 one byte and 3 padding bytes. If another char is there after c2, only 2 bytes padding will be required.

#include<stdio.h>
struct Sample{
  char c1;
  int n;
  char c2;
}; int main() { struct Sample s; printf("size is %u\n",sizeof(s)); }

Output:
$ ./a.out 
size is 12

Wednesday, November 6, 2013

finding square root of a number without using sqrt method!!


Below code is to find the square root of a given integer number with out using sqrt math library function. Its very simple and brute force way to find the square root. This is not the best way, but one of the way to find the square root. The basic Idea is to squaring the numbers from one  and checking with the given number, if the given number is same the square of the number, then squared number is the square root of the number. If you need for more than 5000, jus modify the MAX_NUMBER in the code and run.


Limitations:

  • It works for only Integers
  • Its a brute force method


#include<stdio.h>
#define MAX_NUMBER 5000

int find_sqrt(int number)
{
 int i,product = 0;
 for(i=0;i<MAX_NUMBER;i++)
 {
   product = i*i;
   if(product==number)
     return i;
   else if(product>number)
     break;
 }
 return 0;
}

int main()
{
 int n=0,result=0;
 printf("enter the number to find the sqrt\n");
 scanf("%d",&n);
 if(n<0)
 {
  printf("enter only +ve integer value");
  return 0;
 }
 result = find_sqrt(n);
 if(result)
  printf("sqrt of %d is %d\n",n,result);
 else
  printf("not a proper value for finding the sqrt\n");
}

Output:


$ ./a.out
enter the number to find the sqrt
625
sqrt of 625 is 25

$ ./a.out
enter the number to find the sqrt
123
not a proper value for finding the sqrt

finding cube root of a number without pow method in C!!



Below code is to find the cube root of a given integer number with out using pow math library function. Its very simple and brute force way to find the cube root. This is not the best way, but one of the way to find the cube root. The basic Idea is to find the cube of the numbers from one  and checking with the given number, if the given number is same the cube of the number, then cube number is the cube root of the number. If you need for more than 5000, jus modify the MAX_NUMBER in the code and run.


Limitations:

  • It works for only Integers
  • Its a brute force method


#include<stdio.h>
#define MAX_NUMBER 5000
int find_cuberoot(int number)
{
 int i,cube= 0;
 for(i=0;i<MAX_NUMBER;i++)
 {
   cube= i*i*i;
   if(cube==number)
     return i;
   else if(cube>number)
     break;
 }
 return 0;
}
int main()
{
 int n=0,result=0;
 printf("enter the number to find the cube root\n");
 scanf("%d",&n);
 if(n<0)
 {
  printf("enter only +ve integer value");
  return 0;
 }
 result = find_cuberoot(n);
 if(result)
  printf("cube root of %d is %d\n",n,result);
 else
  printf("not a proper value for finding the cube root\n");
}
Output:

$ ./a.out
enter the number to find the cube root
15625
cube root of 15625 is 25
$ ./a.out
enter the number to find the cube root
99
not a proper value for finding the cube root

Tuesday, November 5, 2013

Bit Fiddling !!

Bit fields are one of the most important aspects of embedded programming . Let us see few tricky and interesting cases in that field .. 1. Searching for the no of bits set in a given number -- Let us see with an example how we can check for the no of bits set in a number
#include<stdio.h>
#include<sys/time.h>
#include<string.h>
#include<time.h>

char *time_stamp()
{
  static char buf[100];
  char timestamp[100];
  time_t time;
  struct timeval detail_time;
  memset (buf, 0, 100);
  gettimeofday(&detail_time,NULL);
  time = detail_time.tv_sec;

  strftime(timestamp, 100, "%Y/%m/%d %H:%M:%S", localtime(&time));
  sprintf(buf, "%s:%ld:%ld ", timestamp,
          detail_time.tv_usec /1000, detail_time.tv_usec%1000);
 
  return buf;
}

int main()
{
int test ;
int temp,i=0;
char bits_count= 0;
printf("Enter any number \n");
scanf("%d",&test);
temp =test;

printf("Time stamp 1 is %s \n",time_stamp());
/* Method -1 */
do {
if(temp & 1)
  bits_count++;
temp = temp >>1;
}while((i++)<(sizeof(int)*8));

printf("No_of_bits_set are %d\n",bits_count);
printf("Time stamp 2 is %s \n",time_stamp());

bits_count= 0;
temp =test;
/* Method - 2*/
while(temp)
{ 
 if(temp & 1)
  bits_count++;
 temp =temp >>1;
};
printf("No_of_bits_set are %d\n",bits_count);
printf("Time stamp 3 is %s \n",time_stamp());

/*Method -3 */
bits_count= 0;
temp =test;

while(temp)
{ 
 if(!((char)temp & 0xff))
 temp = temp >> 8;
 else if(temp & 1)
  bits_count++;
 temp =temp >>1;
};


printf("No_of_bits_set are %d\n",bits_count);
printf("Time stamp 4  is %s \n",time_stamp());

return 0 ;

}

Enter any number 32 <<< one of the worst case scenarios ! Time stamp 1 is 2012/11/02 23:32:47:413:450 No_of_bits_set are 1 Time stamp 2 is 2012/11/02 23:32:47:413:774 <<<< approx 300 Micro seconds No_of_bits_set are 1 Time stamp 3 is 2012/11/02 23:32:47:413:809 <<<< approx 35 Micro seconds No_of_bits_set are 1 Time stamp 4 is 2012/11/02 23:32:47:413:832 <<< approx 23 Micros !!!! :-) << similarly can be calculated for other number as well .... Enter any number 65535 Time stamp 1 is 2012/11/02 23:33:10:851:616 No_of_bits_set are 16 Time stamp 2 is 2012/11/02 23:33:10:851:973 No_of_bits_set are 16 Time stamp 3 is 2012/11/02 23:33:10:852:8 No_of_bits_set are 16 Time stamp 4 is 2012/11/02 23:33:10:852:31

Multiple declarations of global variable is valid in C


Declaring a variable multiple times globally is perfectly valid in C. This is due to the fact that variable declaration in the local function is declaration and definition, where as global variable declaration is tentative definition. That means, global variable declaration wont allocates space , until it defined or at the end the file, it allocates to zero.

Tentative Definition: when we declare the global variable, it just declares and it wont allocate space or memory to that variable, because we may declare and define the same variable in other file using extern or similar process. So to avoid these conflicts, compiler won't allocate space until all the files compiled, then allocates and initialises to zero if not initialised. And if you try to initialise while declaring the global variable more than once you will get the compilation error.

Below is the sample C Program:

#include<stdio.h>

int x;
int x; //valid
int x; //valid
int x=20; //defining here so valid
//int x=30; //invalid, redefinition
int x; //valid

int main(void)
{
printf("%d\n", x);
int x = 40;
printf("%d\n", x);
return 0;
}



Monday, November 4, 2013

C program how to find the cube of a number using recursion!!


One of my cousin asked this question. So thought of sharing this.  The tricky thing here is, if we use recursion, we dont get power of 3, we will get power of 2,4,6 ... etc. To get the cube, we need to call the recursive function two times, so that we will get the number to the power of 4, then devide that result by given number, so that you will get the given number cube.

Given number cube = number to the power of 4 / number

Below is the C program for finding the cube using recursion.

#include<stdio.h>

int iterator = 2;
int givenValue=0;
int cubeOfNumber(int number)
{
  if(!iterator)
  {
    printf("cube of %d is %d\n",givenValue,number/givenValue);
    return;
  }
  else
  {
    iterator--;
    cubeOfNumber(number*number);
  }
}

int main()
{
  int n=0;
  printf("enter the number to find the cube\n");
  scanf("%d",&givenValue);
  cubeOfNumber(givenValue); 
}

OutPut:

./a.out
enter the number to find the cube
3
cube of 3 is 27
$ ./a.out
enter the number to find the cube
25
cube of 25 is 15625

Sunday, November 3, 2013

How to print 1 to 100 without using loop in c!!


The basic idea is to repeat the process of printing number and not using any iteration loop. We can achieve this by using recursion. As most of you know that recursion is calling the same function repeatedly until it reaches the termination condition. We can do printing 1 to n numbers in two ways by using recursion.

  • Calling main function repeatedly
  • Calling user defined function repeatedly


Using main() function: We will maintain the global variable with initial value zero. and call the main() function in the main function, if the i value reaches 100 or required value(n), we will return. If the i value is not 100, print the i value and increment i and call main function.

#include<stdio.h>
int i=0;
int main()
{
  if(i>100)
   return 0;
  printf("%d ",i);
  i++;
  main();
}
Output:
$ ./a.out
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

Using User defined function: We will follow same logic as we did for above method, this time we will call user defined method withOutLoop instead of main function.

#include<stdio.h>
int i=0;
int withOutLoop()
{
  if(i>100)
   return 0;
  printf("%d ",i);
  i++;
  withOutLoop();
}
int main()
{
  withOutLoop();
}
OutPut:
$ ./a.out
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

Wednesday, October 30, 2013

Qt conversion from date to qstring and from qstring to date


Qt provides very nice library to handle Date and Time. We can use them and convert from Date and Time to Qstring and vice-versa. Below is the sample code snippets providing for both conversion from date to string and string to date in Qt.

Conversion from QDateTime to QString: Below is the sample code for converting datetime to string in Qt. Qt has many string formats to retrieve day, month, year in different formats. for more info check here.

QString dateToString(QDateTime d)
{
    //these three statements just for info.
    QString day = d.toString("dd");
    QString month = d.toString("MM");
    QString year = d.toString("yyyy");

    return d.toString("dd")+"/"+d.toString("MM")+"/"+d.toString("yyyy");
}


Conversion from QString to QDateTime: Below is the sample code to convert from string to date and if the date format string is "dd/mm/yyyy". if the format is different, you need to add corresponding order to get the proper date as the code first converts the string to list using convertQDatetoList  and from list to date as below.

QVariantList convertQDatetoList(QString dateTime)
{
    QStringList tempList = dateTime.split("/");
    QVariantList dateList;
    QListIterator i(tempList);
    while(i.hasNext()) {
     dateList.append(i.next());
    }
    return dateList;
}

QDateTime setDateFromString(QString dateString)
{
 QDateTime dt;
    QVariantList dateAsList = convertQDatetoList(dateString);
    if(dateAsList.size()==3) {
     QDate t(dateAsList.at(2).toInt(),
                dateAsList.at(1).toInt(),
                dateAsList.at(0).toInt());
     dt.setDate(t);
    }
    else {
     //date format is not valid,so setting the current date
     dt = QDateTime::currentDateTime();
    }
 return dt;
}


Thursday, October 24, 2013

What is strdup string function in C Language?

strdup string library function is used to create the duplicate string. It will do the following three steps.

  • It creates the dynamic memory (no need to use malloc/calloc)
  • It copies the content to the newly allocated memory 
  • It returns the allocated memory starting address
When we are using strdup function, we need use the free() function do deallocate memory which is allocated by strdup function, other we will get into the memory leak. Check the below sample code.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ONE_INT 1
void display()
{
     int local_a = 7;
     int *local_p = (int *)malloc(ONE_INT);
     printf("local memory location is %p\n",&local_a);
     printf("memory location using malloc is %p\n",local_p);
}
int main()
{
   char str_a[] = "Hello World";
   char *str_p = strdup(str_a);
   printf("local meory location is %p\n",str_a);
   printf("strdup memory location is %p\n",str_p);
   display();
}
OutPut:
local meory location is 0x7fff54cc0ba8
strdup memory location is 0x7fd0904000e0
local memory location is 0x7fff54cc0b7c
memory location using malloc is 0x7fd0904038a0

We can clearly observe that red colour address is from heap and blue colour address is from Stack. 

Sunday, October 20, 2013

ant build file isset property not working

One of the common mistake when checking the property value in the ant build file is putting $ in the condition check in the isset flag. for isset , just specifying the property name is fine, and $ is not required. If $ specify, it will take the property value and checks property value as a property or not. below is the sample ant build file code .


Defining a new property in Ant build file: property, name and value are key words. Syntax is given below. there is no data type for the property. we can give any value like, string, numeric or directory path, file path etc.

<!-- defining a new property -->
<property name="test" value="this is variable"/>

Accessing a property value Ant build file:  We can access property value by using $.  Prepend $ for the property name and use in the echo, condition check etc. Below is the property value access in echo.

<!-- accessing a property value -->
<echo message="test value is $test"/>


correct way of using isset: $ is not required in the condition check
<if>
  <isset property="test"/>
  <then>
     <!-- success and test is a property-->
  </then>
</if>

wrong way of using isset: Putting $ is a wrong way
<if>
  <isset property="$test"/>
  <then>
    <!-- it wont come here, because $test is not a property-->
  </then>
</if>


Thursday, October 17, 2013

What is the difference between exit() and _exit() in C and Unix

In C programming language, exit function is used to terminate the process. Exit function will be called automatically when the program is terminates. exit() cleans up the user-mode data related to library. exit() function internally calls _exit() function which cleans up kernel related data before terminating the process.

    exit() flushes the IO related buffer before exiting the process and calls the _exit() function. Where as _exit() function just terminates the process without cleaning up or flushing user data. It is not advisable to call the _exit() function in your programming until unless you are very clear. There is another function called _Exit() function which also works same as _exit() functionally. We need to use strlid.h for exit() and unistd.h for _exit() functions.

Sample code with exit function:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
        printf("Hello");
        exit(0);
}
Output:
programs$ ./a.out
Helloprograms$


Explanation: 
Result we got  as expected and there is no \n at the end, so on the same line prompt came.

Sample code with _exit function:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
        printf("Hello");
        _exit(0);
}
OutPut: 
It prints nothing. 
Explanation:
This is due to ,we called _exit() function directly, so IO related data is not flushed, so printf data is not flushed, because of this, it has printed nothing.

Sample code with _exit function with \n:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
        printf("Hello\n");
        _exit(0);
}
OutPut:
programs$ ./a.out
Hello
programs$

Explanation:
We got the output Hello,  this is due to we are forcefully flushing the data using '\n'. Infact printf() function wont print or flush the data until buffer completes or end of the character is \n. printf internally maintains some buffer.

Using GDB, we can see functions which are called when the process terminates.  giving below for your info for simple c program
int main()
{
  printf("Hello");
}

programs$ gdb a.out
GNU gdb 6.3.50-20050815 (Apple version gdb-1824) (Wed Feb  6 22:51:23 UTC 2013)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin"...Reading symbols for shared libraries .. done

(gdb) br main
Breakpoint 1 at 0x100000f14: file _exit.c, line 5.
(gdb) r
Starting program: /Users/kh1279/Desktop/practice/Blog/programs/a.out 
Reading symbols for shared libraries +............................. done

Breakpoint 1, main () at _exit.c:5
5		printf("Hello");
(gdb) 
(gdb) n
6	}
(gdb) 
0x00007fff933ab7e1 in start ()
(gdb) 
Single stepping until exit from function start, 
which has no line number information.
0x00007fff933ab808 in dyld_stub_exit ()
(gdb) 
Single stepping until exit from function dyld_stub_exit, 
which has no line number information.
0x00007fff8b4a4f74 in exit ()
(gdb) 
Single stepping until exit from function exit, 
which has no line number information.
Hello0x00007fff8b4eb576 in dyld_stub___exit ()
(gdb) 
Single stepping until exit from function dyld_stub___exit, 
which has no line number information.
0x00007fff8efa3ae0 in _exit ()
(gdb) 
Single stepping until exit from function _exit, 
which has no line number information.

Program exited with code 0377.
(gdb) 
The program is not being run.
(gdb) 

Explanation:
 you just compile your program using -g  option for gcc,  without this option, we cant use GDB. after compilation, launch GDB debugger using gdb with a.out or your program binary file. put a break point at main function and forward using next or n gdb command. You can find the exit and _exit functions calling in the above gdb process in red colour.

Sunday, October 13, 2013

What is the return type of the printf() function in C


printf  function return type is integer. As most of us knows that, printf function is used to print content in the specified format on the standard output. It returns the no.of characters it printed on the standard out put device. i.e for hello string, printf function returns 5 as length of the string is 5 and for integer value 200, printf returns 3  as 200 contains three characters. and for float value 20.034 it returns 6 as it has 6 characters including dot. printf treats \n as a character, so if you use \n in the printf function, return value includes \n as well. sample code and syntax , see below.

Syntax for printf function in C:


int printf(const char * restrict format, ...)


Example with characters:

#include<stdio.h>
int main()
{
    int i = printf("string is %s","hello");
    int j = printf("\n%s","hello");
    printf("\ni value is %d\n",i);
    printf("j value is %d\n",j);
}

OutPut: 

string is hello
hello
i value is 15
j value is 6


Example with Integers:
#include<stdio.h>
int main()
{
    int j=200;
    int k=20;
    int i = printf("%d",j);
    int l = printf("\n%d",k);
    printf("\ni value is %d\n",i);
    printf("l value is %d\n",l);
}
OutPut: 

200
20
i value is 3
l value is 3


Example with Float and character:

#include#include<stdio.h>
int main()
{
    float k=20.034;
    int c='a';
    int i = printf("%d",c);
    int a = printf("%c",c);
    int l = printf("\n%f",k);
    printf("\ni value is %d\n",i);
    printf("a value is %d\n",a);
    printf("l value is %d\n",l);
}

OutPut:

97a
20.034000
i value is 2
a value is 1
l value is 10

Saturday, October 5, 2013

What is the return value of the main() function in C?

As per standard C , main() function always returns int. mostly zero if it is success and error code if it fails. some compilers accepts void as a return type for main() function. But standard compilers like gcc will give you the warning at the time of compilation saying that void is not allowed as a return type for the main() function.

#include<stdio.h>
void main()
{
        printf("testing return type for main");
}

Below is the warning message you will get when compiling using GCC for the above sample code:

$ gcc main.c
main.c: In function ‘main’:
main.c:3: warning: return type of ‘main’ is not ‘int’


Why main() returns int: In C , main() is the  user entry point to execute the code, so whatever writing the code in main, it is user specified code. But internally C execute many functions before and after the main function to startup and exit the program/application.  So when exiting C program, it calls exit() function and it internally calls _exit() function to exit the program. This exit process, specifies whether exit process completed successfully or any failure occurred due to some reason. If success it returns zero and if it fails it will return error code which is generally a numeric value. so logically it should return integer.

Friday, October 4, 2013

How to call function before main() function in C

Calling a user defined function before main() function: This is possible using function attributes. The standard C supports attributes syntax which is compiler dependent. C also supports type attributes, variable attributes. For more details about attributes click here.

     Using function attributes, we can call the function before the main function by specifying the parameter as constructor. This will be called at startup and mostly when shared libraries are called. We can also use destructor for calling the method after main() function, which indicates the exit of the application/program.

Below is the sample code:

#include&lt;stdio.h>
void beforeMain() __attribute__((constructor));
void afterMain() __attribute__((destructor));

void beforeMain()
{
        printf("before main \n");
}

void afterMain()
{
        printf("after main \n");
}


int main()
{
        printf("In main function \n");
        printf("leaving main function \n");
}

Output: below is the result of the above program.

$ ./a.out
before main
In main function
leaving main function
after main

Explanation: This is because of function attribute constructor will be called at the time of start, before main() function and function attribute destructor will be called at the time of exit, after the main() function.


Sunday, September 29, 2013

Introduction to C programming Language

What is language: A language is a communication medium or interface between two different systems. or a language is set of rules which can be mutually understandable.

Natural Languages: The Natural languages like English, Telugu, Hindi are used to communicate between the human beings. Each natural language has set of rules called grammar.

Programming language: As language is communication medium, programming language also a communication medium/interface between machine and human being. E.g: Assembly language, C, C++, JAVA, PHP. There are two types of programming languages namely

  • Low level languages
  • High level languages

Low level languages: As machine understands only binary data like 0 or 1, so machine language is binary language. And human does not understand huge binary code, we need interface to communicate which low level language called assembly language. These are processor dependent languages. Which have limited no. of instructions like ADD, MOV, INC, JMP.
High Level languages: As humans cant remember all the assembly level instructions, so we have high level languages like JAVA, C++, PHP, Python. High level languages have the instruction similar to natural language instructions like if, while, for etc.


Natural Language Vs Programming Language: As both are languages, difference is natural languages are context sensitive and where as programming languages are context free. Context sensitive means depending on the context meaning will change. Where as for context free means, there is only one meaning, there is no context.

E.g: for Context sensitive

  • I like Cricket
  • He is playing cricket like Sachin
Here for Like , there is a separate meaning in both the sentences.


Introduction to C Language: C is a general-purpose programming language initially developed by Dennis Ritchie. C is one of the most widely used programming languages of all time. And C is used to develop applications in different domains like

  • System programs (operating systems, compilers, assemblers)
  • Embedded systems
  • Numerical computations
  • Graphical applications 
  • Security applications
C language supports both low level language and high level language features. C is very efficient and power full language as it directly interacts with hardware using low level features. Because of this features, most of the applications which need efficiency and fast execution are developed in C language. Unix operating system itself developed in C Language. Below are the some of the unique features of C.


There are different types of compilers. well known compilers are given below. For more C compilers click here.

  • GCC
  • Turbo C or Borland C 




Saturday, September 28, 2013

C programming language tutorials


C Programming language Basics:
  • Introduction to C Language
  • C keywords and identifiers
  • C variables and constants
  • C programming data types
  • C input/output
  • C programming operators
  • C Introduction examples
Decision and loops:
  • C programming if..else
  • C programming for loops
  • C do..while loops
  • C break and continue
  • C Switch ..case statement
  • C programming goto
  • Decision and loop examples
C programming language functions:
  • C function introduction
  • C user defined functions
  • C function types
  • C programming recursion
  • C storage class
  • C function example
Arrays and strings:
  • C arrays introduction
  • C multi-dimensional arrays
  • C arrays and functions
  • C programming strings
  • C string functions
  • C array examples
  • C string examples
C programming language pointers:
  • C pointer introduction
  • C pointers and arrays
  • C pointers and functions
  • Memory Management
  • Dynamic memory allocation
  • C pointer examples
Structure and union:
Bitwise Operators:
  • AND, OR, XOR,NOT
  • Common bitwise operations
  • Bit-fields


C programming language Miscellaneous:
  • C enumeration
  • C pre-processors
  • Precedence and associativity
  • C library functions
  • C programming examples



Thursday, September 19, 2013

BB10 How to know the network status

Recently I came across a scenario where we need to retrieve the network status in the BB10 Application. As we are implemented the App using Qt frame work 4.8, this Qt framework does not have any API/method to get the network status. Here I got one API which is provided by Blackberry team for the BB10.0.

netstatus_get_availability is the method to get the network status in the BB10 OS. And Below is the syntax for that method. This method works only in BB10.0. Its depreacated for later versions and introduced new method netstatus_get_info().
Syntax:
BPS_API int netstatus_get_availability(bool *is_available)

In the document they specified, need to add libbps library,  but without including libbps also application working fine.For updated API' and for more information for retrieving network status for the BB10.

http://developer.blackberry.com/native/reference/core/com.qnx.doc.bps.lib_ref/com.qnx.doc.bps.lib_ref/topic/netstatus_get_availability.html


Thursday, August 15, 2013

The Unix file system!!


The Unix file system is divided into four sequential blocks namely Boot block, Super block, Inode block and the data block as shown below. In all the blocks except data blocks, all are fixed at the time of creation. and data blocks will be changed when the file content is changed.


The Boot Block:  This block is starting of the file system and booting code (bootstrapping) will be stored here.Each file system should have one boot block to boot the system. Only one boot block is need to boot the system and if you have more than one file systems, other boot blocks will be empty. So for starting the machine, Operating systems reads the data from boot block to load.
The Super Block: This block specifies the status of the file system. It provides the information like how much space available, how large the file system, total size of the disk, total used blocks, bad blocks etc.
The Inode Block: This blocks specifies the information about the files. each file will have one unique inode (information node) on the disk. The inode contains the information like owner of the file, file type, permissions of the file etc.
The Data Blocks: This block starts immediately after the inode block and this block contains actual data or file content. It also contains other files which contains user data like FIFO, regular files, directory files, character special , block special and socket files etc.

I will post in detail about the Inode structure later.



Tuesday, August 13, 2013

What is ipa file for iPhone and how to open it?


What is ipa file:
ipa is the extenstion of the iPhone Application file. Mostly known as the iPhone Application archive which contains the payload which need by iPhone app mostly images and sound files.

Where can I find ipa file:
 we can find the ipa file at the below location in the mac system. You can find all the application ipa files which are installed in the connected iPhone.
~/Music/iTunes/iTunes\ Media/Mobile\ Applications/

How to open ipa file:
 ipa file is just a archive file, you can rename as .zip file and you can unzip it. ipa a file contains Payload directory. if you unzip the ipa file, you will get Payload directory which contains another directory with a extension of .app. you cant open it directly, because its name has extension. So rename it with some name,it will change to directory, in this directory you can see all the supported files like images an d sound files etc.

Steps to open IPA file:
  • Got to the path ~/Music/iTunes/iTunes\ Media/Mobile\ Applications/
  • Select the ipa which you want to unzip, rename it to zip file using mv unix command
  • unzip the file and you will get payload directory, open Payload directory
  • you will find .app file, which is actually a directory. rename the file with some name, it becomes the directory
  • open that directory, you will find the supported files

Shell commands order to open ipa file:

$ cd ~/Music/iTunes/iTunes\ Media/Mobile\ Applications/
$ ls
test.ipa
$ mv test.ipa test.zip
$ ls
test.zip
$ unzip test.zip 
$ ls
Payload  test.zip
$ cd Payload/
$ ls
test.app
$ mv test.app testDir
$ ls
testDir
Let me know or comment below if you need any info or if you find any issue.

Thursday, August 8, 2013

reversing a given string using recursion C program!!

Below is the simple C program for reverse a given string using recursion.  Check here for non-recursive ways to reverse a string.

#include<stdio.h>
#include<string.h>


void reverse(char *str2,char *str1 )
{
  if(*str1)
  {
     str2[strlen(str1) - 1] = str1[0];
     reverse(str2, str1+1);
  }
}

int main()
{
  char str1[20],str2[20];

  printf("Enter a string for str1 :");
  gets(str1);
  printf("\n Source string:%s",str1);

  memset (str2, 0, 20);

  reverse (str2, str1);
  printf(" \n Destination string:%s \n",str2);

  return 0;
}

Sample Output: 
warning: this program uses gets(), which is unsafe.
Enter a string for str1 :reverse

Source string:reverse
Destination string:esrever

Let me know or comment below for any info or some bug if you find in the above code.

Sunday, July 28, 2013

Stack implementation in C

#include<stdio.h>

#define STACKSIZE 20
//stack size is 20
int stack[STACKSIZE]={0};
//top of the stack initially -1 which means empty
int tos=-1;


void push(int ele)
{
 if(tos>=STACKSIZE)
 {
  printf("err: Stack is full\n");
 }
 else
 {
  tos++;
  stack[tos] = ele;    
 }
}

int pop()
{
 if(tos==-1)
 {
  printf("err: stack is empty\n");
 }
 else
 {
  int temp = stack[tos];
  tos--;
  printf("poped element from the stack is %d\n",temp);
  return temp; 
 }
}

void display()
{
 int i;
 for(i=0;i<=tos;i++)
  printf(" %d\n",stack[i]);
 if(tos== -1)
 {
  printf("err: stack is empty\n");
  return;
 }
}
int main()
{

  int ch,ele;
  printf("enter the choice 1-push 2-pop 3-display 9-exit\n");
  scanf("%d",&ch);
  while(ch!=9)
  {
 switch(ch)
 {
  case 1: printf("Enter the ele to push\n");
   scanf("%d",&ele);
   push(ele);
   break;
  case 2: ele = pop();
   break;
  case 3: display();
   break;
  case 4:
   break;
  default:
   break;
 }

  printf("enter the choice 1-push 2-pop 3-display 9-exit\n");
  scanf("%d",&ch);
  }
}


Wednesday, July 24, 2013

BB10 Triple DES Crypto Sample App!!

In this post I am providing sample BB10 App for the crypto algorithm Triple DES. Here I have already provided the AES crypto algorithm for the BB10.

Limitations: as it is sample Application

  • It can encrypt maximum upto 40 char len string
  • if you want more than 40 len, just change the code in encrypt method
  • input should be multiples of SB_DES_BLOCK_SIZE (8)
  • if input is not multiple of 8, you will get undefined values
download the sample app from here.

Please comment below if you need any info or any bug you found.



Thursday, June 20, 2013

BB10 cryptography sample application(AES)

Here is the sample working application for BB10. I have used BlackBerry specific API's to encrypt and decrypt.  I have implemented AES and Triple DES algorithms.

Implementing Cryptographic algorithms using API's is easy as we need to use api's directly. But tricky part is conversion of QString to unsigned char*. I struggled a lot and googled , but I could not get the solution. Recently I have seen one sample for encrypting password using md5. In that example, I found the conversion of Qstring to unsigned char * and vice-verse.

Download

So providing here complete working example which may help others.

For Triple Des crypto sample BB10 algorithm refer this link.

Saturday, April 20, 2013

Simple calculator program in C!!

Recently one of my friend asked me to implement simple Application in C which reads simple calculator commands from the input file and writes the result in the output.  Below is the complete description of the problem. And  You can find the complete C programming language source code as well.

Simple Calculator Description:

The first line of the file contains two characters giving the initials of the user (such as GN). The rest of the file consists of a sequence of commands. Each line of the command file contains one command.

Each command starts with a character and may have zero or more operands. You may assume that the data file has no errors. The number of commands in the file is unknown. But your processing may stop as soon as the Quit command is processed. The commands are: integer add, integer subtract, integer multiply, integer divide, change to uppercase, change to lowercase, separate, print out all digits, printout the k-th digit, round real number to desired number of decimal places, divide number into two.


Calculator Commands:
-------------------------------------

+ i j [Integer Add]                        Add integers i and j and print out result

* i j [Integer Multiply]                  Multiply integers i and j and print out result

- i j [Integer Subtract ]                  Subtract integer j from i and print out result

/ i j [Integer Divide ]                     Divide integer i by j and print out result of integer division

C Ch [Character Case Change ]    Change character Ch to uppercase and print it out

c Ch [Character Case Change]      Change character Ch to lowercase and print it out

P i k [Print k-th Digit ]                  Print out the k-th digit of integer i

R x i [Round Reals ]                     Round double value x to i decimal places

S x [Separate ]                               Separate out the sign, integer part and fractional part of double value x

D i x [Partition Integer ]               Given integers i and x, print out two integers j and k, where the sum of j and k equals i, and when you take x% of i and truncate it you get j

H [Help ]                                       Print a short synopsis of all the available commands

Q [Quit ]                                       Quit

Click here for the C source code

C source code for simple calculator!!

Below is the complete working C source code for the simple calculator. Click here for the problem description. This programs takes the input file name as a command line argument and write the result in the output.dat in the current directory.

//
//  main.c
//  Calculator
//
//  Created by chanduthedev on 4/18/13.
//

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>


void add(int first, int second,FILE * ofp)
{
    printf("%d + %d = %d\n",first,second,first+second);
    fprintf(ofp,"%d + %d = %d\n",first,second,first+second);
    
}
void multiply(int first, int second,FILE *ofp)
{
    printf("%d * %d = %d\n",first,second,first * second);
    fprintf(ofp,"%d * %d = %d\n",first,second,first * second);

}
void substract(int first, int second, FILE *ofp)
{
    
    printf("%d - %d = %d\n",first,second,first-second);
    fprintf(ofp,"%d - %d = %d\n",first,second,first-second);

}
void divide(int first,int second, FILE * ofp)
{
    
    fprintf(ofp,"%d / %d = %d\n",first,second,first/second);
    printf("%d / %d = %d\n",first,second,first/second);
}
void toUpperCase(char ch, FILE * ofp)
{
    printf("%c ==> %c\n",ch,toupper(ch));
    fprintf(ofp,"%c ==> %c\n",ch,toupper(ch));
}
void toLowerCase(char ch,FILE * ofp)
{
    printf("%c ==> %c\n",ch,tolower(ch));
    fprintf(ofp,"%c ==> %c\n",ch,tolower(ch));

}
void printKthDigit(int val, int k,FILE * ofp)
{
    int i=1;
    int temp =val;
    while(temp >0)
    {
        if(i == k)
        {
            printf("%d (digit @ %d) ==> %d\n",val,k, temp%10);
            fprintf(ofp,"%d (digit @ %d) ==> %d\n",val,k, temp%10);

            break;
        };
        i++;
        temp = temp/10;
    }
    
}
void roundDecimal(double x, int n, FILE * ofp)
{
    char temp[32]="";
    
    double  rounded = round(x);
    
    sprintf(temp,"%.*lf",n,rounded);
    printf("%lf (precision=%d) => %s\n",x,n,temp);
    fprintf(ofp,"%lf (precision=%d) => %s\n",x,n,temp);
    
}

void separte(double x , FILE * ofp)
{
    char temp[32]="";
    char sign;
    int intPart;
    int fraction;
    sprintf(temp,"%lf",x);
    
    sscanf(temp,"%d.%d",&intPart,&fraction);
    
    if(intPart > 0)
        sign = '+';
    else
    {
        sign = '-';
        intPart = -1 * intPart;
    }
    printf("%lf ==>  sign=%c, integer=%d,fraction=%d\n",x, sign,intPart,fraction);
    fprintf(ofp,"%lf ==>  sign=%c, integer=%d,fraction=%d\n",x, sign,intPart,fraction);

}
void partitionInteger(int i, int x, FILE * ofp)
{
    int j;
    int k;
    
    j = floor(x* i/100.0);
    
    k = i-j;
    
    printf("i=%d,x=%d ==>  j=%d, k=%d \n",i,x,j,k);
    fprintf(ofp,"i=%d,x=%d ==>  j=%d, k=%d \n",i,x,j,k);
}
void help( FILE * ofp)
{
    printf("\n *** Help Menu! See below for Calculator Commands: ***\n");
    printf("\n + i j ---> Add integers i and j \n");
    printf("\n * i j ---> Multiply integers i and j \n");
    printf("\n + -i j ---> Subtract integer j from i \n");
    printf("\n /i j ---> Divide integer i by j \n");
    printf("\n C Ch ---> Change character Ch to uppercase \n");
    printf("\n c Ch ---> Change character Ch to lowercase \n");
    printf("\n P i k ---> Print out the k-th digit of integer i \n");
    printf("\n R x i ---> Round double value x to i decimal places \n");
    printf("\n S x ---> Separate out the sign, integer part and fractional part of double value x \n");
    printf("\n D i x ---> Given integers i and x, print out two integers j and k, where the sum of j and k equals i, and when you take x'percent' of i and truncate it you get j \n");
    printf("\n H ---> view all commands \n");
    printf("\n Q ---> Quit program\n");
    
}


int main(int argc, const char * argv[])
{

    if(argc != 2)
    {
        printf("Usage ");
        exit(0);
    }
    
    const char * inFile=argv[1];
 
    char str[64];
    int lineNum=1;
    int first,second;
    double firstDouble;
    char ch;
    char outFile[]="outData.dat";
    
    FILE * ofp = fopen(outFile,"w");
    
    FILE * fp = fopen(inFile,"r");
    while(fgets(str,64,fp) != NULL)
    {
        if(lineNum == 1)
        {
            printf("Initial %s",str);
        }
        else
        {
            char * temp = str;
            char cmd = temp[0];
            temp++; //ignore command
            temp++; //ignore space;
                
            printf("CMD=%c : ",cmd);
            if(cmd == '+')
            {
                sscanf(temp,"%d %d",&first,&second);
                add(first,second,ofp);
            }
            else if (cmd == '*')
            {
                sscanf(temp,"%d %d",&first,&second);
                multiply(first,second,ofp);
            }
            else if (cmd == '-')
            {
                sscanf(temp,"%d %d",&first,&second);
                substract(first,second,ofp);
            }
            else if (cmd == '/')
            {
                sscanf(temp,"%d %d",&first,&second);
                divide(first,second,ofp);
            }
            else if (cmd == 'C')
            {
                sscanf(temp,"%c",&ch);
                toUpperCase(ch,ofp);
            }
            else if (cmd == 'c')
            {
                sscanf(temp,"%c",&ch);
                toLowerCase(ch,ofp);
            }
            else if (cmd == 'P')
            {
                sscanf(temp,"%d %d",&first, &second);
                printKthDigit(first,second,ofp);
            }
            else if (cmd == 'R')
            {
                sscanf(temp, "%lf %d",&firstDouble,&second);
                roundDecimal(firstDouble, second,ofp);
            }
            else if (cmd == 'S')
            {
                sscanf(temp,"%lf",&firstDouble);
                separte(firstDouble,ofp);
            }
            else if (cmd == 'D')
            {
                sscanf(temp,"%d %d",&first,&second);
                partitionInteger(first,second,ofp);
            }
            else if (cmd == 'H')
            {
                help(ofp);
            }
            else if (cmd == 'Q')
            {
                break;//quits
            }
            else
            {
                printf("Function Z not implemented yet!");
            }
        }
        lineNum++;
    }
    
    fclose(fp);
    fclose(ofp);
    return 0;
}


Input file format:

KING
H
+ 2 5
- 10 5
* 8 9
/ 92 3
c A
C b
P 56234 3
R 3.64195 2
S -51.235
D 50 10

OutPut:
2 + 5 = 7
10 - 5 = 5
8 * 9 = 72
92 / 3 = 30
A ==> a
b ==> B
56234 (digit @ 3) ==> 2
3.641950 (precision=2) => 4.00
-51.235000 ==>  sign=-, integer=51,fraction=235000
i=50,x=10 ==>  j=5, k=45


Thursday, March 28, 2013

iPhone developement slides


Here are the slide for the iOS development topics
  1. Introduction to iOS
  2. Views in iOS
  3. ViewControllers
  4. StoryBoards
  5. Notifications n KeyPadHiding
  6. Gestures
  7. CustomeGestures
  8. ViewHeirarchy, ResponderChain
  9. iOSArchitecture
  10. DataPersistence
  11. SQLite3
  12. CoreData
  13. XML n JSONParsing
  14. Communicating with WebServices
  15. AudioVideo Foundation
  16. Camera, Accelorometer
  17. Memory Crash issues
  18. UIPageViewController
  19. AutoLayout, iCloud
Download from this link.



Thursday, March 21, 2013

ObjectiveC slides

Here are the slides for the ObjectivC topics which given below.
  1. Introductin to ObjectiveC
  2. Objects, Classes, Messages in ObjectiveC
  3. OOPS concepts in ObjectiveC
  4. Properties in ObjectiveC
  5. protocols n Categories in ObjectiveC
  6. Selectors in ObjectiveC
  7. FoundationClasses in ObjectiveC
  8. NSString n NSNumber in ObjectiveC
  9. NSArray n NSData in ObjectiveC
  10. Dictionary, Range, Date in ObjectiveC
  11. NSFileManager, NSFileHandle in ObjectiveC
  12. Memory Management in ObjectiveC
  13. Blocks and GCD
Download slides from here.


Saturday, March 16, 2013

C programming language slides

 Here are the complete slides for all the topics in the C Programming language. Given URL is a downloadable link for the zip file which contains the slides for all the topics given below.
  1. Introduction to C programming language
  2. C Language Basics
  3. Operators
  4. control statements
  5. Switch statements
  6. looping Statements
  7. Arrays
  8. Functions
  9. Structures-Unions-typedef
  10. Pointers
  11. Char and Strings
  12. Memory Management
  13. Storage Classes
  14. Miscellaneous
Download from this link.


Tuesday, January 29, 2013

typeof operator in javascript!!

The typeof operator in javascript is used to find the data type of the variables or operands. typeof returns a string which includes any one of the below list.
  • number: it returns this string if the input to the typeof is number
  • string: it returns this string if the input to the typeof is string
  • boolean: it returns this string if the input to the typeof is boolean
    • The string is boolean and not bool
  • object: it returns this string if the input to the typeof is javascript
  • undefined: it returns this string if the input to the typeof is a variable and which is not defined
Syntax:
      typeof operand   // braces are optional
      typeof(operand)

Example:
       typeof 2 //returns number
       typeof(2) //returns number
       typeof("2") // returns string
       typeof(a) // a is a variable and returns depending on a value

Sample code:
function typetest()
{
 var a = 2; //number type
 var a = "2"; // string type
 var a;  //undefined
 var a =  true; //boolean type
 var a =  {a:"first character",b:"second character"}; // object type

 if(typeof a == "number")
  alert("a is number");
 else if(typeof a == "string")
  alert ("a is string");
 else if(typeof a == "undefined")
  alert ("a is undefined"); 
 else if(typeof a == "boolean")
  alert ("a is boolean"); 
 else if(typeof a == "object")
  alert ("a is object");  
}

This function gives object as output, because javascript overrides the variable declarations, so latest declaration will take, here it is javascript object. This variable overriding is called variable hoist. I will write one post on this later.

Thursday, January 17, 2013

wamp server asking password in xp


Recently when I try to start the wamp server in my freinds laptop I faced this problem. And sharing the solution for that problem here.

The reason for this may be because of running IIS server in your system. To solve this problem either disable the IIS server. Follow below steps to disable IIS server.
  1. Goto control panel
  2. Goto Add/Remove programs
  3. Goto Add/Remove Windows components
  4. Uncheck IIS
Then restart the wamp server. This time it wont ask for the password.


Popular Posts