Sunday, April 23, 2006

FAQ's of C.. Check out your C Knowledge... Part VIII

85.
Unique combinations for a given numberHow do I write a program which can generate all possible combinations of numbers from 1 to one less than the given number ?main( ){long steps, fval, bstp, cnt1 ;int num, unit, box[2][13], cnt2, cnt3, cnt4 ;printf ( "Enter Number " ) ;scanf ( "%d", &num ) ;num = num <> 12 ? 12 : num ;for ( steps = 1, cnt1 = 2 ; cnt1 <= num ; steps *= cnt1++ ) ;for ( cnt1 = 1 ; cnt1 <= steps ; cnt1++ ){for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ )box[0][cnt2] = cnt2 ;for ( fval = steps, bstp = cnt1, cnt2 = 1 ; cnt2 <= num ; cnt2++ ){if ( bstp == 0 ){cnt4=num ;while ( box[0][cnt4] == 0 )cnt4-- ;}else{fval /= num - cnt2 + 1 ;unit = ( bstp + fval - 1 ) / fval ;bstp %= fval ;for ( cnt4 = 0, cnt3 = 1 ; cnt3 <= unit ; cnt3++ )while ( box[0][++cnt4] == 0 ) ;}box[1][cnt2] = box[0][cnt4] ;box[0][cnt4] = 0 ;}printf ( "\nSeq.No.%ld:", cnt1 ) ;for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ )printf ( " %d", box[1][cnt2] ) ;}}This program computes the total number of steps. But instead of entering into the loop of the first and last combination to be generated it uses a loop of 1 to number of combinations. For example, in case of input being 5 the number of possible combinations would be factorial 5, i.e. 120. The program suffers from the limitation that it cannot generate combinations for input beyond 12 since a long int cannot handle the resulting combinations. Data StructuresHashing...Hashing or hash addressing is a searching technique. Usually, search of an element is carried out via a sequence of comparisons. Hashing differs from this as it is independent of the number of elements n in the collection of data. Here, the address or location of an element is obtained by computing some arithmetic function. Hashing is usually used in file management. The general idea is of using the key to determine the address of a record. For this, a function fun( ) is applied to each key, called the hash function. Some of the popular hash functions are: 'Division' method, 'Midsquare' method, and 'Folding' method. Two records cannot occupy the same position. Such a situation is called a hash collision or a hash clash. There are two basic methods of dealing with a hash clash. The first technique, called rehashing, involves using secondary hash function on the hash key of the item. The rehash function is applied successively until an empty position is found where the item can be inserted. If the hash position of the item is found to be occupied during a search, the rehash function is again used to locate the item. The second technique, called chaining, builds a linked list of all items whose keys hash to the same values. During search, this short linked list is traversed sequentially for the desired key. This technique involves adding an extra link field to each table position.------------------------------------------------------------------------------------------------- 86. The following program demonstrates how to get input from the user in graphics mode, echoed in the current colors and font size and font style.#define ON 1#define OFF 0#include main( ){char nameString[80], ageString[80] ;int age, gd = DETECT, gm ;initgraph ( &gd, &gm, "c:\\tc\\bgi" ) ;setbkcolor ( BLUE ) ;setcolor ( YELLOW ) ;settextstyle ( GOTHIC_FONT, HORIZ_DIR, 0 ) ;moveto ( 0, 0 ) ;outtext ( "Enter your name: " ) ;getGrString ( nameString ) ; moveto ( 0, gety( ) + textheight ( "A" ) ) ;outtext ( "Name: " ) ;outtext ( nameString ) ;moveto ( 0, gety( ) + textheight ( "A" ) ) ;outtext ( "Press key to exit! " ) ;getch( ) ;closegraph( ) ;restorecrtmode( ) ;}getGrString ( char *inputString ){int stringIndex = 0, oldColor ;char ch, outString[2] ;/* xVal will store the screen position for each char */int xVal[255] ;outString[1] = 0 ;xVal[0] = getx( ) ;do{cursor ( ON ) ;ch = getch( ) ;cursor ( OFF ) ;if ( ch == 0 ) /* avoid dealing with all special keys */getch( ) ;else{if ( ch == 8 ) /* backspace */{oldColor = getcolor( ) ;--stringIndex ;if ( stringIndex < stringindex =" 0" oldcolor =" getcolor(" curx =" getx(">#include #include main( ){int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ;int s ;time_t t1, t2 ; // time_t defines the value used for time functions = sizeof ( a ) / 2 ;t1 = time ( NULL ) ;sel_sort ( a, s ) ; // sort array by selection sortbub_sort ( a, s ) ; // sort array by bubble sort methodt2 = time ( NULL ) ;printf ( "\nThe difference between two function calls is %f", difftime ( t2, t1 ) ) ;}In the above program we have called difftime( ) function that returns the time elapsed from t1 to t2.-------------------------------------------------------------------------------------------------88.
Generalmain( ){char *s ;s = fun ( 128, 2 ) ;printf ( "\n%s", s ) ;}fun ( unsigned int num, int base ){static char buff[33] ;char *ptr ;ptr = &buff [ sizeof ( buff ) - 1 ] ;*ptr = '\0' ;do{*--ptr = "0123456789abcdef"[ num % base ] ;num /= base ;} while ( num != 0 ) ;return ptr ;}The above program would convert the number 128 to the base 2. You can convert a number to a hexadecimal or octal form by passing the number and the base, to the function fun( ).
Data StructuresWhat is a priority queue?Ans: As we know in a stack, the latest element is deleted and in a queue the oldest element is deleted. It may be required to delete an element with the highest priority in the given set of values and not only the oldest or the newest one. A data structure that supports efficient insertions of a new element and deletions of elements with the highest priority is known as priority queue. There are two types of priority queues: an ascending priority queue is a collection of items into which items can be inserted arbitrarily and from which only the smallest item can be removed. A descending order priority queue is similar but allows only the largest item to be deleted.-------------------------------------------------------------------------------------------------89.
What is the difference between const char *p, char const *p, and char* const p ?
'const char *p' and 'char const *p' are the same, i.e. p points to a constant character. On the other hand, 'char* const p' means p is a constant pointer pointing to a character which means we cannot change the pointer p but we can change the character which p is pointing to.-------------------------------------------------------------------------------------------------90.
What's the difference between a null pointer, a NULL macro, the ASCII NUL character and a null string?Ans: A null pointer is a pointer which doesn't point anywhere. A NULL macro is used to represent the null pointer in source code. It has a value 0 associated with it. The ASCII NUL character has all its bits as 0 but doesn't have any relationship with the null pointer. The null string is just another name for an empty string "".System Utility
Sparse Matrix...A sparse matrix is one where most of its elements are zero. There is no precise definition as to know whether a matrix is sparsed or not, but it is a concept which we all can recognize intuitively. The natural method of representing matrices in memory as two-dimensional arrays may not be suitable for sparse matrices. That is one may save space by storing only those entries which may be nonzero. If this is done, then the matrix may be thought of as an ordered list of non-zero elements only. Information about a non-zero element has three parts:an integer representing its row, an integer representing its column and the data associated with this element.
That is, each element of a matrix is uniquely characterized by its row and column position, say i, j. We might store that matrix as a list of 3-tuples of the form (i, j, data), as shown below,
Although the non-zero elements may be stored in the array in any order, keeping them ordered in some fashion may be advantageous for further processing. Note that above array is arranged in increasing order of the row number of non-zero elements. Moreover, for elements in the same row number, the array is arranged in order of increasing column number.-------------------------------------------------------------------------------------------------91.
Pointers
What does the error "Null Pointer Assignment" mean and what causes this error?
Ans: The Null Pointer Assignment error is generated only in small and medium memory models. This error occurs in programs which attempt to change the bottom of the data segment. In Borland's C or C++ compilers, Borland places four zero bytes at the bottom of the data segment, followed by the Borland copyright notice "Borland C++ - Copyright 1991 Borland Intl.". In the small and medium memory models, a null pointer points to DS:0000. Thus assigning a value to the memory referenced by this pointer will overwrite the first zero byte in the data segment. At program termination, the four zeros and the copyright banner are checked. If either has been modified, then the Null Pointer Assignment error is generated. Note that the pointer may not truly be null, but may be a wild pointer that references these key areas in the data segment.
Data Structures
How to build an expression trees ?
Ans: An expression tree is a binary tree which is built from simple operands and operators of an (arithmetic or logical ) expression by placing simple operands as the leaves of a binary tree and the operators as the interior nodes. If an operator is binary , then it has two nonempty subtrees, that are its left and right operands (either simple operands or sub expressions). If an operator is unary, then only one of its subtrees is nonempty, the one on the left or right according as the operator is written on the right or left of its operand. We traditionally write some unary operators to the left of their operands, such as "-" ( unary negation) or the standard functions like log( ), sin( ) etc. Others are written on the right, such as the factorial function ()!. If the operator is written on the left, then in the expression tree we take its left subtree as empty. If it appears on the right, then its right subtree will be empty. An example of an expression tree is shown below for the expression ( -a <>main( ){printf ( "%f", fmod ( 5.15, 3.0 ) ) ;}The above code snippet would give the output as 2.150000.-------------------------------------------------------------------------------------------------93.
How to extract the integer part and a fractional part of a floating point number?Ans: C function modf( ) can be used to get the integer and fractional part of a floating point.#include "math.h"main( ){double val, i, f ;val = 5.15 ;f = modf ( val, &i ) ;printf ( "\nFor the value %f integer part = %f and fractional part = %f", val, i, f ) ;}The output of the above program will be:For the value 5.150000 integer part = 5.000000 and fractional part = 0.150000
94.
How do I define a pointer to a function which returns a char pointer?Ans:char * ( *p )( ) ; or typedef char * ( * ptrtofun )( ) ; ptrtofun p ;Here is a sample program which uses this definition. main( ) { typedef char * ( * ptrtofun ) ( ) ; char * fun( ) ; ptrtofun fptr ; char *cptr ; fptr = fun ; cptr = (*fptr) ( ) ; printf ( "\nReturned string is \"%s\"", cptr ) ; } char * fun( ) { static char s[ ] = "Hello!" ; printf ( "\n%s", s ) ; return s ; }-------------------------------------------------------------------------------------------------95. What's wrong with the following declaration: char* ptr1, ptr2 ; get errors when I try to use ptr2 as a pointer.
Ans: char * applies only to ptr1 and not to ptr2. Hence ptr1 is getting declared as a char pointer, whereas, ptr2 is being declared merely as a char. This can be rectified in two ways : char *ptr1, *ptr2 ; typedef char* CHARPTR ; CHARPTR ptr1, ptr2 ;-------------------------------------------------------------------------------------------------96.
How to use scanf( ) to read the date in the form of dd-mm-yy? Ans: To read the date in the form of dd-mm-yy one possible way is, int dd, mm, yy ; char ch ; /* for char '-' */ printf ( "\nEnter the date in the form of dd-mm-yy : " ) ; scanf( "%d%c%d%c%d", &dd, &ch, &mm, &ch, &yy ) ; Another way is to use suppression character * is as follows: int dd, mm, yy ; scanf( "%d%*c%d%*c%d", &dd, &mm, &yy ) ; The suppression character '*' suppresses the input read from the standard input buffer for the assigned control character.-------------------------------------------------------------------------------------------------

No comments: