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

Popular Posts