Showing posts with label C&Cpp. Show all posts
Showing posts with label C&Cpp. Show all posts

Friday, 27 March 2015

Program to print rhombus in C


#include<stdio.h>
int main( )
{

            int n = 5, inc = 1, i, j,k;     //n is number of stars to be printed in middle row
            for (i = 1; i <= n && i >= 1; i = i + inc)
            {

                for (j = 1; j <= n - i; j++)
                   printf(" ");     //prints a space

                for (k = 1; k <= i;k++ )
                    printf("* ");   //prints star and space

                printf("\n");   //prints a new line

                if (i == n)
                    inc = -1;
            }

             return 0;
}

Program to find missing elements in an array in C


#include<stdio.h>
int main( )
{

        int a[ ]={2,4,7};    //array to be tested
        int n=sizeof(a)/sizeof(a[0]);    //length of array
        int i,j,match;

        for(i=1;i<=9;i++)    //here we are testing the missing elements from 1 to 9
        {
                 match=0;
                 for(j=0; j<n | | (match==0);j++)    //it will loop until the array ends or we found a match
                           if(a[j] = = i)
                                  match=1;
   
                  if(match==0)   //no match found
                         printf("%d  ",i);
         }
     
          return 0;
}

How to find length of an array in C or C++?


To find the length of an array in C or C++, you can use the following:

int n=sizeof(a)/sizeof(a[0]);

Here, a is array

Thursday, 1 January 2015

What is Object slicing? Give an example.

When a Derived Class object is assigned to Base class, the base class' contents in the derived object are copied to the base class leaving behind the derived class specific contents. This is referred as Object Slicing. That is, the base class object can access only the base class members. This also implies the separation of base class members from derived class members has happened.
class base
{
     public:
          int i, j;
};
class derived : public base
{
      public:
           int k;
};
int main()
{
      base b;
      derived d;
      b=d;
      return 0;
}
here b contains i and j where as d contains i, j& k. On assignment only i and j of the d get copied into i and j of b. k does not get copied. on the effect object d got sliced.

Sunday, 28 December 2014

Pointer to member of class

We can assign the address of a member of a class to a pointer by applying operator & to a "fully qualified" class member name. Pointer to class member can be declared using the operator ::*. For example:

class abc
{
      int x;
      public :
      void show( );
};

Now we can define a pointer to the member x as follows:

int abc::* p=&abc :: x;

The p pointer created thus act like a class member in that it must be invoked with a class object. In the statement above, the phrase abc::* means  "pointer-to-member of abc class". The phrase &abc::x means the "address of the x member of abc class".

abc a;
cout<<a.*p;
cout<<a.x;

Above two statements are identical

Thursday, 25 December 2014

How to declare const member functions?

If a member function does not alter any data in the class, then we may declare it as a const member function as follows:

void func(int , int) const;
float sum(float , float) const;

The qualifier const is appended to the function prototypes (in both declaration and definition). The compiler will generate an error message if such functions try to alter the data values of the data members of that class.

Some facts about static member functions in C++

Like static member variable, we can also have static member functions. A member function that is declared static has the following properties:
  1. A static function can have access to only other static members (functions or variables) declared in the same class.
  2. A static member function can be called using the class name (instead of its objects) as follows:
                   class-name  : :  function-name;

Situations where inline expansion may not work

The inline keyword merely sends a request, not a command, to the compiler. The compiler may ignore this request if the function definition is too large or too complicated and compile the function as a normal function.

Some of the situation where inline expansion may not work are:

1. For functions returning value, if a loop, a switch, or a goto exists.
2. For functions not returning values, if a return statement exist.
3. If functions contain static variables.
4. If inline functions are recursive.

Wednesday, 17 December 2014

Some facts on C/C++

  1. Functions defined in a class are by default inline.
  2. Memory space for the members of a class is allocated when an object of that class is created, not before that(at declaration of the class).
  3. Compiler provides a zero argument constructor only when there is no other constructor defined in the class.
  4. Realloc can be used to reallocate the memory allocated using new operator.
  5. Size of the pointer does not depend on where it is pointing to, it is always the same.
  6. Copy constructor and assignment operators are provided by default by the compiler.
  7. When an object is passed or returned to/from a function by value the copy constructor gets called automatically.
  8. For a template function to work it is mandatory that its definition should always be present in the same file from where it is called.
  9. All static data members are initialized to zero.
  10. For every static data member of a class it should also be defined outside the class to allocate the storage location.

