Showing posts with label C C(plus plus) TUTORIAL. Show all posts
Showing posts with label C C(plus plus) TUTORIAL. Show all posts

Thursday, 7 March 2013

STRUCTURE

A structure contains a number of data types grouped together. These data types may or may not be of the same type. The following example illustrates the use of this data type.
main( )
{
    struct book
    {
        char name ;
        float price ;
        int pages ;
    } ;

    struct book b1, b2, b3 ;
    printf ( "\nEnter names, prices & no. of pages of 3 books\n" ) ;
    scanf ( "%c %f %d", &b1.name, &b1.price, &b1.pages ) ;
    scanf ( "%c %f %d", &b2.name, &b2.price, &b2.pages ) ;
    scanf ( "%c %f %d", &b3.name, &b3.price, &b3.pages ) ;
    printf ( "\nAnd this is what you entered" ) ;
    printf ( "\n%c %f %d", b1.name, b1.price, b1.pages ) ;
    printf ( "\n%c %f %d", b2.name, b2.price, b2.pages ) ;
    printf ( "\n%c %f %d", b3.name, b3.price, b3.pages ) ;
}

And here is the output...
Enter names, prices and no. of pages of 3 books
A 100.00 354
C 256.50 682
F 233.70 512


And this is what you entered


A 100.000000 354
C 256.500000 682
F 233.700000 512



This program demonstrates two fundamental aspects of structures:
(a) declaration of a structure

    struct book
    {
        char name ;
        float price ;
        int pages ;
    } ;
    struct book b1, b2, b3 ;

(b) accessing of structure elements

    b3.name, b3.price, b3.pages




Source By Let Us C "Yashwant Kanetkar"

Thursday, 17 January 2013

RECURSIVE FUNCTION

It is possible for the functions to call themselves. A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself.
Let us now see a simple example of recursion. Suppose we want to calculate the factorial value of an integer. As we know, the factorial of a number is the product of all the integers between 1 and that number. For example, 4 factorial is 4 * 3 * 2 * 1.

main( )
{
   int a, fact ;
   printf ( "\nEnter any number " ) ;
   scanf ( "%d", &a ) ;
   fact = factorial ( a ) ;
   printf ( "Factorial value = %d", fact ) ;
}
factorial ( int x )
{
   int f = 1, i ;
   for ( i = x ; i >= 1 ; i-- )
   f = f * i ;
   return ( f ) ;
}


And here is the output...
Enter any number 3
Factorial value = 6


Following is the recursive version of the function to calculate the factorial value.
main( )
{
   int a, fact ;
   printf ( "\nEnter any number " ) ;
   scanf ( "%d", &a ) ;
   fact = rec ( a ) ;
   printf ( "Factorial value = %d", fact ) ;
}
rec ( int x )
{
   int f ;
   if ( x == 1 )
      return ( 1 ) ;
   else
      f = x * rec ( x - 1 ) ;
   return ( f ) ;
}


Now the output is
Enter any number 5
Factorial value = 120

Tuesday, 15 January 2013

FUNCTION CALLS : Call by value and Call by reference

Two types of function calls—call by value and call by reference. Arguments can
generally be passed to functions in one of the two ways:
(a) sending the values of the arguments
(b) sending the addresses of the arguments


In the first method the ‘value’ of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. The following program illustrates the ‘Call by Value’.

main( )
{
   int a = 10, b = 20 ;
   swapv ( a, b ) ;
   printf ( "\na = %d b = %d", a, b ) ;
}
swapv ( int x, int y )
{
   int t ;
   t = x ;
   x = y ;
   y = t ;
   printf ( "\nx = %d y = %d", x, y ) ;
}

The output of the above program would be:


x = 20 y = 10
a = 10 b = 20

Note that values of a and b remain unchanged even after exchanging the values of x and y.

In the second method (call by reference) the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them. The following program illustrates this fact.

main( )
{
   int a = 10, b = 20 ;
   swapr ( &a, &b ) ;
   printf ( "\na = %d b = %d", a, b ) ;
}
swapr( int *x, int *y )
{
   int t ;
   t = *x ;
   *x = *y ;
   *y = t ;
}

The output of the above program would be:

a = 20  b = 10
 

Note that this program manages to exchange the values of a and b using their addresses stored in x and y.

Friday, 4 January 2013

VIRTUAL FUNCTION

A virtual function is a member function that is declared within a base class and redefined by a derived class. To create virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.
Base class pointer can point to derived class object. In this case, using base class pointer if we call some function which is in both classes, then base class function is invoked. But if we want to invoke derived class function using base class pointer, it can be achieved by defining the function as virtual in base class, this is how virtual functions support run-time polymorphism.

Consider following program code:


