#Label1 a:hover{ color:#666; background:none #fff; text-decoration:none; }
BannerFans.com

Much awaited movies

BannerFans.com BannerFans.com BannerFans.com BannerFans.com BannerFans.com " /> ">

Sunday, 10 February 2013

C Ques & Ans mainly asked in exams & interviews.

What does static variable mean ?
Static variables are the variables which retain their values between the function call initialized only once their scope is within the function in which they are defined.
What is a pointer ?
Pointers are variables which stores the address of another variable. That variable may scalar (including another pointer), or an aggregate (array or structure). The pointed-to ob may be part of a larger object, such as a field of a structure or an element in an array.
What is a structure ?
Structure constitutes a super data type which represents several different data types unit. A structure can be initialized if it is static or global.
What are the differences between structures and arrays ?
Structure is a collection of heterogeneous data type but array is a collection of homo data types. Array Structure 1-It is a collection of data items of same data type. 2-It has declaration only 3-.There is no keyword. 4- array name represent the address of the starting element. 1-It is a collection of data items of different data type. 2- It has declaration and definition 3- keyword struct is used 4-Structure name is known as tag it is the short hand notation of the declaration.
In header files whether functions are declared or defined?
Functions are declared within header file. That is function prototypes exist in a heade not function bodies. They are defined in library (lib).
What are the differences between malloc () and calloc () ?
Malloc Calloc 1-Malloc takes one argument Malloc(a);where a number of bytes 2-memory allocated contains garbage values 1-Calloc takes two arguments Calloc(b,c) where b no of object and c size of object2-It initializes the contains of block of memory to zerosMalloc takes one argument, memory allocated contains garbage values allocates contiguous memory locations. Calloc takes two arguments, memory allocated contains zeros, and the memory allocated is not contiguous.
What are macros? What are its advantages and disadvantages ?
Macros are abbreviations for lengthy and frequently used statements. When a macro is ca entire code is substituted by a single line though the macro definition is of several lines The advantages of macro is that it reduces the time taken for control transfer as in case o function. The disadvantage of it is here the entire code is substituted so the program beco lengthy if a macro is called several times.
Difference between pass by reference and pass by value ?
Pass by reference passes a pointer to the value. This allows the callee to modify the directly.Pass by value gives a copy of the value to the callee. This allows the callee to m the value without modifying the variable. (In other words, the callee simply cannot modify variable, since it lacks a reference to it.)
What is static identifier ?
A file-scope variable that is declared static is visible only to functions within that function-scope or block-scope variable that is declared as static is visible only within th scope. Furthermore, static variables only have a single instance. In the case of functionblock-scope variables, this means that the variable is not “automatic” and thus retains its across function invocations.
Where is the auto variables stored ?
Auto variables can be stored anywhere, so long as recursion works. Practically, they’r the stack. It is not necessary that always a stack exist. You could theoretically allocate function invocation records from the heap.
Where does global, static, and local, register variables, free memory and C Program instructions get stored ?
Global: Wherever the linker puts them. Typically the “BSS segment” on many platforms. Static: Again, wherever the linker puts them. Often, they’re intermixed with the globals. T only difference between globals and statics is whether the linker will resolve the symbols compilation units. Local: Typically on the stack, unless the variable gets register allocate never spills. Register: Nowadays, these are equivalent to “Local” variables. They live on the stack unless they get register-allocated.
Difference between arrays and linked list ?
An array is a repeated pattern of variables in contiguous storage. A linked list is a structure scattered through memory, held together by pointers in each element that point t next element. With an array, we can (on most architectures) move from one element to the nex adding a fixed constant to the integer value of the pointer. With a linked list, there is a “next” pointer in each structure which says what element comes next.
What are enumerations ?
They are a list of named integer-valued constants. Example:enum color { black , orange yellow, green, blue, violet };This declaration defines the symbols “black", “orange", “yell etc.to have the values “1,” “4,” “5,” … etc. The difference between an enumeration and a ma that the enum actually declares a type, and therefore can be type checked.
Describe about storage allocation and scope of global, extern, static, local and register variables.
Globals have application-scope. They’re available in any compilation unit that include appropriate declaration (usually brought from a header file). They’re stored wherever the l puts them, usually a place called the “BSS segment.” Extern? This is essentially “global.” Static: Stored the same place as globals, typically, but only available to the compilation that contains them. If they are block-scope global, only available within that block and it subblocks.Local: Stored on the stack, typically. Only available in that block and its subbl (Although pointers to locals can be passed to functions invoked from within a scope where t local is valid.)Register: See tirade above on “local” vs. “register.” The only difference i the C compiler will not let you take the address of something you’ve declared as “register.
What are register variables ? What are the advantages of using register variables ?
If a variable is declared with a register storage class,it is known as register variable register variable is stored in the cpu register instead of main memory. Frequently used variable are declared as register variable as it’s access time is faster.
What is the use of typedef ?
The typedef help in easier modification when the programs are ported to another machine. A descriptive new name given to the existing data type may be easier to understand the code.
Can we specify variable field width in a scanf() format string ? If possible how ?
All field widths are variable with scanf(). You can specify a maximum field width for field by placing an integer value between the ‘%’ and the field type specifier. (e.g. %64s) a specifier will still accept a narrower field width. The one exception is %#c (where # is an integer). This reads EXACTLY # characters, and it i only way to specify a fixed field width with scanf().
Out of fgets() and gets() which function is safe to use and why ?
fgets() is safer than gets(), because we can specify a maximum input length. Neither o completely safe, because the compiler can’t prove that programmer won’t overflow the buffer pass to fgets ().
Difference between strdup and strcpy ?
Both copy a string. strcpy wants a buffer to copy into. strdup allocates a buffer usin Unlike strcpy(), strdup() is not specified by ANSI .
What is recursion ?
A recursion function is one which call itself either directly or indirectly.It must have definite point to avoid infinite recursion.
Differentiate between a for loop and a while loop ? What are it uses ?
For executing a set of statements fixed number of times we use for loop while when the iterations to be performed is not known in advance we use while loop.
What is storage class ? What are the different storage classes in C ?
Storage class is an attribute that changes the behavior of a variable. It controls the scope and linkage. The storage classes in c are auto, register, and extern, static, typedef.
Write down the equivalent pointer expression for referring the same element a[i][j][k][l] ?
*(*(*(*(a+i)+j)+k)l)
What is difference between Structure and Unions ?
The Main diff is Structure is Allocate the memory in asper the Data type.But Union is Allocate the Memory in max size of Declare the vari to all. The instance of unions can access one member at a time. The memory allocated for the instance is the size of largest member. But instance of a structure has memory for all members separately and all the members can be accessed independently. a structure is basically a collection of hetrogeneous(dissimilar in nature) elements which r stored contiguously in memory.&in. unions they r user defined data types .A union is a data type that allows different types of variables to share same space in memmory
What the advantages of using Unions ?
When the C compiler is allocating memory for unions it will always reserve enough room largest member.
What are the advantages of using pointers in a program ?
The main advantages of using pointers are:

1.) Function cannot return more than one value. But when the same function can modify many pointer variables and function as if it is returning more than one variable. 
2.) In the case of arrays, we can decide the size of the array at runtime by allocating the necessary space.
3. If you want to access a variable quickly or efficiently without wasting CPU time you have only 2 ways: one is declare it as a register variable and other one is declare it with a pointer.because a CPU  has less registers in it ( approximately 6 i.e. A,B,C,D,E,F,G,H), when no register are freely available then you CAN DO THAT TASK WITH ONLY POINTERS.
4. By using pointers you can improve the CPU’s throughput time.
(Throughput time refers to no of jobs done by the CPU in unit amount of time). These are the advantages that can be acquired from pointers.
What is the difference between Strings and Arrays ?
String is a sequence of characters ending with NULL .it can be treated as a one dimensional array of characters terminated by a NULL character.
In a header file whether functions are declared or defined ?
see Q (5)
 
What is a far pointer ? Where we use it ?
In large data model (compact, large, huge) the address B0008000 is acceptable because in these model all pointers to data are 32bits long. If we use small data model(tiny, small, medium) the above address won’t work since in these model each pointer is 16bits long. If we are working in a small data model and want to access the address B0008000 then we use far pointer. Far pointer is always treated as a 32bit pointer and contains a segment address and offset address both of 16bits each. Thus the address is represented using segment : offset format B000h:8000h. For any given memory address there are many possible far address segment : offset pair. The segment register contains the address where the segment begins and offset register contains the offset of data/code from where segment begins.
What is a NULL Pointer ? Whether it is same as an uninitialized pointer ?
Null pointer is a pointer which points to nothing but uninitialized pointer may point to anywhere.
What is a NULL Macro ? What is the difference between a NULL Pointer and a NULL Macro ?
There are times when it?s necessary to have a pointer that doesn?t point to anything. The macro NULL, defined in , has a value that?s guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*.
The null pointer is used in three ways :
1) To stop indirection in a recursive data structure.
2) As an error value.
3) As a sentinel value.
Both are very different.
NULL macro is
#define NULL 0
it means the macro NULL will be replaced by 0 while preprocessing
But the NULL pointer means it points to nowhere i.e. contains 0. 
It contains 0 means it may be dangerous to use such pointer without assigning proper address to it otherwise NULL pointer may try to access reset address may cause the program to crash.
What does the error 'Null Pointer Assignment' mean and what causes this error ?
As null pointer points to nothing so accessing a uninitialized pointer or invalid location may cause an error.
What is near, far and huge pointers ? How many bytes are occupied by them?
far pointer is a pointer which includes a segment selector, making it possible to point to addresses outside of the current segment. Far pointers have a size of 4 bytes. They store both the segment and the offset of the address the pointer is referencing. A far pointer has an address range of 0 - 1M bytes. A far pointer can be incremented and decremented using arithmetic operators. When a far pointer is incremented or decremented ONLY the offset of the pointer is actually incremented or decremented. The segment is never incremented by the arithmetic operators. 

Near pointers have a size of 2 bytes. They only store the offset of the address the pointer is referencing. An address consisting of only an offset has a range of 0 - 64K bytes. A near pointer can be incremented and decremented using arithmetic operators (+, -, ++, and --) through the entire address range. Any attempt to increment a near pointer that has a value of 64K (0xffff) will result in a value of 0.

HUGE pointers have a size of 4 bytes. They store both the segment and the offset of the address the pointer is referencing. A huge pointer has an address range of 0 - 1M bytes. A huge pointer can be incremented and decremented using arithmetic operators. The only difference between a far pointer and a huge pointer is that a huge pointer is normalized by the compiler. A normalized pointer is one that has as much of the address as possible in the segment, meaning that the offset is never larger than 15. A huge pointer is normalized only when pointer arithmetic is performed on it. It is not normalized when an assignment is made.
How would you obtain segment and offset addresses from a far address of a memory location ?
Pointers to far objects are stored using four bytes (32 bits). The bytes are stored little endian or low to high order. The first word contains the 14-bit memory offset (bits 14 and 15 are always 0). The second word contains the page number (or segment number for function pointers). The memory address is calculated as follows:
Variable Address (Page * 0x4000L) + Offset
Function Address (Segment * 0x10000L) + Offset
Are the expressions arr and &arr same for an array of integers ?
No arr refers to address of array &arr refers address of address of array but compiler treats arr and & arr, so even you place arr and & arr no error only warnings will be displayed.
Does mentioning the array name gives the base address in all the contexts?
Mentioning the array name in C or C++ gives the base address in all contexts except one.
Syntactically, the compiler treats the array name as a pointer to the first element. You can reference elements using array syntax, a[n], or using pointer syntax, *(a+n), and you can even mix the usages within an expression. When you pass an array name as a function argument, you are passing the "value of the pointer", which means that you are implicitly passing the array by reference, even though all parameters in functions are "call by value".
There is, however, one very important distinction. While an array name is referentially the same as a pointer, it is not a pointer in that it does not occupy program referential space in the process. This means that, while you can change the value of a pointer, and thus the address to which it points, you cannot change the value of an array name. This distinction is what we call R-Value (array or pointer) as opposed to L-Value (pointer only), i.e. can the object appear on the left sign of an assignment operator.
Explain one method to process an entire string as one unit ?
By using gets() function we can do so.
What is the similarity between a Structure, Union and enumeration?
All of them let the programmer to define new data type.
Can a Structure contain a Pointer to itself ?
Yes such structures are called self-referential structures.
How can we check whether the contents of two structure variables are same or not ?
The two structure variables need to be of same type.
we can check the equality of two structure variables by comparing them individually.
example::
#include<stdio.h>
#include<conio.h>
struct student
{
int rno;
char name[20];
float tot;
}a,b;
void main()
{
clrscr();
printf("enter rno,total of student 1"); 
scanf("%d%f",a.rno,a.total);
printf("enter the name of student1");
scanf("%s",a.name);
printf("enter the rno and total of student2");
scanf("%d%f",b.rno,b.total);
printf("enter the name of student2");
scanf("%s",b.name);

if((a.rno==b.rno)&&(a.name==b.name)&&(a.total==b.total))
printf("two structure variables are equal");
else
printf("two structure variables are not equal");
getch();
}
How are Structure passing and returning implemented by the complier ?
When structures are passed as argument to functions, the entire structure is typically pushed on the stack. To avoid this overhead many programmer often prefer to pass pointers to structure instead of actual structures. Structures are often returned from functions in a location pointed to by an extra, compiler-supported ‘hidden’ argument to the function.
How can we read/write Structures from/to data files ?
To write out a structure we can use fwrite() as Fwrite( &e, sizeof(e),1,fp);Where e is a structure variable. A corresponding fread() invocation can read the structure back from file. calling fwrite() it writes out sizeof(e) bytes from the address &e. Data files written as memory images with fwrite(),however ,will not be portable, particularly if they contain floating point fields or Pointers. This is because memory layout of structures is machine and compiler dependent. Therefore, structures written as memory images cannot necessarily be read back by programs running on other machine, and this is the important concern if the data files you’re writing will ever be interchanged between machines.
What is the difference between an enumeration and a set of pre-processor # defines ?
Enumeration provide convenient way to associate constant values with names , an alternative to #define with advantage that the values can be generated for you. Although variables of enum types may be declared , compilers need not check that what you store in such variable is a calid value for enum. Neverthless enum variables offer a chance of checking and so are often better that #defines. In addition debugger may be able to print values of enum variables in their symbolic forms.
What do the 'c' and 'v' in argc and argv stand for?
The c in argc(argument count) stands for the number of command line argument the program is invoked with and v in argv(argument vector) is a pointer to an array of character string that contain the arguments.
Are the variables argc and argv are local to main ?
Yes both argc and argv are local to main method.Any thing you write within the parenthesis is local to the function.
What is the maximum combined length of command line arguments including the space between adjacent arguments ?
It depends on the operating system.
If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision ? If yes, which ?
Yes you have to compile a program like tcc myprog wildargs.obj
Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function ?
Using the predefined variables _argc, _argv. This is a compiler dependent feature. It works in TC/TC++ but not in gcc and visual studio.
You can copy them into global variables in the main() function, then have your other functions access those global variables. Global variables should generally be avoided, however.
What are bit fields? What is the use of bit fields in a Structure declaration ?
A bit field is a set of adjacent bits within a single implementation based storage unit that we
will call a “word”.
The syntax of field definition and access is based on structure.
Struct {
unsigned int k :1;
unsigned int l :1;
unsigned int m :1;
}flags;
the number following the colon represents the field width in bits.Flag is a variable that contains three bit fields.
To which numbering system can the binary number 1101100100111100 be easily converted to ?
Since this is a 16 bit number,
we can group these bits into 4bits a group each as
(1101)(1001)(0011)(1100)
Hence the given set of bits can be converted to HEXA DECIMAL SYSTEM as
(D93C)
16
Which bit wise operator is suitable for checking whether a particular bit is on or off ?
The bitwise AND operator. Here is an example: 

enum {
KBit0 = 1, 
KBit1,
?
KBit31,
};

if ( some_int & KBit24 )
printf ( ?Bit number 24 is ON
? );
else
printf ( ?Bit number 24 is OFF
? );
Which bit wise operator is suitable for turning off a particular bit in a number ?
The bitwise AND operator, again. In the following code snippet, the bit number 24 is reset to zero.
some_int = some_int & ~KBit24;
Which bitwise operator is suitable for putting on a particular bit in a number?
Enumeration can be done at the place where we need to assaign integer values for words,
Pre-processor dir can be used at the places where we want to give any other names to represent the original word or statement.
Enumeration provide convenient way to associate constant values with names , an alternative to #define with advantage that the values can be generated for you. Although variables of enum types may be declared , compilers need not check that what you store in such variable is a calid value for enum. Neverthless enum variables offer a chance of checking and so are often better that #defines. In addition debugger may be able to print values of enum variables in their symbolic forms.
Enums are compile time substituted constants whereas #defines are preprocessing substituted time constants.
Write a program to compare two strings without using the strcmp() function.
strcmp() function compares two strings lexicographically. strcmp is declared in stdio.h
Case 1: when the strings are equal, it returns zero.
Case 2: when the strings are unequal, it returns the difference between ascii values of the characters that differ.
a) When string1 is greater than string2, it returns positive value.
b) When string1 is lesser than string2, it returns negative value.
Syntax:
int strcmp (const char *s1, const char *s2);
Program: to compare two strings.
#include<stdio.h>
#include<string.h>
int cmpstr(char s1[10], char s2[10]);

int main()
{
char arr1[10] = "Nodalo";
char arr2[10] = "nodalo";
printf(" %d", cmpstr(arr1, arr2));
//cmpstr() is equivalent of strcmp()
return 0;
}

//s1, s2 are strings to be compared
int cmpstr(char s1[10], char s2[10]) 
{
//strlen function returns the length of argument string passed
int i = strlen(s1);
int k = strlen(s2);
int bigger;

if (i < k)
{
bigger = k;
}
else if (i > k) 
{
bigger = i;
}
else 
{
bigger = i;
}

//loops 'bigger' times
for (i = 0; i < bigger; i++) 
{
//if ascii values of characters s1[i], s2[i] are equal do nothing
if (s1[i] == s2[i])
{
}
//else return the ascii difference
else 
{
return (s1[i] - s2[i]);
}
}
//return 0 when both strings are same
//This statement is executed only when both strings are equal
return (0);
}
Write a program to interchange 2 variables without using the third one.
a ^= b; ie a=a^b
b ^= a; ie b=b^a;
a ^= b ie a=a^b;
here the numbers are converted into binary and then xor operation is performed.
You know, you’re just asking “have you seen this overly clever trick that’s not worth applying on
modern architectures and only really applies to integer variables?
Write programs for String Reversal & Palindrome check
Palindrome is a string, which when read in both forward and backward way is same.
Example: radar, madam, pop, lol, etc.
Program:
#include <stdio.h>
#include <string.h>
int main() 
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: \n");
scanf("%s", string1);
length = strlen(string1);
for(i=0;i < length ;i++)
{
if(string1[i] != string1[length-i-1])
{
flag = 1;
break;
}
}
if (flag)
{
printf("%s is not a palindrome\n", string1);
}
else
{
printf("%s is a palindrome\n", string1);
}
return 0;
}

Output:
Enter a string: radar
“radar” is a palindrome
Write a program to find the Factorial of a number
#include <stdio.h>
#include <conio.h>
int fact (int);
void main()
{
int n,f;
clrscr();
printf("\n Enter a number:");
scanf("%d",&n);
f=fact(n);
printf("\n The factorial is:%d",f);
getch();
}

