Input/Output in C16 min read

  • Input/output in c establishes communication between user and program.
  • Input statements are used to read necessary data for the program through a keyboard or through the data files created earlier.
  • Output statements are used to display the message or result either on-screen or to data files or to print in a formatted manner.
  • Unlike other high-level languages ‘C’ language input and output, an operation is carried through its built-in function.
  • Each program that uses I/O function must include a statement #include<stdio.h> or #include<conio.h> or both header files at the beginning.
  • ‘C’ provides the following function for accepting data and displaying the result

There are two types of I/O library functions for accepting and displaying data,

1. Unformatted Functions

This function works only with the character data type and the conversion code while accepting or displaying results like required in the formatted function. They can be classified as Single character I/O and String I/O.

a) Single Character I/O

These kinds of statements are used to either accept a single character or display a single character.

1) getch() : This function is useful to accept a single character that is typed without waiting for the <Enter> key to be pressed. The character that is typed in is not echoed on the screen. It takes no parameters and it returns a value that is accepted through the keyboard. It is useful for accepting passwords. This function is found in the conio.h header file.

Syntax: variable = getch();

Example :

  • char c;
  • c = getch();

In the above example, the character accepted through the keyboard is assigned to character variable c. But the character that is typed is not echoed on the screen.

2) getche() : This function is useful to accept a single character that is typed without waiting for the <Enter> key to be pressed. The character that is typed is echoed on the screen. It takes no parameters and it returns a value that is accepted through the keyboard. This function is found in the conio.h header file.

Syntax : variable = getche();

Example :

  • char c;
  • c = getch();

In the above example, the character accepted through the keyboard is assigned to character variable c.

3) getchar() or fgetchar() : This function is useful to accept a single character and one must press <Enter> key. The character that is typed in is echoed on the screen. It takes no parameters and it returns a value that is accepted through the keyboard. This function is found in the stdio.h header file.

A difference between getchar() and fgetchar() is that getchar() is a macro while fgetchar() is a function.

Syntax: variable = getchar();

Example :

  • char c;
  • c = getchar();

In the above example, the character accepted through the keyboard is assigned to character variable c.

4) putch() : This function is useful to print one character on screen. This function is found in the conio.h header file.

Syntax : putch(character constant / variable);

Example :

  • char c;
  • c=getche(); or putch( getche());
  • putch(c);

In the above example, the character that is accepted through the keyboard is displayed using putch().

5) putchar() or fputchar() : This function is useful to print one character on screen, This function found in the stdio.h header file.

Syntax: putchar(character constant / variable);

Example :

  • char c;
  • c=getchar();
  • putchar(c);

In the above example, the character that is accepted through the keyboard is displayed using putchar().

b) String I/O

These kinds of functions are useful to accept a string (group of characters). For example, to accept and display the Name, Address of a student or employee, etc.

1) gets() : It reads a string from the keyboard. In ‘C’ string is terminated by a special character called Null character (“\0′). gets() function reads character until <Enter> key is not pressed through keyboard.

Syntax : gets (variable);

Example :

  • char name[20];
  • gets(name);

In the above example, gets() will accept the characters as long as the <Enter> key is not pressed.

2) puts() : This function prints the message or string value accepted or stored in the character array variable. Each puts () print message on a separate line.

Syntax : puts(String Constant / Variable);

Example :

  • char name[20];
  • puts(” Enter a Name”);
  • gets(name);
  • puts(name);

In the above example, puts() function displays the name accepted through gets() function.

2. Formatted I/O Functions

  • The formatted function allows you to print the data in a way that you select i.e. width of the number, where to print etc.
  • ‘C’ language provides scanf() and printf() as formatted input and output statements.
  • Unlike other I/O console functions which accept and display only character and string values, formatted I/O functions are used to accept and display character, string, and as well as Numeric values.
  • Generally, the printf() statement precedes every scanf() to prompt the user how many input values and what kind of data type is required through the keyboard.

A) scanf() :

This function is useful to accept character, string, and numeric values i.e. all kinds of basic data type values from the standard input (Keyboard). Thus this function is useful to ask the user for input.

Syntax : scanf(“Control String”: List of variables separated by comma i.e. argument list):

1) Control String (Format String):

  • The control string is enclosed within double quotation marks. These strings contain the conversion character and also determine the number of argument values to be accepted as per the user-defined variable list.
  • Each Control string starts with the character % and must follow the format code which specifies the data type for conversion.
  1. The types d, o, x, u may be preceded by the letter I to indicate they are long integers.
  2. The types e, g, f may be preceded by the letter L to indicate they are long double.

2) Argument List :

This list contains the variable name separated by commas. An ampersand (&) symbol, also called address operator must be included as a prefix to a variable of data type numeric and character. If ampersand is not used then the values entered are lost and the variable will hold some garbage value.

Inputting the value: During execution, the value can be input through the keyboard for scanf() either of the following two ways,

1) By giving space after each value is entered.

i) By pressing the <Enter> key after entering each value

Example :- 1) scanf(“%d %c %f”, &rollno, &sex,&percentage);

Where the variable name rollno, sex, and the percentage have previously been defined as int rollno; char sex; float percentage;

The conversion %d %c %f within double quotes tells the compiler that it should expect the user to type integer, character, and floating constant value for the second argument of scanf i.e. &rollno, &sex, &percentage respectively.

Ampersand (&) is used to indicate that the value that is accepted should be stored at the address of the variable name.

Example :- 2) To accept y or n only during execution, scanf(“%[yn])”,&choice);

B) printf():

The printf() function in ‘C’ is used as a formatted output statement and is useful to display character, string, and numeric values i.e. all kinds of basic data type values on screen by default. The name printf stands for print formatted values and displays the values at the current cursor location to advance to the next line a backslash character must be used and will be discussed very soon.

Syntax: printf(“control string”, list of variable separated by comma i.e. argument list);

1) Control String (Format String):

The control string is enclosed within double quotation marks. These strings contain the message or Escape sequence character or conversion character and also determine the number of arguments to be displayed as per the user-defined variable list. Each Control string starts with the character % and must follow the format code which specifies the data type for conversion. One can also specify the backslash character in the control string

2) Argument List :

This list contains the variable name separated by commas. Specifying an argument list is optional and useful when users want to display only a message.

1) printf (“value of aa %d “,aa);

Where the variable aa has previously been declared as an integer. The format control string value of aa is printed as it is and the format character %d tells the computer that it should print an integer value of the variable aa.

Other example of printf routine include,

2) Displaying only message

printf(“Enter the 2 numbers “);

3) Displaying only values

printf(“%d %f”,total_marks, percentage); of variable

4) Displaying message along with printing values

printf(“to count the total number of positive number = %d”, c);

5) Printing the integer values in decimal, octal and hexadecimal format

int a = 27;

printf(“%d %0 %x”, a, a, a);

6) Printing a floating-point number using

k = 157.89;

different floating format code

printf(“%f %g %e”, k, k, k);

7) Assigning the value in printf statement

int b, c=7;

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

8) Evaluating expression in printf statement

int pl=67, p2 = 58, p3 = 56;

printf(“Percentage = %d “, (p1+ p2 + p3) / 3.0);

9) Printing separate message

printf(“Hello” “World”);

3. Backslash Characters

  • The backslash (1) character in ‘C’ is called Escape character because a character after \ (slash) has special meaning in ‘C’ and causes an escape from the normal interpretation of a string.
  • For example, the backslash() and the letter ‘n’ when used in combination, cause the subsequent printing to begin on the next line therefore its combination ‘\n’ is called a new line character.

Similarly, other characters or letters can be combined with backslash characters to perform “special functions”. Backslash characters are also known as Control characters (as it allows control over the format of output) and various backslash characters are listed below:

Escape character Function PerformedASCII Value
\aGenerate beep sound and useful to alert the user.007
\bBackspace (Moves the cursor one position back)008
\fForm feed (Moves the cursor to the next page). Useful when output is printed through a printer012
\nNewline (Moves the cursor to the next line)010
\rCarriage return (Moves the cursor to the beginning of 013 the current line)013
\tHorizontal tab (Moves the cursor to the next tab stop)009
\vVertical tab (Moves the cursor to the first column of the next lines). Useful when output is printed through a printer011
\0The null character (Used to indicate the end of the string)000
\\Back slash printing092
\”Double quote printing034
\’Single quote printing039
\?Printing question mark 063

3.1 Trigraph Characters

  • In order to print a special symbol/character not listed on the keyboard, ‘C’ supports this facility by means of a Trigraph sequence to print these characters.
  • Trigraph sequence consists of 3 characters of which the first two are ?? and the third character is any character from the ‘C’ language character set.
  • It was invented by the ANSI C committee for the keyboards that support any version of the ISO 646 character set.

Example 1

Demo of printf Statement

#include<stdio.h> 
#include<conio.h> 

void main(void)
  
{
   clrscr();          /* Clear the Screen and place the cursor at topmost left corner */ 
   printf("Hello "); 
   printf("Friend, "); 
   printf("Filling great to talk with you"); 
  
   getch();
  
}

Output :- Hello Friend, Filling great to talk with you.

