4 Input and Output in C – Programming in C, 3/e, 3rd Edition

CHAPTER 4

Input and Output in C

Chapter Outline
4.1  INTRODUCTION

Reading input data, processing it and displaying the results are the three tasks of any program. The data is read from the input device such as a keyboard. Operations on the data are performed on the basis of the operators, and the result is displayed on the screen. All the three tasks are important and none of them can be ignored.

There are two ways to accept the data. In one method, a data value is assigned to the variable with an assignment statement. The programmer writes assignment statements in most of the programs. The assignment statements are mentioned throughout the book. Examples of an assignment statement are as follows:

(i) int year=2005; (ii) char letter=‘a’; (iii) long int x=123456.

Another way of accepting the data is with functions. In C the input and output functions can be used for inputting the data and for getting the results, respectively. To perform these tasks in a user friendly manner, C has a number of input and output functions. When a program needs data, it takes the data through the input functions and sends results obtained through the output functions. Thus, the input/output functions are the link between the user and terminals.

There are a number of I/O functions in C, based on the data types. The input/output functions are classified in two types:

  1. Formatted functions
  2. Unformatted functions

With formatted functions, the input or output is formatted as per our requirement. The readability in easy way is possible with formatted functions. For example, with formatted functions one can decide how the result should appear or display on the screen. The result can be shown on the second line or it can appear after leaving some space or if the result is a real number then decisions on the number of digits before and after decimal point, etc. will be taken care in formatted functions. All I/O functions are defined as stdio.h header file, which can be initialized at the starting of a program; that is this header file should be included in the program at the beginning. However, formatting is not possible with unformatted functions. Various functions of these categories are listed in Figure 4.1.

Streams perform all input and output operations. The streams are nothing but a sequence of bytes. In input operations, the bytes (data) flow from input device such as keyboard, a disc drive or network connection to main memory. Similarly, in output operation bytes flow from main memory to output devices such as monitor, printer, disc drive, network connection.

When a program performs input and output operations, the streams are connected to the program automatically. The operating system always allows streams to redirect to other devices. While performing these operations, if any error occurs, it will be reported on the screen by the third stream called standard error stream.

Further elaboration on formatted functions is as follows.

  1. Formatted Functions: The formatted input/output functions read and write, respectively, all types of data values. They require format string to produce formatted results. Hence, they can be used for both reading and writing of all data values. The formatted functions return values after execution. The return value is equal to the number of variables successfully read/written. Using this value, the user can find out the error that occurred during reading or writing of data. Using this function, the given numeric data can be represented in float, integer and double to possible available limits of the language.

    Figure 4.1  Formatted and unformatted functions

    The syntax of input function for inputting the data such as scanf() is as follows:

    scanf(“control string”, argu1, argu2,. . .);

    Precisely, if we write scanf() as scanf(“%d”,&x); where %d is a control string which is nothing but conversion specification and it is to be placed within double quote. The other part is the argument and a sign & (ampersand) must precede it. Arguments are the identifiers.

    For displaying the result, prinf() formatted function is used. In Section 4.2, printf() and scanf() are discussed in depth.

  2. Unformatted Functions: The unformatted input/output functions work only with character data type. They do not require format conversion symbol for formatting of data types because they work only with character data type. There is no need to convert data. In case, values of other data types are passed to these functions, they are treated as character data.
4.2  FORMATTED FUNCTIONS
  1. The printf() statement: The formatted output as per the programmers requirement is displayed on the screen with printf(). The list of variables can be indicated in the printf(). The values of variables are printed according to the sequence mentioned in printf(). The printf() function prints all types of data values to the console. It translates internal values to characters. It requires format conversion symbol or format string and variable names to print the data. The format string symbol and variable names should be the same in number and type. The syntax of printf() statement is as follows:

     

    printf(“Control string”,variable1,variable2,. . .variable n);

     

    The control string specifies the field format such as %d, %s, %g, %f, and variables as taken by the programmer.

    The following are a few examples of the printf() function.

    Example:

     

    void main()

    {

    int x=2;

    float y=2.2;

    char z=‘C’;

    printf(“%d %f %c”,x,y,z);

    }

    OUTPUT:

    2 2.2000 C

    In the above program, %d corresponds to ‘x’ variable, %f to y and %c to ‘z’. The conversion symbol given by the user helps the printf() to identify the data type of a given variable. In case a mismatch occurs, the value of a variable is converted according to the conversion symbol given.

    Example:

     

    int main()

    {

    int y=65;

    clrscr();

    printf(“%c %d”,y,y );

    return 0;

    }

    OUTPUT:

    A 65

    In the above example, the integer variable ‘y’ contains the value of 65. The variable ‘y’ is printed using two-conversion symbols, integer and character. As shown in the output, %c converts numeric 65 value to its corresponding character A. %d prints the value 65, as it is, because the variable is of integer type. Sometimes, if no conversion is possible between two data types, some garbage value is printed.

    Example:

     

    int main()

    {

    int y=7;

    clrscr();

    printf(“%f”,y );

    return 0;

    }

    In the above example, it is attempted in the printf() statement to print the integer value as float value providing %f as a conversion symbol. This is not the proper way. While compiling time no error occurs, but after execution the printf() function will produce an error message ‘floating points formats not linked’.

    The format string is nothing but a string that begins and ends with the double quote. The printf() statement is used to display the data on console or stdout (standard output device). The format string is a combination of two types of character objects. They are plain character and conversion specification.