int fact (int n)
{
int f=0;
if(n==0)
return (1);
else
f=n*fact(n-1);
return (f);
}
What are the advantages of using typedef in a program ?
1. Readability. Just like naming your variables properly can show how you intend to use the variable, renaming the type can help show how you intend to use all variables of this type. It eliminates the possible bug of incorrect argument ordering (e.g. if a method signature has multiple boolean flags). 
2. Portability. On different systems you might want to have the same variable name (because you're using it the same way) to be of a different type. So you keep the typedef in a header file controlled by conditional compilation (for example) for maximal portability.
3. decreases complexity for declaring complex and repeated declarations like typedef unsigned long int UINT64;
How would you dynamically allocate a one-dimensional and two-dimensional array of integers ?
/* Allocate space for an array with ten elements of type int. */ 
int *ptr = malloc(10 * sizeof (int)); 
if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error here as appropriate. */
realloc
It is often useful to be able to grow or shrink a block of memory. This can be done using realloc which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by ptr (truncated to the minimum of the old and new sizes). If realloc is unable to resize the memory region in-place, it allocates new storage, copies the required data, and frees the old pointer. If this allocation fails, realloc maintains the original pointer unaltered, and returns the null pointer value. The newly allocated region of memory is uninitialized (its contents are not predictable). The function prototype is
void *realloc(void *pointer, size_t size);


   How can you increase the size of a dynamically allocated array ?
/* Allocate space for an array with ten elements of type int. */ 
int *ptr = malloc(10 * sizeof (int)); 
if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error here as appropriate. */
realloc
It is often useful to be able to grow or shrink a block of memory. This can be done usingrealloc which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by ptr (truncated to the minimum of the old and new sizes). If realloc is unable to resize the memory region in-place, it allocates new storage, copies the required data, and frees the old pointer. If this allocation fails, realloc maintains the original pointer unaltered, and returns the null pointer value. The newly allocated region of memory is uninitialized (its contents are not predictable). The function prototype is 
void *realloc(void *pointer, size_t size);
When reallocating memory if any other pointers point into the same piece of memory do you have to readjust these other pointers or do they get readjusted automatically ?
As for pointers, I think you have to readjust them. Pointers are just variables that store a memory address in them. You can have as many pointers that points to a single location in memory as you want.
Which function should be used to free the memory allocated by calloc() ?
free() is a function used to free the memory allocated dynamically ,by both malloc and calloc functions.
free(ptr): ptr is a pointer to a memory block which has already been creeated by malloc or calloc.
How much maximum can you allocate in a single call to malloc() ?
Theoretically, as many bytes whose total number can be expressed with type 'size_t'. But the range of 'size_t' is implementation defined. It must be an unsigned integer type, with a minimum magnitude of 65535. The maximum single allocation size possible is also limited by the host operating system.
Can you dynamically allocate arrays in expanded memory ?
int *ptr = malloc(10 * sizeof (int)); if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error here as appropriate. */
realloc It is often useful to be able to grow or shrink a block of memory. This can be done using realloc which returns a pointer to a memory region of the specified size, which contains the same data as the old region pointed to by ptr (truncated to the minimum of the old and new sizes). If realloc is unable to resize the memory region in-place, it allocates new storage, copies the required data, and frees the old pointer. If this allocation fails, realloc maintains the original pointer unaltered, and returns the null pointer value. The newly allocated region of memory is uninitialized (its contents are not predictable). The function prototype is
void *realloc(void *pointer, size_t size);
What is object file ? How can you access object file ?
An object file is binary representation of source(text) file. On Linux, object and executable files have ELF format. It's a collection of various sections segragating type of data in:
- text section
- data section
- stack
- heap
Also addresses in an object file are relative and hence object files can't be run unless it's linked. for ex, if you make a call to printf(), object file will have an entry as
("call printf ___") where the blank is the address of printf function. Since printf is part of libc.so, you have no knowledge of its address. Linking with libc pads the correct address and enables you to call it successfully.
Which header file should you include if you are to develop a function which can accept variable number of arguments ?
stdarg.h
Read the manual for your compiler the header files for each compiler are different. 
None of the compilers I currently use have a header file called "stdarg.h" but do have "varargs.h"
Can you write a function similar to printf() ?
puts()
How can a called function determine the number of arguments that have been passed to it ?
Use the variable length argument - va_arg , va_list , ca_start and va_end macros
How do you declare the following:  
a.  An array of three pointers to chars 
b.  An array of three char pointers  
c.  A pointer to array of three chars  
d.  A pointer to function which receives an int pointer and returns a float pointer  
e.  A pointer to a function which receives nothing and returns nothings  
(a) char *ptr[3]
(b) char *array[3]
(c) char (*ptr)[3]
(d) float *(*ptr)(int*)
(e) void (*ptr)()
What do the functions atoi(), itoa() and gcvt() do ?
atoi() is a macro that converts integer to character.
itoa() It converts an integer to string
gcvt() It converts a floating point number to string.
Does there exist any other function which can be used to convert an integer or a float to a string ?
#include char *itoa(int value, char *string, int radix);
DESCRIPTION
The itoa() function constructs a string representation of an integer.
value:
Is the integer to be converted to string representation.
string:
Points to the buffer that is to hold resulting string. The resulting string may be as long as seventeen bytes.
radix:
Is the base of the number; must be in the range 2 - 36.
A portable solution exists. One can use sprintf():
char s[SOME_CONST];
int i = 10;
float f = 10.20;
sprintf ( s, “%d %f\n”, i, f );
How would you use qsort() function to sort an array of structures ?
include stdlib.h library.
Representation: basic reoresentaion of qsort() function is,
void qsort(void *Base, size noe , size width, int (*compar)(constt void *, constt void *));
where:
Base-> Pointer indicates beginning of array.
noe-> Number of Elements.
Width-> Size of Element.
Compare-> Does comparison and returns +ve or -ve integer.It is a callback function (pointer to function).
Example:
This Examples uses structs_sort() function.It is use to compare struct_cmp_product_price() and
struct_cmp_product() as compar callbacks.struct_array is used to print structure of array.
void structs_sort(void)
{
struct st_eq structs[] = {{"Computer",24000.0f}, {"Laptop", 40000.0f},
{"Inverter", 10000.0f}, {"A.C.", 20000.0f},
{"Refrigerator", 7000.0f}, {"Mobile", 15000.0f }};
size structs_len = sizeof(structs) / sizeof(struct st_eq);
puts("*** Struct sorting (price)...");
/* original struct array */
print_struct_array(structs, structs_len);
/* sort array using qsort functions */
qsort(structs, structs_len, sizeof(struct st_ex), struct_cmp_product_price);
/* print sorted struct array */
print_struct_array(structs, structs_len);
puts("*** Struct sorting (product)...");
/* resort using other comparision function */
qsort(structs, structs_len, sizeof(struct st_eq), struct_cmp_product);
/* print sorted struct array */
print_struct_array(structs, structs_len);
}
/* MAIN program */
int main()
{
/* run all example functions */
sort_integers();
sort_cstrings();
sort_structs();
return 0;
}
How would you use bsearch() function to search a name stored in array of pointers to string ?
bsearch, It is a library function.Using this we done data entry in array. Ther is mandatry in binary search you must sorted in ascending order.And do compare two datas.For using this function we have to include stdlib.h library function.
Syntax:
void *bsearch(void *key, void *base, size num, size width);
int (*cmp)(void *emt1, void *emt2));
where;
emt->Element.
Some steps that we have to follow when we using
bsearch.
1. It is passed pointers to two data items
2. It returns a type int as follows:
2.1) <0 Element 1 is less than element 2.
2.2) 0 Element 1 is equal to element 2.
2.3) > 0 Element 1 is greater than element 2.
example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABSIZE 1000
struct node { /* These are stored in the table. */
char *string;
int length;
};
struct node table[TABSIZE];/*Table to be search*/
.
.
.
{
struct node *node_ptr, node;
/* Routine to compare 2 nodes. */
int node_compare(const void *, const void *);
char str_space[20]; /* Space to read string into. */
.
.
.
node.string = str_space;
while (scanf("%s", node.string) != EOF) 
{
node_ptr = (struct node *)bsearch((void *)(&node),(void *)table, TABSIZE,sizeof(struct node),node_compare);
if (node_ptr != NULL)
{
(void)printf("string = %20s, length = %d\n",
node_ptr->string, node_ptr->length);
}
else
{
(void)printf("not found: %s\n", node.string);
}
}}
/*
This routine compare two nodes based on an
alphabetical ordering of the string field.
*/
int node_compare(const void *node1, const void *node2)
{
return strcoll(((const struct node *)node1)->string,((const struct node *)node2)->string);
}
How would you use the functions sin(), pow(), sqrt() ?
before using these functions <math.h>
should be included in the program