Observe that though three printf statements are written separately output is displayed on the same line.

Example 2

Demo of printf Statement using the escape sequence

#include<stdio.h> 
#include<conio.h> 

void main(void)
{
  clrscr(); 
  
  printf("Hello"); 
  printf("\n friend,"); 
  printf("\n\t Feeling great to talk with you");
  
  getch(); 
} 

Output:-

Hello –

Friend,

Feeling great to talk with you

Example 3

A program to display the list of messages at a specific location with color and other formatting

 #include <stdio.h> 
 #include<conio.h> 
 
 void main(void)
 {
   clrscr(); 
   
   gotoxy(10.12);                 /* This function is useful to place the cursor at specific location on the screen */ 
   printf(" Welcome "); 
   gotoxy(10,14); 
   textcolor(RED); 
   cprintf(" to the world of");   /* cprintf() does not allow backslash character */ 
   gotoxy(10,16); 
   textcolor(CYAN + BLINK); 
   cprintf("C"); 
   
   getch();
 }

4. Role of a Field Width in printf Statements

The field width is specified in order to print the value in formatted output.

Syntax : – %width [precision] type

  1. Width is a number that represents the minimum size of the field for displaying a number. The numbers are right-justified and characters are left-justified unless a negative width is used in that case the number is displayed left-justified and characters arc right-justified.
  2. The data item may be composed of fewer characters than the specified width. However, the number of characters in the actual data type cannot exceed the specified width, and such width is automatically expanded to accommodate the number.
  3. The precision after the decimal point indicates the number of decimal places to be displayed for a number of type float, double or long float.

4.1) Formatted Integer Output

It is useful to print integer values in a formatted manner.

Syntax : %wd

Where w is the width or number of digits to be printed. When output data length size is greater than width specification then the output will be displayed without alternation.

Example formatted integer values to print

#include<stdio.h> 
#include<conio.h> 

void main(void)

 {
  
  clrscr();
  
  printf("case a %d \n",456);      /* defaults to width of number */ 
  printf("case b%2d \n",456);      /* Also defaults to width of number */ 
  printf("case c %70 \n",456);     /* right - justified in a field of 7*/ 
  printf("case d \ %-7d| \n".456); /* left-justified in a field of 7 */ 
  printf("case e l%7d| \n".-456);  /* negative no. Right justified in a field of 7*/ 
  
  getch();
 
}

4.2) Formatted Float Output

Syntax: %w.df

Where d represents the number of digits after the decimal point and w represents the total width including the decimal point. When output data length size is greater than width specification then the output will be displayed without alternation before the decimal point and truncation tales place after the decimal point.

Example of Demo of formatted float values to be print

#include<stdio.h> 
#include<conio.h> 

void main(void)

  {
  
   clrscr();
   
   printf("case 1 %f \n",123.456);      /* prints in f format with 6 decimal digit */ 
   printf("case 2 %f} \n",123.4567898); /* print, rounding to 6 decimal place */
   printf("case 3 l%4.2f| \n",123.456); /* print with 2 decimal */
   printf("case 4 l%8.2f\ \n",123.456); /* Print in 2 decimal digit but in a field of 8 column */ 
   printf("case 5 %f} \n",1.23456e+02); /* print exponent value in flout formatting */ 
   
   getch();
   
}

Output :

63

case

case

case

1 123.4560001 2 |123.4567901 3|123.46 4 | 123.46

case

5 |123.456000 Ex. 1.6 /* Demo of formatted

case

4.3) Formatted Exponent Output

Example of exponent values to be print

#include<stdio.h> 
#include<conio.h> 

void main(void)

{
    
  clrscr();
  
  printf("case 1 %el \n",123.456); 
  printf("case 2 l%el \n",1.23456e2); 
  printf("case 3 l%.3e \n",123.456); 
  printf("case 4 %12.3e \n",123.456); 
  
  getch();
  
}

Output :

/* print in exponent format */ /* print in actual format */ /* print with 3 decimal place */ /* print in a field of 12 with 3 decimal places */

1 1.234560e+021 case 2 1.234560e+021 3 [1.235e+02 41 1.235e+02 case case case

4.4) Formatted Character Output

Syntax : %we

Where w is the width. When the output data length size is greater than width specification then the output will be displayed without alternation otherwise blank spaces (width -1) are inserted before the character and in the case of negative width blank space are padded at the right.

Example of formatting string values tp be print

#include<stdio.h> 
#include<conio.h> 