4.3  FLAGS, WIDTHS AND PRECISION WITH FORMAT STRING

The plain characters are straightforward and are used to write data on the screen. On the other hand, the conversion specification retrieves arguments from the list of arguments and apply different formatting to them. All format specification starts with % and a format specification letter after this symbol. It indicates the type of data and its format. In case the format string does not match the corresponding variable, the result will not be correct.

Flags: Flags are used for output justification, numeric signs, decimal points, trailing zeros. The flag (−) left justifies the result. If it is not given, the default is right justification. The plus (+) signed conversion result always starts with a plus (+) or a minus (−) sign.

Width specifier : It sets the minimum field width for an output value. Width can be specified through a decimal point or using an asterisk ‘*’.

Few programs are provided on width requirement.

4.1  Write a program to demonstrate the use of width specifier.

 

void main()

{

clrscr();

printf(“\n%.2s”,“abcdef”);

printf(“\n%.3s”,“abcdef”);

printf(“\n%.4s”,“abcdef”);

}

OUTPUT:

ab

  abc

  abcd

Explanation:

Observe the above program carefully and watch the width specified along with conversion specification character %s. Although the actual string length is six characters, the number of printed characters as per printf() statements is 2, 3 and 4, respectively.

4.2  Write a program to demonstrate the use of width specifier.

 

void main()

{

int x=55,y=33;

clrscr();

printf(“\n %3d”,x−y);

printf(“\n %6d”,x−y);

}

OUTPUT:

22

   22

Explanation:

In this program, in the first printf() statement width is given 3 and in second width is given 6. Hence, the results are displayed at different positions on the screen.

4.3  Write a program to demonstrate the use of ‘*’ for formatting.

 

void main()

{

int x=55,y=33;

clrscr();

printf(“\n %*d”,15,x−y);

printf(“\n %*d”,5,x−y);

}

OUTPUT:

    22

22

Explanation:

In this program, ‘*’ is used along with format string or conversion specification character %d. An extra parameter is required to mention or set the starting column for printing. This value is given along the set of variables. You can observe in the printf() statements the values 15 and 5 that indicate the position from where printing on screen begins.

Precision specifiers: Precise results on the screen can be obtained. The precision specifier always starts with a period or a dot in order to separate it from any preceding width specifiers.

Consider the following program:

4.4  Write a program to demonstrate the use of precision specifiers.

 

void main()

{

float g=123.456789;

clrscr();

printf(“\n %.1f”,g);

printf(“\n %.2f”,g);

printf(“\n %.3f”,g);

printf(“\n %.4f”,g);

}

OUTPUT:

123.5

123.46

123.457

123.4568

Explanation:

In the above program, the precision value is specified before the format string. Fractional part after decimal point can be precisely shown in various printf() statements. The output shows these numbers.

From the above examples, it is now clear that outputs can be shown in different formats. Table 4.1 describes the various formats for presenting various outputs.

 

Table 4.1  Formats for various outputs

A programming example is provided on the above formats for readers understanding.

4.5  Write a program to display the integers, float point numbers and string with different formats as explained above.

 

void main()

{

clrscr();

printf(“\n%5d”,12);

printf(“\n%5d”,123);

printf(“\n%5d”,1234);

printf(“\n %4.5f”,6.12);

printf(“\n %4.6f”,16.12);

printf(“\n %4.7f”,167.12);

printf(“\n %4.8f”,1678.12);

printf(“\n %8s”,“Amitkumar”);

printf(“\n %8.2s”,“Amitkumar”);

getche();

}

OUTPUT:

  12

 123

1234

6.12000

16.120000

167.1200000

1678.12000000

Amitkumar

       Am

(ii) The scanf() statement: The scanf() statement reads all types of data values. It is used for runtime assignment of variables. The scanf() statement also requires conversion symbol to identify the data to be read during the execution of the program. The scanf() statement stops functioning when some input entered does not match with format string. The syntax of the scanf() statement is the same as printf() except they work exactly opposite of each other.

Syntax:

The syntax of the input function for inputting the data is scanf().

Example:

scanf(“control string”, address of variable 1,address of variable 2,----);

The control string has to be enclosed within double quotes. It specifies the format specifier, such as %d for integer, %f for float, %c for character, etc. and the data are to be invoked by arguments, such as address of variable1, address of variable 2, etc.

Precisely, we write scanf() as scanf(“%d”,&x);

Here, “ %d” is the format specifier in the control string, which is nothing but the conversion specification and it is to be placed within double quotes. The other part is the variable and & (ampersand) must precede it.

The format specifiers and their meanings are given below.

%d: The data is taken as integer.

%c: The data is taken as character.

%s: The data string.

%f: The data is taken as float.

 

scanf(“%d %f %c”,&a,&b,&c);

The scanf() statement requires ‘&’ operator called address operator. The address operator prints the memory location of the variable. Here, in the scanf() statement the role of ‘&’ operator is to indicate the memory location of the variable, so that the value read would be placed at that location.

The scanf() statement also returns values. The return value is exactly equal to the number of values correctly read. In case of any mismatch, error will be thrown. Otherwise, if the read value is convertible to the given format, conversion is made. The following program shows an example of such a mismatch case.

4.6  Write a program to show the effect of mismatch of data types.

 

void main()

{

int a;

clrscr();

printf(“Enter value of ‘A’ : ”);

scanf(“%c”,&a);

printf(“A=%c”,a);

}

OUTPUT:

Enter value of ‘A’ : 8

A=8

Explanation:

In the above program, although the type of variable ‘a’ is int, it works perfectly with conversion symbol of character, i.e. character and integer data types are compatible to each other. When the two data types are compatible to each other, the compatible range is equal to the lowest range from the two data types. The above example illustrates this point.

4.7  Write a program to read and print the integer value using the character variable.

 

void main()

{

char a;

clrscr();

printf(“Enter value of ‘A’ : ”);

scanf(“%d”,&a);

printf(“A=%d”,a);

}

OUTPUT:

Enter value of ‘A’ : 255

A=255

Enter value of ‘A’ : 256

A=0

Explanation:

In the above program variable ‘a’ is of character type, i.e. its valid range is 0 to 255. The variable ‘a’ is used with conversion symbol of integer data type, i.e. in the printf() and scanf() statements the variable ‘a’ is supposed as an integer type. The value read in the first execution is valid. Hence, it is printed as it is read. In the second execution, the value read is greater than the range of the character type. In such a case, the excess range is again considered as the beginning or starting point. Here, the excess value is 1. That is why 0 is printed.

Consider the following scanf() statements, where a, b and c are integer variables.

Examples:

  1. scanf(“%d %d %d”,a,b,c);
  2. scanf(“%d,%d,%d”,a,b,c);

In the first statement, the format strings (%d) are separated by a space. It indicates that while inputting values for these variables, the values should be separated by space. Similarly, in the second statement, the format strings (%d) are separated by a comma; therefore, while inputting, values should be separated by a comma. The following program illustrates this.

4.8  Write a program to demonstrate the use of comma with scanf() statement.

 

void main()

{

int a,b,c;

clrscr();

printf(“\nEnter values :”);

scanf(“%d, %d,%d”,&a,&b,&c);

printf(“a=%d b=%d c=%d”,a,b,c);

}

OUTPUT:

Enter values: 4,5,8

a=4 b=5 c=8

Explanation:

From the above program, it is very clear that if format strings are separated by commas, the inputs should also be separated by commas. The readers are advised to try this by writing more programs. Table 4.2 describes the formats for the various inputs.

Table 4.2  Formats for the various inputs

An example illustrating a few formatted input is as follows.

4.9  Write a program to demonstrate the use of scanf() with different formats.

 

void main()

{

int a,b;

float x;

char name[20];

clrscr();

printf(“Enter two integers:-\n”);

scanf(“%4d %4d”,&a,&b);

printf(“\nEntered integers are”);

printf(“\n%4d %4d”,a,b);

printf(“\n”);

printf(“\nEnter a real number:-\n”);

scanf(“%f”,&x);

printf(“\n Entered float number is ”);

printf(“\n%f”,x);

printf(“\n”);

printf(“\nEnter a string :-\n”);

scanf(“%7s”,name);

printf(“\n Entered string ”);

printf(“\n%7s”,name);

getche();

}

OUTPUT:

Enter two integers:-

1 2

Entered integers are

1 2

Enter a real number:-

12.3

Entered float number is

12.300000

Enter a string:-

Deelipkumar

Entered string

Deelipk

Explanation:

In the scanf() statements, the format for various inputs are taken. Similarly, the outputs are also provided with various formats. The readers can verify the input and output.

The prinf() and scanf() statements follow different data types which are listed in Table 4.3. It can be seen from this table that format string is initialized with %sign as a special character, which indicates the format of the data to be displayed on the screen.

Table 4.3  Data types with conversion symbols

Data Type

Format String

Integer

Short integer

%d or %i

Short unsigned

%u

Long signed

%ld

Long unsigned

%lu

Unsigned hexadecimal

%x

Unsigned octal

%o

Real

Floating

%f or %g

Double floating

%lf

Character

Signed character

%c

Unsigned character

%c

String

%s

Octal number

 

%o

Displays Hexa decimal number in lowercase

 

%hx

Displays Hexa decimal number in uppercase

 

%p

Aborts program with error

 

%n

The printf() and scanf() statements follow the combination of characters called escape sequences. In order to come out, computers from routine sequence escape sequences are used. These are nothing but special characters starting with ‘\’. The escape sequences and their uses are illustrated in Table 4.4.

Table 4.4  Escape sequences with their ASCII values

Escape Sequence 

Use 

ASCII Value

\n

New line

10

\b

Backspace

8

\f

Form feed

12

\’

Single quote

39

\\

Backslash

92

\o

Null

0

\t

Horizontal tab

9

\r

Carriage return

13

\a

Alert

7

\”

Double quote

34

\v

Vertical tab

11

\?

Question mark

63

4.10  Write a program to show the effect of various escape sequences.

 

void main()

{

int a=1,b=a+1,c=b+1,d=c+1;

clrscr();

printf(“\tA=%d\nB=%d \‘C=%d\’”,a,b,c);

printf(“\n\b***\D=%d**”,d);

printf(“\n*************”);

printf(“\rA=%d B=%d”,a,b);

}

OUTPUT:

     A=1

B=2 ‘C=3’

***D=4**

A=1 B=2******

Explanation:

In the above program, a few commonly used escape sequences are described.

  1. In the first printf() statement due to ‘\t’, prints the value of ‘a’ after a tab. The ‘\n’ splits the line and prints the value of B and C on the next line.
  2. In the second printf() statement the three prefixes ‘*’ are written followed by the ‘\b’. The ‘\b’ overwrites the last character. The output D=4 will be displayed.
  3. In the third printf() statement only the sequences of ‘*’ are printed, but in the output only half line is displayed because it is affected by the fourth printf() statement.
  4. In the fourth printf() statement ‘\r’ is used which reverses the printable area one line before from the current location. Hence, the line generated by the third statement is replaced by the output of the fourth statement.

The programs illustrated below use printf() and scanf() statements.

4.11  Write a program to print the third power of 2 using pow() function. Assume the floating-point numbers.

 

#include <math.h>

void main()

{

double x = 2.0, y = 3.0;

clrscr();

printf(“%lf raised to %lf is %lf\n”, x, y, pow(x, y));

}

OUTPUT:

2.000000 raised to 3.000000 is 8.000000

Explanation:

In the above program, two variables x and y are declared and initialized. In the printf() statement using pow() function expression x^y is calculated and displayed.

4.12  Write a program to print the third power of 10 using pow10() function. Assume the floating-point numbers.

 

#include <math.h>

void main

{

int p = 3;

printf(“Ten raised to %lf is %lf\n”, p, pow10(p));

}

OUTPUT:

Ten raised to 3.000000 is 1000.000000

Explanation:

In the above program, power of 10 is calculated. Here, p is declared as an integer data type. The value returned by this function is of double data type. Hence, conversion symbol %lf is used.

4.13  Write a program to detect an error while inputting a data. Use return value of scanf() statement.

 

void main()

{

int a,b,c,v;

clrscr();

printf(“Enter value of ‘A’,‘B’ & ‘C’ : ”);

v=scanf(“%d %d %d”,&a,&b,&c);

 (v<3 ? printf(“\n Error In Inputting.”) : printf(“\n Values Successfully read.”));

}

OUTPUT:

Enter value of ‘A’,‘B’ & ‘C’ : 1 2 3

Value Successfully read.

Enter value of ‘A’,‘B’ & ‘C’ : 1 J 2

Error In Inputting.

Explanation:

In the above program, the printf() statement returns values equal to the number of variables correctly read. The conditional statement checks the value of variable ‘v’ and prints the respective messages.

4.14  Write a program to find the length of the string using printf() function.

 

void main()

{

char nm[20];

int l;

clrscr();

printf(“Enter String :”);

scanf(“%s”,nm):

l=printf(nm);

printf(“\nLength = %d”,l);

}

OUTPUT:

Enter String : HELLO

Length = 5

Explanation:

The printf() function returns the length of the string entered. In the above program the string entered is ‘HELLO’. Length of the string is 5, which is stored in variable ‘l’.

4.15  Write a program to perform the addition of two numbers.

 

void main()

{

int a,b,c;

printf(“\n ENTER TWO VALUES\n”);

scanf(“\n %d %d”, &a, &b);

c=a+b;

printf(“\n Sum is=%d”,c);

}

OUTPUT:

ENTER TWO VALUES 5 8

Sum is = 13

Explanation:

In the above program, variables a, b and c are declared. Values of a and b are read through the keyboard using scanf() statement. The addition of variables a and b is performed and assigned to variable c.

4.16  Write a program to find the square of the given number.

 

void main()

{

int a,c;

printf(“\n ENTER ANY NUMBER\n”);

scanf(“\n %d”, &a);

c=a*a;

printf(“\n SQUARE OF GIVEN NUMBER = %d”,c);

}

OUTPUT:

ENTER ANY NUMBER 5

SQUARE OF GIVEN NUMBER 25

Explanation:

The above program is same as the previous one. Only difference is that instead of addition, the square of a is calculated.

4.17  Write a program to input a single character and display it.

 

void main()

{

char ch;

clrscr();

printf(“Enter any character :”);

scanf(“%c”,&ch);

printf(“\n Your Entered Character is : %c”,ch);

}

OUTPUT:

Enter any character: C

Your Entered Character is: C

Explanation:

In the above program, a character is entered and stored in variable ch. The printf() statement displays the entered character.

4.18  Write a program to swap the values of two variables without the use third variable.

 

void main()

{

int a=7,b=4;

clrscr();

printf(“\n A= %d B= %d”,a,b);

a=a+b;

b=a−b;

a=a−b;

printf(“Now A= %d B= %d”,a,b);

}

OUTPUT:

A=7 B=4

Now A= 4 B=7

Explanation:

In the above program, no third variable is used as a mediator for swapping the values. The below given steps illustrate the working of the program.

  1. In the first statement, variable ‘a’ contains the sum of a+b, i.e. 11.
  2. In the second statement, variable ‘b’ contains a−b, i.e. 11−4 =7.
  3. In the third statement, variable ‘a’ contains a−b, i.e. 11−7=4.

Thus, the two values are interchanged.

4.4  UNFORMATTED FUNCTIONS