sin(d) will returns the sine of d,
pow(a,b) will returns a the value a to the power b(a^b)
eg:pow(2,3) will returns 8;
sqrt(a) returns the square root of a
eg: sqrt(4) returns 2;
How would you use the functions memcpy(), memset(), memmove() ?
memcpy() function copies n bytes from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.
memmove() function shall copy n bytes from the object pointed to by s2 into the object pointed to by s1. Copying takes place as if the n bytes from the object pointed to by s2 are first copied into a temporary array of n bytes that does not overlap the objects pointed to by s1 and s2, and then the n bytes from the temporary array are copied into the object pointed to by s1.
memset() function copies c (converted to an unsigned char) into each of the first n bytes of the object pointed to by s. SYNTAX:
void *memcpy(void *s1, const void *s2, size_t n);
void *memmove(void *s1, const void *s2, size_t n);
void *memset(void *s, int c, size_t n);
How would you use the functions fseek(), freed(), fwrite() and ftell() ?
fseek(f,1,i) Move the pointer for file f a distance 1 byte from location i.
fread(s,i1,i2,f) Enter i2 dataitems,each of size i1 bytes,from file f to string s.
fwrite(s,i1,i2,f) send i2 data items,each of size i1 bytes from string s to file f.
ftell(f) Return the current pointer position within file f.
The data type returned for functions fread,fseek and fwrite is int and ftell is long int.
How would you obtain the current time and difference between two times ?
By using in built gettime() and difftime().
How would you use the functions randomize() and random() ?
Randomize() initiates random number generation with a random value.
Random() generates random number between 0 and n-1;
How would you implement a substr() function that extracts a sub string from a given string ?
substr(string, position [, count])
It extract substring starting from start and going for count characters. If count is not specified, the string is clipped from the start till the end.
What is the difference between the functions rand(), random(), srand() and randomize() ?
RAND: Rand uses a multiplicative congruential random number generator with period232 to return successive pseudo-random numbers in the range 0 to RAND_MAX.
Return Value: Rand returns the generated pseudo-random number.
RANDOM(): Random returns a random number between 0 and (num-1).random(num) is a macro defined in STDLIB.H.
RANDOMIZE(): Randomize initializes the random number generator with a random value. Because randomize is implemented as a macro that calls the time function prototyped in TIME.H, you should include TIME.H when you use this routine
SRAND(): The random number generator is reinitialized by calling srand with an argument value of 1.The generator can be set to a new starting point by calling srand with a given seed number.
What is the difference between the functions memmove() and memcpy() ?
The arguments of memmove() can overlap in memory. The arguments of memcpy() cannot.
Can you use the function fprintf() to the output on the screen ?
#include<stdio.h>
int main()
{
char name[10]="prachee";
fprintf( stdout, "Hello %s ", name );
getchar();
return 0;
}

No comments:

Post a Comment