void main(void)

 {
    
  clrscr();
  
  printf("case 1 |% s| \n","KEY TO C");        /* actual output */
  printf("case 2 |% 3s| \n","KEY TO C");       /* width is too small that's why it will print actual value */
  printf("case 3 |% 12s| \n","KEY TO C");      /* printed in a field wider than the string */
  printf("case 4 |% -12s| \n","KEY TO C");     /* ledt justified in a field og 12 columns */
  printf("case 5 |% 12.6s| \n","KEY TO C");    /* truncated to 6 character, printed in a field of 6 */ 
  printf("case 6 |% .6s| \n","KEY TO C");      /* truncated to 6 character */
  printf("case 7 |% -12.6s| \n", "KEY TO C");  /* truncated to 6 character, left justified in a field of 12 */ 
  
  getch(); 
  
}

Output :

case 1 | KEY TO C | case 2 ( KEY TO C | case 3 KEY TO CI case 4 KEY TO C 1 case 51 KEY TO 1 case 6 | KEY TO I case 7 | KEY TO 1

5. Mathematical Functions

Some of the predefined mathematical functions that are supported by the ‘C’ language are illustrated below, which we will use throughout the chapters as and when required. In order to use them, we must include a special header file known as math.h

5.1) Example of various mathematical function

#include<stdio.h> 
#include<conio.h> 
#include<math.h> 

#define R 3.14159/180 

void main( void)

 {
 
  clrscr();
  
  printf(" 1. %d\n ", abs(-15));         /* Returns absolute value of integer */ 
  printf(" 2. %f\n ", fabs(-15.234));    /*Returns absolute value of float */ 
  printf(" 3. %1d\n", labs(-12345678));  /* Returns absolute value of long integer */ 
  printf(" 4. %.2f\n", sin(30 * R));     /* Returns sin of 30 */ 
  printf(" 5. %.2f\n", cos(30 * R));     /* Returns cos of 30 */ 
  printf(" 6. %.2f\n", tan(30 * R));     /* Returns tan of 30 */ 
  printf(" 7. %.2f\n", sqrt(25));        /* Returns square root of positive value*/ 
  printf(" 8. %f\n", pow(2,3));          /* Returns power of 2^3 */ 
  printf(" 9. %f\n", fmod(5.6,3.1));     /* Returns remainder aller division */ 
  printf(" 10. %f \n", exp());           /* Returns exponentiation value */ 
  printf(" 11. %\n", log(16));           /* Returns logarithm */ 
  printf(" 12. %.2f\n", ceil(12.50));    /* Returns rounded value to next digit*/ 
  printf(" 13. %.2f\n", floor(12.50));   /* Returns truncated value */ 
  
  getch();
  
}

Output :

1. 15 2. 15.234000 3. 12345678 4. 0.50 5. 0.86 6. 0.57 7. 5.00 8. 8.000000 9. 2.500000 10. 2.718282 11. 2.772589 12. 13.00 13. 12.00

Explore Programming Skills

5.2) Example: A program to compute the sum and average of 3 integer numbers

#include <stdio.h>
#include<conio.h> 

void main(void)

  {
    
    int i, j, k, sum; 
    float avg; 
    
    clrscr(); 
    
    printf(" Enter three numbers :- "); 
    scanf("%d %d %d", &i, &j, &k); 
    sum = i + j + k ;
    avg = (float) sum / 3;  /* Type casting */ 
    printf(" Sum = %d \n Average = %f", sum. avg);
    
    getch();
    
}

5.3) Example: Write a program to find the parameters of a Circle

#include<stdio.h> 
#include<conio.h> 
#define PI 3.14 

void main(void) 

 { 
  
  float r,d,a,c; 
  
  clrscr(); 
  
  printf(" Enter Radius :-"); 
  scanf("%f",&r); 
  d = 2 * r;
  a = PI * r * r;
  c = 2 * PI * r;
  print("\n Diameter = %2f\n Area = %.2f\n Circumference of Circle = %2f",d,a,c); 
  
  getch();
  
}

5.4) Example: A program to find simple interest & compound interest for the rate of interest 8.5

#include<stdio.h> 
#include <conio.h> 
#include math.h> 

void main(void)  

 {
  
  long unsigned int p;        /* Where p:- Principal Amount */ 
  int n;                      /* n:- Number of years */
  float si, r = 8.5. ci, amt; /* r:- Rate of Interest */
  
  clrscr(); 
  
  printf(" Enter a principal amount and number of year :- "); 
  scanf("%1u %d", &p, &n);
  
  si = (p * n * r)/100;
  amt = p * pow ((1 + r/100,n);
  ci = amt - p;
  
  printf(" Simple interest is %.2f", si"); 
  printf("\n Compound interest = %.2f", ci);
  
  getch();
  
}

Share:

Leave a Reply