C has three types of I/O functions.

  1. Character I/O
  2. String I/O
  3. File I/O
  1. Character I/O

     

    1.

    getchar() -

    This function reads a character-type data from standard input. It reads one character at a time till the user presses the enter key. The syntax of the getchar() is as follows:

    Variable name=getchar();

    Example:

    char c;

    c=getchar();

    A program is supported for the following getchar() function.

    4.19  Write a program to accept characters through keyboard using getchar() function.

     

    void main()

    {

    char c;

    clrscr();

    printf(“\nEnter a char :”);

    c=getchar();

    printf(“a=%c”,c);

    }

    OUTPUT:

    Enter a char :g

    a=g

    Explanation:

    In the above program, a character variable c is declared. The getchar() reads a character through the keyboard. The same is displayed by the printf() statement.

     

    2.

    putchar() -

    This function prints one character on the screen at a time, read by the standard input.

    The syntax is as follows:

     

    putchar(variable name);

    Example:

    char c=‘C’;

    putchar (c);

    A program is provided on putchar().

    4.20  Write a program to use putchar() in work.

     

    void main()

    {

    char c=‘C’;

    clrscr();

    putchar(c);

    }

    OUTPUT:

    C

    Explanation:

    In this program, the character variable c assigns a char ‘C’; the same is displayed by the putchar() statement. The argument c is used with the putchar() statement.

     

    3.

    getch() & getche()

    These functions read any alphanumeric character from the standard input device. The character entered is not displayed by the gectch() function.

    Syntax of getche() is as follows:

     

    getche();

    4.21  Write a program to show the effect of getche() and getch().

     

    void main()

    {

    clrscr();

    printf(“Enter any two alphabetic”);

    getche();

    getch();

    }

    OUTPUT:

    Enter any two alphabetic A

    Explanation:

    In the above program, even though two characters are entered, the user can see only one character on the screen. The second character is accepted but not displayed on the console. The getche() accepts and displays the character whereas getch() accepts but does not display the character.

     

    4.

    putch() :

    This function prints any alphanumeric character taken by the standard input device.

    4.22  Write a program to read and display the character using getch() and putch().

     

    void main()

    {

    char ch;

    clrscr();

    printf(“Press any key to continue”);

    ch=getch();

    printf(“\n You Pressed :”);

    putch(ch);

    }

    OUTPUT:

    Press any key to continue

    You Pressed: 9

    Explanation:

    The function getch() reads a keystroke and assigns to the variable ch. The putch() displays the character pressed.

  2. String I/O

     

    1.

    gets () :

    This function is used for accepting any string through stdin (keyboard) until enter key is pressed. The header file stdio.h is needed for implementing the above function. Format of gets() is as follows:

     

    char str[length of string in number];

    gets(str)

    A program is given on gets().

    4.23  Write a program to accept string through the keyboard using the gets() function.

     

    void main()

    {

    char ch[30];

    clrscr();

    printf(“Enter the String :”);

    gets(ch);

    printf(“\n Entered String : %s”, ch);

    }

    OUTPUT:

    Enter the String : USE OF GETS()

    Entered String : USE OF GETS()

    Explanation:

    In the above program, gets() reads string through the keyboard and stores it in character array ch[30]. The printf() function displays the string on the console.

     

    2.

    puts() :

    This function prints the string or character array. It is opposite to gets().

     

    char str[length of string in number];

    gets(str);

    puts(str);

    A program is given on puts().

    4.24  Write a program to print the accepted character using puts() function.

     

    void main()

    {

    char ch[30];

    clrscr();

    printf(“Enter the String :”);

    gets(ch);

    puts(“Entered String :”);

    puts(ch);

    }

    OUTPUT:

    Enter the String: puts is in use.

    Entered String:

    puts is in use.

    Explanation:

    This program is the same as the previous one. Here, to display the string puts() function is used.

     

    3.

    cgets() :

    This function reads string from the console. The syntax is as follows.

    Syntax:

    cgets(char *st);

    It requires character pointer as an argument. The string begins from st[2].

     

    4.

    cputs() :

    This function displays string on the console. The syntax is as follows.

    Syntax:

    cputs(char *st);

    4.25  Write a program to read string using cgets() and display it using cputs().

     

    void main()

    {

    static char *t;

    clrscr();

    printf(“\n Enter Text Here :”);

    cgets(t);

    t+=2;

    printf(“\n Your Entered Text :”);

    cputs(t);

    getche();

    }

    OUTPUT:

    Enter Text Here: How are you?

    Your Entered Text: How are you?

    Explanation:

    In this example character pointer ‘t’ is declared. The cgets() function reads string through the keyboard and the cputs() function displays the string on the console.

4.5  COMMONLY USED LIBRARY FUNCTIONS

1.

clrscr()

This function is used to clear the screen. It clears previous output from the screen and displays the output of the current program from the first line of the screen. It is defined in conio.h header file. The syntax is as follows.

Syntax:

clrscr();

 

2.

exit()

This function terminates the program. It is defined in process.h header file. The syntax is as follows.

Syntax:

exit();

 

3.

sleep()

This function pauses the execution of the program for a given number of seconds. The number of seconds is to be enclosed between parentheses. It is defined in dos.h header file. The syntax is as follows.

Syntax:

sleep(1);

An example on sleep() is given below.

4.26  Write a program to show the effect of the sleep() function. 

 

void main()

{

static char t[10];

clrscr();

printf(“\n Enter Text Here :”);

gets(t);

printf(“\n Your Entered Text :”);

sleep(5);

puts(t);

getche();

}

OUTPUT:

Enter Text Here: ashok

Your Entered Text: ashok

Explanation:

The explanation is straightforward and self-explanatory. See the effect of sleep(5). The display appears after taking a pause.

 

3.

system ()

This function is helpful in executing different DOS commands. It returns 0 on success and –1 on failure. The syntax is as follows.

Syntax:

     system (“dir”);

The command should be enclosed within double quotation marks. After we run this command using C, directory will be displayed. Programmer can verify this command.

4.6  STRONG POINTS FOR UNDERSTANDABILITY

Computer produces output, which is useful for the user. Therefore, the clarity and neatness of result should appear in the output. The following are a few steps which can be followed to produce the neatness output:

  1. Give space between numbers.
  2. Provide suitable and problem-related variable names and headings.
  3. Provide user prompt so that the user can understand what to do.
  4. Provide a gap between two lines so that the text should be readable.
  5. Alert the user about what to do and what not to do.
  6. Use formatted inputs and outputs for precisely inputting the data and outputting results.
  7. It is recommended to use escape sequence characters such as \t, \b, \n.
