Saturday, July 7, 2018

C Questions And Answers – 2018A7

There are many commonly asked questions regarding C programming language. Below are some collected such question-answer examples. The questions are usually related with Turbo C IDE in windows or GCC under Linux environment [not always].

For more such examples, click C_Q&A label.

 

-------------------------------------------------------------------------------------------------

 

Are the expressions *ptr++ and ++*ptr same?

 

Ans:

No. *ptr++ increments the pointer and not the value pointed by it, whereas ++*ptr

increments the value being pointed to by ptr.

 

-------------------------------------------------------------------------------------------------

 

strpbrk( )

 

The function strpbrk( ) takes two strings as parameters. It scans the first string, to find, the

first occurrence of any character appearing in the second string. The function returns a pointer to the first occurrence of the character it found in the first string.

 

The following program demonstrates the use of string function strpbrk( ).

 

#include <string.h>

main( )

{

char *str1 = "Hello!" ;

char *str2 = "Better" ;

char *p ;

p = strpbrk ( str1, str2 ) ;

if ( p )

printf ( "The first character found in str1 is %c", *p ) ;

else

printf ( "The character not found" ) ;

}

 

The output of the above program would be the first character found in str1 is e

div( )...

 

The function div( ) divides two integers and returns the quotient and remainder. This function takes two integer values as arguments; divides first integer with the second one and returns the answer of division of type div_t. The data type div_t is a structure that contains two long ints, namely quot and rem, which store quotient and remainder of division respectively.

 

The following example shows the use of div( ) function.

 

#include <stdlib.h>

void main( )

{

div_t res ;

res = div ( 32, 5 ) ;

printf ( "\nThe quotient = %d and remainder = %d ", res.quot, res.rem ) ;

 

-------------------------------------------------------------------------------------------------

 

Is the following code fragment correct?

 

const int x = 10 ;

int arr[x] ;

 

Ans:

No! Here, the variable x is first declared as an int so memory is reserved for it. Then it is qualified by a const qualifier. Hence, const qualified object is not a constant fully. It is an object with read only attribute, and in C, an object associated with memory cannot be used in array dimensions.

 

How do I write code to retrieve current date and time from the system and display it as a string?

 

Ans:

Use time( ) function to get current date and time and then ctime( ) function to display it

as a string. This is shown in following code snippet.

 

#include <sys\types.h>

void main( )

{

time_t

curtime ;

char ctm[50] ;

time ( &curtime ) ; //retrieves current time & stores in curtime

printf ( "\nCurrent Date & Time: %s", ctime (&curtime ) ) ;

}

 

-------------------------------------------------------------------------------------------------

 

How do I change the type of cursor and hide a cursor?

 

Ans:

We can change the cursor type by using function _setcursortype( ). This function can change the cursor type to solid cursor and can even hide a cursor. Following code shows how to change the cursor type and hide cursor.

 

#include <conio.h>

 

main( )

{

 /* Hide cursor */

_setcursortype ( _NOCURSOR ) ;

 

/* Change cursor to a solid cursor */

_setcursortype ( _SOLIDCURSOR ) ;

 

/* Change back to the normal cursor */

_setcursortype ( _NORMALCURSOR ) ;

}

 

-------------------------------------------------------------------------------------------------

 

How do I write code that would get error number and display error message if any

standard error occurs?

 

Ans:

Following code demonstrates this.

 

#include <stdio.h>

#include <stdlib.h>

#include <errno.h>

 

main( )

{

char *errmsg ;

FILE *fp ;

fp = fopen ( "C:\file.txt", "r" ) ;

 

if ( fp == NULL )

{

errmsg = strerror ( errno ) ;

printf ( "\n%s", errmsg ) ;

}

}

Here, we are trying to open 'file.txt' file. However, if the file does not exist, then it would cause an error. As a result, a value (in this case 2) related to the error generated would get set in errno. errno is an external int variable declared in 'stdlib.h' and also in 'errno.h'. Next, we have called sterror( ) function which takes an error number and returns a pointer to standard error message related to the given error number.

 

-------------------------------------------------------------------------------------------------

 

…till next post, bye-bye & take care.

Friday, July 6, 2018

C Questions And Answers – 2018A6

There are many commonly asked questions regarding C programming language. Below are some collected such question-answer examples. The questions are usually related with Turbo C IDE in windows or GCC under Linux environment [not always].

For more such examples, click C_Q&A label.

 

-------------------------------------------------------------------------------------------------

 

How do I use scanf( ) to read the date in the form 'dd-mm-yy' ?

 

Ans:

There are two ways 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 ) ;

 

And another best way is to use suppression character * as...

 

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.

 

-------------------------------------------------------------------------------------------------

 

How do I print a floating-point number with higher precision say 23.34568734 with only precision up to two decimal places?

 

