Saturday, June 5, 2010

List of C/C++ Programmes

List of C/C++ Programs
  1. WAP to print your general Information.
  2. WAP to Input 2 numbers and find the sum.
  3. WAP to input marks of 5 subjects and find total, percentage.
  4. WAP to convert Celsius temp to F.
  5. WAP to input 2 numbers and find the bigger number.
  6. WAP to input 3 numbers and find the bigger.
  7. WAP to input percentage and check either a student is eligible for scholarship or not. Percentage should be more than or equal to 80.
  8. WAP to check either a person is eligible for voting in India or not.
  9. WAP to enter basic salary and calculate net salary on the given basis.
  10. WAP to Input percentage and calculate the grade
  11. WAP to demo speed program using switch.
  12. WAP to print first 10 Number.
  13. WAP to print first 10 numbers in reverse order.
  14. WAP to print you name 10 times.
  15. WAP to print your general information 10 times.
  16. WAP to Input 10 numbers and find the sum of numbers.
  17. WAP to input 10 numbers and find the biggest number.
  18. WAP to input 10 number and find how many number are even and odd
  19. WAP to input 10 numbers and find the sum of even and odd separately.
  20. WAP to input 10 numbers and find how many numbers are +ve, -ve and zeros.
  21. WAP to print Fibonacci sr.
  22. WAP to input number and find factorial of a number.
  23. WAP to input a number and print a table of number.
  24. WAP to print first 10 tables
  25. WAP to input starting table num, end table num, and extend and print the tables.
  26. WAP to print various series.

Friday, June 4, 2010

DiffERENCE BETWEEN c/c++


DIFFERENCE b/w C and C++
1.) C was the C++ predecessor. As its name implies, alot of
C remains in C++. Although not actually being more powerful
than C, C++ allows the programmer to more easily manage and
operate with Objects, using an OOP (Object Oriented
Programming) concept.

2.) C++ allows the programmer to create classes, which are
somewhat similar to C structures. However, to a class can be
assigned methods, functions associated to it, of various
prototypes, which can access and operate within the class,
somewhat like C functions often operate on a supplied
handler pointer.

3.) Although it is possible to implement anything  which C++
could implement in C, C++ aids to standardize a way in which
objects are created and managed, whereas the C programmer
who implements the same system has alot of liberty on how to
actually implement the internals, and style among
programmers will vary alot on the design choices made.

4.) In C, some will prefer the handler-type, where a main
function initializes a handler, and that handler can be
supplied to other functions of the library as an object to
operate on/through. Others will even want to have that
handler link all the related function pointers within it
which then must be called using a convention closer to C++.

5.) In C, there's only one major memory allocation function:
malloc. You use it to allocate both single elements and
arrays. In C++, however, memory allocation for arrays is
somewhat different than for single objects; you use the
new[] operator, and you must match calls to new[] with calls
to delete[] (rather than to delete).

6.) C++ applications are generally slower at runtime, and
are much slower to compile than C programs. The low-level
infrastructure for C++ binary execution is also larger. For
these reasons C is always commonly used even if C++ has alot
of popularity, and will probably continue to be used in
projects where size and speed are primary concerns, and
portable code still required (assembly would be unsuitable
then).

7.) In C++, you are free to leave off the statement 'return
0;' at the end of main; it will be provided automatically
but in C, you must manually add it.

8.) A function can be declared in C as int fun( );. This
means that fun( ) is a function without any argument or any
number of arguments. But in C++, this means that the
function with no argument at all.

9.) C++ support operator overloading but c doesn't support
operator overloading.

Recursion

  1. A recursive function is a function that calls itself.
  2. The speed of a recursive program is slower because of stack overheads.
  3. In recursive function we need to specify recursive conditions,
    terminating conditions, and recursive expressions.

#include <stdio.h>

int add(int k,int m);

main()

{

    int k ,i,m;

    m=2;

    k=3;

    i=add(k,m);

    printf("The value of addition is %d\n",i);

}

int add(int pk,int pm)

{
    if(pm==0)

       return(pk);

    else

       return(1+add(pk,pm-1));

}

Recursive Function

#include <stdio.h>
unsigned long factorial(unsigned long);
int main(void)
{
  unsigned long number = 0L;

  printf("\nEnter an integer value: ");

  scanf(" %lu", &number);

  printf("\nThe factorial of %lu is %lu\n", number, factorial(number));

  return 0;
}

unsigned long factorial(unsigned long n)
{

  if(n < 2L)

    return n;

  else

    return n*factorial(n - 1L);

}

Return Structure from Function using C++

#include <cmath>

#include <iostream>

using namespace std;



// define the structures

struct DataStructure

{

  float radius;

  double angle;

};



struct ResultStructure

{

  float area;