SUMMARY

This chapter dealt with formatted functions such as printf() and scanf() statements. The unformatted functions such as putchar(), getche(), gets() have been illustrated with suitable examples. The different data types and conversion symbols used in the C programs have also been elaborated. The special symbols such as escape sequences together with their applications are also discussed. A few of the functions which are commonly used in the programs such as clrscr(), exit() are described in this chapter. Input and output functions together with examples are narrated with programming example. At last, the main points for the understanding of programs are given to the readers so that they can follow them.

EXERCISES

I  Fill in the blanks:

  1. _______functions provide the conversion symbol to identify the data type.
    1. Formatted
    2. Unformatted
    3. Library
    4. User defined
  2. ______functions does not convert data.
    1. Formatted
    2. Unformatted
    3. Library
    4. User defined
  3. The function prints all types of data values on to the console_____
    1. printf()
    2. scanf()
    3. gets()
    4. pow()
  4. The ________statement reads all types of data values.
    1. scanf()
    2. printf()
    3. puts()
    4. abs()
  5. _______function reads one character type data at a time till the user presses the enter key.
    1. getchar()
    2. puts()
    3. accept()
    4. floor()

II  True or false:

  1. Formatted functions require format string to format the data.
  2. The function gets() is an unformatted function.
  3. The ‘\n escape sequence inserts a tab.
  4. Formatted functions return values.
  5. The function gets() is defined in <string.h>.
  6. Any signed data type can have negative as well as positive values.
  7. The functions cgets() and cputs() work with character pointer as argument.
  8. While inputting values through scanf(), & is required before a variable name.
  9. The getche() is used to read data character by character.
  10. The char requires one byte space in the memory.
  11. The ‘\a’ escape sequence is for alert bell.
  12. The format string %g is used for float type.
  13. The %s is used to format the string.
  14. The format string %P is used to display hexadecimal in lowercase.
  15. The %lf is used for long integer

III  Select the appropriate options from the choices given in the questions:

  1. What will be the output of the following program?

    void main()

    {

    printf(“\n %d%d%d%d”,‘A’, ‘B’,‘C’,‘D’);

    }

    1. 65666768
    2. ABCD
    3. 91929394
    4. None of the above
  2. What will be the values of a and b after the execution of the following program?

    void main()

    {

    int a,b;

    a=65*66;

    b=‘A’ * ‘B’;

    clrscr();

    printf(“a=%d b=%d”,a,b);

    }

    1. a=4290 b=4290
    2. a=4290 b=AB
    3. a=4290 b=0
    4. None of the above
  3. What function is appropriate for accepting a string?
    1. gets()
    2. getch()
    3. getche()
    4. scanf()
  4. What is the ASCII range for 0 to 9 digits?
    1. 48 to 57
    2. 65 to 90
    3. 97 to 122
    4. None of the above
  5. What is the ASCII range for A to Z letters?
    1. 65 to 90
    2. 48 to 57
    3. 97 to 122
    4. None of the above
  6. The escape sequence ‘\t’ is a
    1. tab
    2. next line
    3. backspace
    4. None of the above
  7. What would be the value of x on execution of the program?

    void main()

    {

    float x=2.3;

    clrscr();

    x+=.2;

    printf(“%g”,x);

    }

    1. 2.5
    2. 4.3
    3. 4
    4. None of the above
  8. What will be the output of the following program?

    void main()

    {

    system(“”);

    }

    1. control goes to the DOS prompt
    2. syntax error
    3. bad command or file name
    4. None of the above
  9. Which is the correct statement for finding the cube of 2?
    1. pow(2,3);
    2. pow(3,2);
    3. pow(3);
    4. None of the above
  10. The abs() function displays
    1. an absolute value
    2. a negative value
    3. a zero value
    4. None of the above
  11. What will be the output of the following program?

    void main()

    {

    printf(“\n %d%d%d%d”,‘a’, ‘b’,‘c’,‘d’);

    }

    1. 979899100
    2. 87888990
    3. 90919293
    4. None of them
  12. What will be the output of the following program?

    void main()

    {

    char yourname[10]={“AJAY”};

    clrscr();

    printf(“\n Welcome %s to ‘C’ Programming Course”, yourname);

    }

    1. Welcome AJAY to ‘C’ Programming Course
    2. Welcome to ‘C’ Programming Course
    3. Welcome ‘C’ Programming Course
    4. None of them
  13. What will be the values of a and b after execution of the following program?

    void main()

    {

    int a,b;

    a=65*66;

    b=‘A’*‘B’;

    clrscr();

    printf(“a=%d b=%d”,a,b);

    }

    1. a=4290 b=4290
    2. a=4290 b=9506
    3. a=4290 b=0
    4. None of the above