Ans:

This can be achieved through the use of suppression char '*' in the format string of printf(

) as shown in the following program.

 

main( )

{

int i = 2 ;

float f = 23.34568734 ;

printf ( "%.*f", i, f ) ;

}

 

The output of the above program would be 23.35.

 

-------------------------------------------------------------------------------------------------

 

Is the following code fragment correct?

 

const int x = 10 ;

int arr[x] ;

 

Ans:

No! Here, the variable x is first declared as an int so memory is reserved for it. Then it is qualified by a const qualifier. Hence, const qualified object is not a constant fully. It is an object with read only attribute, and in C, an object associated with memory cannot be used in array dimensions.

 

How do I write code to retrieve current date and time from the system and display it as a string?

 

Ans:

Use time( ) function to get current date and time and then ctime( ) function to display it

as a string. This is shown in following code snippet.

 

#include <sys\types.h>

void main( )

{

time_t

curtime ;

char ctm[50] ;

time ( &curtime ) ; //retrieves current time & stores in curtime

printf ( "\nCurrent Date & Time: %s", ctime (&curtime ) ) ;

}

 

-------------------------------------------------------------------------------------------------

 

How do I change the type of cursor and hide a cursor?

 

Ans:

We can change the cursor type by using function _setcursortype( ). This function can change the cursor type to solid cursor and can even hide a cursor. Following code shows how to change the cursor type and hide cursor.

 

#include <conio.h>

 

main( )

{

 /* Hide cursor */

_setcursortype ( _NOCURSOR ) ;

 

/* Change cursor to a solid cursor */

_setcursortype ( _SOLIDCURSOR ) ;

 

/* Change back to the normal cursor */

_setcursortype ( _NORMALCURSOR ) ;

}

 

-------------------------------------------------------------------------------------------------

 

…till next post, bye-bye & take care.

Thursday, July 5, 2018

C Questions And Answers – 2018A5

There are many commonly asked questions regarding C programming language. Below are some collected such question-answer examples. The questions are usually related with Turbo C IDE in windows or GCC under Linux environment [not always].

For more such examples, click C_Q&A label.

 

-------------------------------------------------------------------------------------------------

 

How do I print the contents of environment variables?

 

Ans:

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.

 

-------------------------------------------------------------------------------------------------

 

What would the second and the third printf( ) output the following program?

 

main( )

{

char *str[ ] = {

"Good Morning"

"Good Evening"

"Good Afternoon"

} ;

printf ( "\nFirst string = %s", str[0] ) ;

printf ( "\nSecond string = %s", str[1] ) ;

printf ( "\nThird string = %s", str[2] ) ;

}

 

Ans:

For the above given program, we expect the output as Good Evening and Good Afternoon, for the second and third printf( ). However, the output would be as shown below.

 

First string = Good MorningGood EveningGood Afternoon

Second string = ( null )

Third string =

 

What is missing in the above given code snippet is a comma separator which should separate the strings Good Morning, Good Evening and Good Afternoon. On adding comma, we would get the output as shown below.

 

First string = Good Morning

Second string = Good Evening

Third string = Good Afternoon

 

-------------------------------------------------------------------------------------------------

 

The Spawnl( ) function...

 

DOS is a single tasking operating system, thus only one program runs at a time. The

Spawnl( ) function provides us with the capability of starting the execution of one program

from within another program. The first program is called the parent process and the second program that gets called from within the first program is called a child process. Once the second program starts execution, the first is put on hold until the second program completes execution. The first program is then restarted. The following program demonstrates use of spawnl( ) function.

 

/* Mult.c */

int main ( int argc, char* argv[ ] )

{

int a[3], i, ret ;

if ( argc < 3 || argc > 3 )

{

printf ( "Too many or Too few arguments..." ) ;

exit ( 0 ) ;

}

for ( i = 1 ; i < argc ; i++ )

a[i] = atoi ( argv[i] ) ;

ret = a[1] * a[2] ;

return ret ;

}

 

/* Spawn.c */

#include <process.h>

#include <stdio.h>

main( )

{

int val ;

val = spawnl ( P_WAIT, "C:\\Mult.exe", "3", "10", "20", NULL ) ;

printf ( "\nReturned value is: %d", val ) ;

}

 

Here, there are two programs. The program 'Mult.exe' works as a child process whereas

'Spawn.exe' works as a parent process. On execution of 'Spawn.exe' it invokes 'Mult.exe' and passes the command-line arguments to it. 'Mult.exe' in turn on execution, calculates the product of 10 and 20 and returns the value to val in 'Spawn.exe'. In our call to spawnl( ) function, we have passed 6 parameters, P_WAIT as the mode of execution, path of '.exe' file to run as childprocess, total number of arguments to be passed to the child process, list of command line arguments and NULL. P_WAIT will cause our application to freeze execution until the child process has completed its execution. This parameter needs to be passed as the default parameter if you are working under DOS. under other operating systems that support multitasking, this parameter can be P_NOWAIT or P_OVERLAY. P_NOWAIT will cause the parent process to execute along with the child process; P_OVERLAY will load the child process on top of the parent process in the memory.

 