Thursday, 11 December 2014

Some facts about comma operator

Consider the following C programs.
// 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
// 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.

Some facts about static variable

IN C STATIC VARIABLE CAN BE INITIALIZED USING ONLY CONSTANT LITERALS.........

FOR EXAMPLE :  


static int i=20;
 

 IF WE DO NOT INITIALIZE ANY VALUE THEN......



 FOR EXAMPLE : 

static int i;

then by default value of i will be ZERO.......
MEANS i will be 0  ......



Note: All objects with static storage duration must be initialized   before execution of main() starts......

 FOR EXAMPLE : 

BELLOW PROGRAM WILL GIVE COMPILE TIME ERROR...


#include<stdio.h>
int a( )
{
return 6;
}
main( )
{
static int i=a( );       /* Compile Time Error*/
printf("%d",i);
return 0;
}




Explanation: All objects with static storage duration must be initialized   before execution of main() starts......

Wednesday, 10 December 2014

Disadvantages of C

The most common disadvantages of C are:
  1. No Run Time Checking mechanism.
  2. Does not support Object Oriented Programming (OOP) features.
  3. No Strict Type Checking.
  4. Does not support Exception Handling.

Features of C

Following are the features of C:
1 . Low Level Features: C Programming provides low level features that are generally provided by the Lower level languages. C is Closely Related to Lower level Language such as Assembly Language.

2 . Portability: C Programs are portable i.e they can be run on any Compiler with Little or no Modification.

3 . Powerful: Provides Wide variety of Data Types, Functions, useful Control  Loop Control Statements

4 . Bit Manipulation: C Programs can be manipulated using bits. We can perform different operations at bit level.

5 . High Level Features: It is more User friendly as compare to Previous languages. Previous languages such as BCPL, Pascal and other programming languages never provide such great features to manage data.

6 . Modular Programming: Modular programming is a software design technique that increases the extent to which software is composed of separate parts, called modules C Program Consist of Different Modules that are integrated together to form complete program.

7 . Efficient Use of Pointers: Pointers has direct access to memory. C Supports efficient use of pointers. .

Thursday, 4 December 2014

List of valid escape sequence

To learn escape sequence you can use following sentence for easy learning

Very Big Farms Need A Red Tractor

So valid escape sequence are:

\v for Vertical Tab
\b for Backspace
\f for Form Feed
\n for Newline(Line Feed)
\a for Alarm(Beep, Bell)
\r for Carriage Return
\t for Horizontal Return


Other escape sequence are:

\\ for Backslash
\' for Single Quotation Mark
\" for Double Quotation Mark
\? for Question Mark

Wednesday, 3 December 2014

How to read string of any size in C++?

#include<iostream.h>
#include<stdio.h>
#define SIZE 1
void main( )
{
             char* str[SIZE];
             gets(str[0]);         //Read string of any string
             cout<<str[0];      
 }

Function to find whether a given string is a substring of another string

Following function finds whether a given string is a substring of another string. If a given string is a substring of another string it returns 1 which means success, otherwise it will return 0.

int substr(char* str1, char* str2)
{
                  int m, n, i, j;
                  m=n=0;

                  //Find the lengths of strings
                  while(str1[m])
                             ++m;
                  while(str2[n])
                              ++n;

                   for(i=0; i<m-n+1;++i)
                   {
                              for(j=0; j<n;++j)
                                         if(str2[j] != str1[i+j])
                                                       break;
                                 
                               if( j == n )
                                         return 1;        //Substring exists
                     }
           
                      return 0;         //Substring does not exists
}

Sunday, 23 November 2014

How to concatenate two strings?

The following function will concatenate two strings and return the concatenated strings:

char* strcat(char* str1,char* str2)
{
             int len=0,i=0;
             while(str1[len])     //until a null character founds
                       ++len;

              while(str2[i])         //until a null character founds
              {
                          str1[len]=str2[i];
                          ++i;
                          ++len;
               }
             
               str1[len]='\0';       //terminate the string
               return str1;
}
                 
for e.g.:

strcat("hello","hi");

will return :

hellohi