IV  Attempt the following programming exercises:

  1. Write a program to input the rainfall of three consecutive days in CMS and find its average?
  2. Find the simple interest? Inputs are principal amount, period in year and rate of interest.
  3. Write a program to find the total number of minutes of 12 hours?
  4. Find the area and perimeter of (a) square and (b) rectangle. Input the side(s) through the keyboard?
  5. Accept any three numbers and find their squares and cubes.
  6. The speed of a van is 80 km/hour. Find the number of hours required for covering a distance of 500 km? Write a program in this regard.
  7. Write a program to convert inches into centimetres.
  8. Write a program to enter the name of this book and display it.
  9. Write a program to store and interchange two float numbers in variables a and b.
  10. Write a program to enter text with gets() and display it using printf() statement. Also find the length of the text.
  11. Write a program to ensure that the subtraction of any two-digit number and its reverse is always the multiple of nine. For example, entered number is 54 and its reverse is 45. The difference between them is 9.
  12. Write a program to convert kilograms into grams.
  13. Write a program to find the total amount when there are five notes of Rs. 100, three notes of Rs. 50 and 20 notes of Rs. 20.
  14. Write a program to enter the temperature in Fahrenheit and convert it to Celsius. Formula to be used is tc= ((tf−32)*5)/9 where tc and tf are temperatures in Celsius and Fahrenheit, respectively.
  15. Write a program to display the list of c program files and directories. Use system() function to execute DOS commands.

V  What will be the output/s of the following program/s?

  1. void main()

    {

    clrscr();

    printf(“\n %o %hx %p”,45, 65,65);

    }

  2. void main()

    {

    int x=67,y=68,z=69;

    clrscr();

    printf(“\n%c %c %c”,x, y,z);

    getche();

    }

  3. void main()

    {

    char str=”C Programming”;

    clrscr();

    puts(str);

    getche();

    }

  4. void main()

    {

    int k=‘A’;

    clrscr();

    while (k<=‘K’) putch(k++);

VI  Find the bug/s in the following program/s:

  1. void main()

    {

    int x=2;

    char y=‘A’;

    float f=2.05;

    clrscr();

    printf(“%d %c %f”,f,y,x);

    getche();

    }

  2. void main()

    {

    int x;

    clrscr();

    printf(“Enter a Number :”);

    scanf(“%d”,x);

    printf(“%d”,x);

    }

  3. void main()

    {

    char x,d;

    clrscr();

    printf(“Enter an alphabet:”);

    x= getchar();

    }

  4. void main()

    {

    clrscr();

    printf(“I \nam /n an\t Indian”);

    }

  5. void main()

    {

    putchar(“x”);

    }

VII  Answer the following questions:

  1. What are the formatted and unformatted functions?
  2. What is the difference between character I/O and string I/O?
  3. What is the escape sequence? List and indicate the functions of escape sequences.
  4. List any three escape sequences with their uses.
  5. What is the difference between puts() and putch()?
  6. What is the difference between getch() and getche()?
  7. How cgets() is different from gets()?
  8. How will you execute a DOS command through C program?
  9. What is the use of the exit() function?
  10. What is a stream?
  11. What are the tips to the design output?
ANSWERS

I  Fill in the blanks:

Q.

Ans.

1.

a

2.

b

3.

a

4.

a

5.

a

 

II  True or false:

Q.

Ans.

1.

T

2.

T

3.

F

4.

T

5.

F

6.

T

7.

T

8.

T

9.

T

10.

T

11.

T

12.

T

13.

T

14.

F

15.

F

III  Select the appropriate options from the choices given in the questions:

Q.

Ans.

1.

a

2.

a

3.

a

4.

a

5.

a

6.

a

7.

a

8.

a

9.

a

10.

a

11.

a

12.

a

13.

b

 

V  What will be the output/s of the following program/s?

Q.

Ans.

1.

55 41 0041

2.

C D E

3.

No Output

4.

ABCDEFGHIJK

VI  Find the bug/s in the following program/s:

Q.

Ans.

1.

Program runs but output will be 0 because formatted data cannot be displayed through unformatted functions. After putting them in sequence output will be 2 A 2.050000.

2.

In scanf() & is not prefixed before variable name.

3.

Header file <stdio.h> must be included

4.

No bug

5.

putchar() cannot be used to display string. Instead of it use puts().