C Interview Questions Part 11

Q:How can I find the day of the week of a given date?
A: The following code snippet shows how to get the day of week from the given date.
dayofweek ( int yy, int mm, int dd )
{
/*Monday = 1 and Sunday = 0 */
/* month number >= 1 and <= 12, yy > 1752 or so */
static int arr[ ] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 } ;
yy = yy - mm < 3 ;
return ( yy + yy / 4 - yy / 100 + yy / 400 + arr[ mm - 1] + dd ) % 7 ;
}
void main( )
{
printf ( "\n\n\nDay of week : %d ", dayofweek ( 2002, 5, 18 ) ) ;
}

Q:What's the difference between these two declarations?
struct str1 { ... } ;
typedef struct { ... } str2 ;
A: The first form declares a structure tag whereas the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type -- its users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it.

Q: How do I print the contents of environment variables?
A: The following program shows how to achieve this:
main( int argc, char *argv[ ], char *env[ ] )
{
int i = 0 ;
clrscr( ) ;
while ( env[ i ] )
printf ( "\n%s", env[ i++ ] ) ;
}
main( ) has the third command line argument env, which is an array of pointers to the strings. Each pointer points to an environment variable from the list of environment variables.


Q:How do I use the function ldexp( ) in a program?
A: The math function ldexp( ) is used while solving the complex mathematical equations. This function takes two arguments, a double value and an int respectively. The order in which ldexp( ) function performs calculations is ( n * pow ( 2, exp ) ) where n is the double value and exp is the integer. The following program demonstrates the use of this function.
#include
void main( )
{
double ans ;
double n = 4 ;
ans = ldexp ( n, 2 ) ;
printf ( "\nThe ldexp value is : %lf\n", ans ) ;
}
Here, ldexp( ) function would get expanded as ( 4 * 2 * 2 ), and the output would be the ldexp value is : 16.000000