  double sine;

  double cosine;

  double tangent;

};



ResultStructure compute(struct DataStructure mystruct);



int main ()

{

    DataStructure input;

       ResultStructure output;



       input.radius = 3;



       input.angle = 0.8;



       output = compute(input);



    cout << " The area is "<< output.area << "\n";

       cout << " The sine of the angle is " << output.sine << "\n";

       cout << " The cosine of the angle is " << output.cosine << "\n";

    cout << " The tangent of the angle is " << output.tangent << "\n";

       return 0;

}



ResultStructure compute(struct DataStructure mystruct)

{

     ResultStructure answer;



        answer.area = pow(mystruct.radius,2);

        answer.sine = sin(mystruct.angle);

        answer.cosine = cos(mystruct.angle);

        answer.tangent = tan(mystruct.angle);



   

Friday, May 21, 2010

Dynamic Memory Allocation

In programming we may come across situations where we may have to deal with data, which is dynamic in nature. The number of data items may change during the executions of a program. The number of customers in a queue can increase or decrease during the process at any time. When the list grows we need to allocate more memory space to accommodate additional data items. Such situations can be handled move easily by using dynamic techniques. Dynamic data items at run time, thus optimizing file usage of storage space.



Dynamic memory allocation:

The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this function.

Many languages permit a programmer to specify an array size at run time. Such languages have the ability to calculate and assign during executions, the memory space required by the variables in the program. But c inherently does not have this facility but supports with memory management functions, which can be used to allocate and free memory during the program execution. The following functions are used in c for purpose of memory management.

Function
Task
malloc
Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space
calloc
Allocates space for an array of elements initializes them to zero and returns a pointer to the memory
free
Frees previously allocated space
realloc
Modifies the size of previously allocated space.


Memory allocations process:

According to the conceptual view the program instructions and global and static variable in a permanent storage area and local area variables are stored in stacks. The memory space that is located between these two regions in available for dynamic allocation during the execution of the program. The free memory region is called the heap. The size of heap keeps changing when program is executed due to creation and death of variables that are local for functions and blocks. Therefore it is possible to encounter memory overflow during dynamic allocation process. In such situations, the memory allocation functions mentioned above will return a null pointer.

Allocating a block of memory:

A block mf memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form:

ptr=(cast-type*)malloc(byte-size);

ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size.

Example:

x=(int*)malloc(100*sizeof(int));

On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int

Allocating multiple blocks of memory:

Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is:

ptr=(cast-type*) calloc(n,elem-size);

The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.

Releasing the used space:

Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function.

free(ptr);

ptr is a pointer that has been created by using malloc or calloc.

To alter the size of allocated memory:

The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is :

ptr=realloc(ptr,newsize); 
This function allocates new memory space of size newsize to the pointer variable ptr ans returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.

/*Example program for reallocation*/
#include< stdio.h >
#include< stdlib.h >
define NULL 0
main()
{
char *buffer;
/*Allocating memory*/
if((buffer=(char *) malloc(10))==NULL)
{
printf(“Malloc failed\n”);
exit(1);
}
printf(“Buffer of size %d created \n,_msize(buffer));
strcpy(buffer,”Bangalore”);
printf(“\nBuffer contains:%s\n”,buffer);
/*Reallocation*/
if((buffer=(char *)realloc(buffer,15))==NULL)
{
printf(“Reallocation failed\n”);
exit(1);
}
printf(“\nBuffer size modified.\n”);
printf(“\nBuffer still contains: %s\n”,buffer);
strcpy(buffer,”Mysore”);
printf(“\nBuffer now contains:%s\n”,buffer);
/*freeing memory*/
free(buffer);
}
 

Pointers and Structures


Pointers and structures:

We know the name of an array stands for the address of its zeroth element the same concept applies for names of arrays of structures. Suppose item is an array variable of struct type. Consider the following declaration:

struct products
{
char name[30];
int manufac;
float net;
item[2],*ptr;

this statement declares item as array of two elements, each type struct products and ptr as a pointer data objects of type struct products, the

assignment ptr=item;

would assign the address of zeroth element to product[0]. Its members can be accessed by using the following notation.

ptr- >name;
ptr- >manufac;
ptr- >net;

The symbol - > is called arrow pointer and is made up of minus sign and greater than sign. Note that ptr- > is simple another way of writing product[0].

When the pointer is incremented by one it is made to pint to next record ie item[1]. The following statement will print the values of members of all the elements of the product array.

for(ptr=item; ptr< item+2;ptr++)
printf(“%s%d%f\n”,ptr- >name,ptr- >manufac,ptr- >net);

We could also use the notation

(*ptr).number

to access the member number. The parenthesis around ptr are necessary because the member operator ‘.’ Has a higher precedence than the operator *.