Class Base
{
        int a;
        public:
        Base()
        {
                 a = 1;
        }
        virtual void show()
        {
                 cout <<a;
        }
};

Class Drive: public Base
{
         int b;
         public:
         Drive()
         {
                b = 2;
         }
         virtual void show()
         {
                cout <<b;
         }
};

int main()
{
           Base *pBase;
           Drive oDrive;
           pBase = &oB;
           pBase->show();
           return 0;
}

Output is 2

since pBase points to object of Drive and show() is virtual in base class Base.

Tuesday, 25 December 2012

Array in C Tutorial

An array is a collection of similar elements. These similar elements could be all ints, or all floats, or all chars, etc. Usually, the array of characters is called a ‘string’, whereas an array of ints or floats is called simply an array. Remember that all elements of any given array must be of the same type. i.e. we cannot have an array of 10 numbers, of which 5 are ints and 5 are floats.

Program Using Array
Let us try to write a program to find average marks obtained by a class of 30 students in a test.


main ( )
{
  int avg, sum = 0 ;
  int i ;
  int marks[30] ; /* array declaration */

  for ( i = 0 ; i <= 29 ; i++ )
  {
    printf ( "\nEnter marks " ) ;
    scanf ( "%d", &marks[i] ) ; /* store data in array */
  }

  for ( i = 0 ; i <= 29 ; i++ )
  {
    sum = sum + marks[i] ; /* read data from an array*/
  }

  avg = sum / 30 ;
  printf ( "\nAverage marks = %d", avg ) ;
}


Thursday, 20 December 2012

Conditional Operators tutorial

The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. Their general form is,

expression 1 ? expression 2 : expression 3

What this expression says is: “if expression 1 is true (that is, if its value is non-zero), then the value returned will be expression 2, otherwise the value returned will be expression 3”. Let us understand this with the help of a few examples:

int x, y ;
scanf ( "%d", &x ) ;
y = ( x > 5 ? 3 : 4 ) ;

This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y. The equivalent if statement will be,


if ( x > 5 )
    y = 3 ;
else
    y = 4 ;

Nested IF-ELSE Condition in C tutorial

It is perfectly all right if we write an entire if-else construct within either the body of the if statement or the body of an else statement. This is called ‘nesting’of ifs. This is shown in the following program.


/* A quick demo of nested if-else */
main( )
{
    int i ;
    printf ( "Enter either 1 or 2 " ) ;
    scanf ( "%d", &i ) ;
    if ( i == 1 )
        printf ( "You would go to heaven !" ) ;
    else
    {
        if ( i == 2 )
            printf("Hell was created with you in mind");
        else
            printf("How about mother earth !");
    }
}

IF-ELSE Condition in C tutorial


The if statement by itself will execute a single statement, or a group of statements, when the expression following if evaluates to true. It does nothing when the expression evaluates to false. Can we execute one group of statements if the expression evaluates to true and another group of statements if the expression evaluates to false? Of course.

i.e.
If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the employee's salary is input through the keyboard write a program to find his gross salary.


/* Calculation of gross salary */
main( )
{
   float bs, gs, da, hra ;
   printf ( "Enter basic salary " ) ;
   scanf ( "%f", &bs ) ;
   if ( bs < 1500 )
   {
      hra = bs * 10 / 100 ;
      da = bs * 90 / 100 ;
   }
   else
   {
      hra = 500 ;
     da = bs * 98 / 100 ;
   }
   gs = bs + hra + da ;
   printf ( "gross salary = Rs. %f", gs ) ;
}

IF Condition in C tutorial

The keyword if tells the compiler that what follows is a decision control instruction. The condition following the keyword if is always enclosed within a pair of parentheses. If the condition, whatever it is, is true, then the statement is executed. If the condition is not true then the statement is not executed; instead the program skips past it

if ( this condition is true )
    execute this statement ;

The relational operators should be familiar to you except for the equality operator == and the inequality operator !=. Note that = is used for assignment, whereas, == is used for comparison of two quantities. Here is a simple program, which demonstrates the use of if and the relational operators.

/* i.e. */
main( )
{
      int num ;
      printf ( "Enter a number less than 10 " ) ;
      scanf ( "%d", &num ) ;
      if ( num <= 10 )
          printf ( "What an obedient servant you are !" ) ;
}


Wednesday, 19 December 2012

What are pointers? tutorial