-------------------------------------------------------------------------------------------------

 

Are the following two statements identical?

 

char str[6] = "Kicit" ;

char *str = "Kicit" ;

 

Ans:

No! Arrays are not pointers. An array is a single, pre-allocated chunk of contiguous elements (all of the same type), fixed in size and location. A pointer on the other hand, is a reference to any data element (of a particular type) located anywhere. A pointer must be

assigned to point to space allocated elsewhere, but it can be reassigned any time. The array declaration char str[6] ; requests that space for 6 characters be set aside, to be known by name str. In other words there is a location named str at which six characters are stored.

 

The pointer declaration char *str ; on the other hand, requests a place that holds a pointer, to be known by the name str. This pointer can point almost anywhere to any char, to any

contiguous array of chars, or nowhere.

 

-------------------------------------------------------------------------------------------------

 

…till next post, bye-bye & take care.

Wednesday, July 4, 2018

C Questions And Answers – 2018A4

There are many commonly asked questions regarding C programming language. Below are some collected such question-answer examples. The questions are usually related with Turbo C IDE in windows or GCC under Linux environment [not always].

For more such examples, click C_Q&A label.

 

-------------------------------------------------------------------------------------------------

 

How can I find the day of the week of a given date?

 

Ans:

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 ) ) ;

}

 

-------------------------------------------------------------------------------------------------

 

What's the difference between these two declarations?

 

struct str1 { ... } ;

typedef struct { ... } str2 ;

 

Ans :

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.

 

-------------------------------------------------------------------------------------------------

 

The Spawnl( ) function...

 

DOS is a single tasking operating system, thus only one program runs at a time. The

Spawnl( ) function provides us with the capability of starting the execution of one program

from within another program. The first program is called the parent process and the second program that gets called from within the first program is called a child process. Once the second program starts execution, the first is put on hold until the second program completes execution. The first program is then restarted. The following program demonstrates use of spawnl( ) function.

 

/* Mult.c */

int main ( int argc, char* argv[ ] )

{

int a[3], i, ret ;

if ( argc < 3 || argc > 3 )

{

printf ( "Too many or Too few arguments..." ) ;

exit ( 0 ) ;

}

for ( i = 1 ; i < argc ; i++ )

a[i] = atoi ( argv[i] ) ;

ret = a[1] * a[2] ;

return ret ;

}

 

/* Spawn.c */

#include <process.h>

#include <stdio.h>

main( )

{

int val ;

val = spawnl ( P_WAIT, "C:\\Mult.exe", "3", "10", "20", NULL ) ;

printf ( "\nReturned value is: %d", val ) ;

}

 

Here, there are two programs. The program 'Mult.exe' works as a child process whereas

'Spawn.exe' works as a parent process. On execution of 'Spawn.exe' it invokes 'Mult.exe' and passes the command-line arguments to it. 'Mult.exe' in turn on execution, calculates the product of 10 and 20 and returns the value to val in 'Spawn.exe'. In our call to spawnl( ) function, we have passed 6 parameters, P_WAIT as the mode of execution, path of '.exe' file to run as childprocess, total number of arguments to be passed to the child process, list of command line arguments and NULL. P_WAIT will cause our application to freeze execution until the child process has completed its execution. This parameter needs to be passed as the default parameter if you are working under DOS. under other operating systems that support multitasking, this parameter can be P_NOWAIT or P_OVERLAY. P_NOWAIT will cause the parent process to execute along with the child process; P_OVERLAY will load the child process on top of the parent process in the memory.

 

-------------------------------------------------------------------------------------------------

 

Are the following two statements identical?

 

char str[6] = "Kicit" ;

char *str = "Kicit" ;

 

Ans:

No! Arrays are not pointers. An array is a single, pre-allocated chunk of contiguous elements (all of the same type), fixed in size and location. A pointer on the other hand, is a reference to any data element (of a particular type) located anywhere. A pointer must be

assigned to point to space allocated elsewhere, but it can be reassigned any time. The array declaration char str[6] ; requests that space for 6 characters be set aside, to be known by name str. In other words there is a location named str at which six characters are stored.

 

The pointer declaration char *str ; on the other hand, requests a place that holds a pointer, to be known by the name str. This pointer can point almost anywhere to any char, to any

contiguous array of chars, or nowhere.

 

-------------------------------------------------------------------------------------------------

 

…till next post, bye-bye & take care.