Pointers are aptly named: they "point" to locations in memory. Think of a row of safety deposit boxes of various sizes at a local bank. Each safety deposit box will have a number associated with it so that the teller can quickly look it up. These numbers are like the memory addresses of variables. A pointer in the world of safety deposit boxes would simply be anything that stored the number of another safety deposit box. Perhaps you have a rich uncle who stored valuables in his safety deposit box, but decided to put the real location in another, smaller, safety deposit box that only stored a card with the number of the large box with the real jewelry. The safety deposit box with the card would be storing the location of another box; it would be equivalent to a pointer. In the computer, pointers are just variables that store memory addresses, usually the addresses of other variables.
The cool thing is that once you can talk about the address of a variable, you'll then be able to go to that address and retrieve the data stored in it. If you happen to have a huge piece of data that you want to pass into a function, it's a lot easier to pass its location to the function than to copy every element of the data! Moreover, if you need more memory for your program, you can request more memory from the system--how do you get "back" that memory? The system tells you where it is located in memory; that is to say, you get a memory address back. And you need pointers to store the memory address.

A note about terms: the word pointer can refer either to a memory address itself, or to a variable that stores a memory address. Usually, the distinction isn't really that important: if you pass a pointer variable into a function, you're passing the value stored in the pointer--the memory address. When I want to talk about a memory address, I'll refer to it as a memory address; when I want a variable that stores a memory address, I'll call it a pointer. When a variable stores the address of another variable, I'll say that it is "pointing to" that variable.
C++ Pointer Syntax
Pointers require a bit of new syntax because when you have a pointer, you need the ability to request both the memory location it stores and the value stored at that memory location. Moreover, since pointers are somewhat special, you need to tell the compiler when you declare your pointer variable that the variable is a pointer, and tell the compiler what type of memory it points to.
The pointer declaration looks like this:
<variable_type> *<name>; 

For example, you could declare a pointer that stores the address of an integer with the following syntax
int *points_to_integer; 
Notice the use of the *. This is the key to declaring a pointer; if you add it directly before the variable name, it will declare the variable to be a pointer. Minor gotcha: if you declare multiple pointers on the same line, you must precede each of them with an asterisk:
// one pointer, one regular int
int *pointer1, nonpointer1;
// two pointers
int *pointer1, *pointer2;
 
As I mentioned, there are two ways to use the pointer to access information: it is possible to have it give the actual address to another variable. To do so, simply use the name of the pointer without the *. However, to access the actual memory location, use the *. The technical name for this doing this is dereferencing the pointer; in essence, you're taking the reference to some memory address and following it, to retrieve the actual value. It can be tricky to keep track of when you should add the asterisk. Remember that the pointer's natural use is to store a memory address; so when you use the pointer:
call_to_function_expecting_memory_address(pointer); 
then it evaluates to the address. You have to add something extra, the asterisk, in order to retrieve the value stored at the address. You'll probably do that an awful lot. Nevertheless, the pointer itself is supposed to store an address, so when you use the bare pointer, you get that address back. 
Pointing to Something: Retrieving an Address
In order to have a pointer actually point to another variable it is necessary to have the memory address of that variable also. To get the memory address of a variable (its location in memory), put the & sign in front of the variable name. This makes it give its address. This is called the address-of operator, because it returns the memory address. Conveniently, both ampersand and address-of start with a; that's a useful way to remember that you use & to get the address of a variable. 
For example:
#include <iostream>
using namespace std;
int main()
{
  int x;            // A normal integer
  int *p;           // A pointer to an integer
  p = &x;           // Read it, "assign the address of x to p"
  cin>> x;          // Put a value in x, we could also use *p here
  cin.ignore();
  cout<< *p <<"\n"; // Note the use of the * to get the value
  cin.get();
}
 
The cout outputs the value stored in x. Why is that? Well, let's look at the code. The integer is called x. A pointer to an integer is then defined as p. Then it stores the memory location of x in pointer by using the address-of operator (&) to get the address of the variable. Using the ampersand is a bit like looking at the label on the safety deposit box to see its number rather than looking inside the box, to get what it stores. The user then inputs a number that is stored in the variable x; remember, this is the same location that is pointed to by p. 
The next line then passes *p into cout. *p performs the "dereferencing" operation on p; it looks at the address stored in p, and goes to that address and returns the value. This is akin to looking inside a safety deposit box only to find the number of (and, presumably, the key to ) another box, which you then open. 
The keyword new is used to initialize pointers with memory from free store (a section of memory available to all programs). The syntax looks like the example:
int *ptr = new int; 
It initializes ptr to point to a memory address of size int (because variables have different sizes, number of bytes, this is necessary). The memory that is pointed to becomes unavailable to other programs. This means that the careful coder should free this memory at the end of its usage. 
The delete operator frees up the memory allocated through new. To do so, the syntax is as in the example.
delete ptr; 
After deleting a pointer, it is a good idea to reset it to point to 0. When 0 is assigned to a pointer, the pointer becomes a null pointer, in other words, it points to nothing. By doing this, when you do something foolish with the pointer (it happens a lot, even with experienced programmers), you find out immediately instead of later, when you have done considerable damage.

LinkWithin

Related Posts Plugin for WordPress, Blogger...