April 12, 2018

Input and Output in C


   Input means to feed some data into program and output means to display data on screen.


C programming language provides a set of built-in library functions to perform input-output operations. The set of library functions that performs input-output operations is known as standard I/O library.

To use any function from the standard I/O library, the header file stdio.h should be included in the program.

In this tutorial we will discuss about the input functions scanf() and getchar() and the output functions printf() and putchar(). There are several other input-output functions that will be discussed in upcoming tutorials.


Conversion Specifications

The functions scanf() and printf() make use of conversion specifications to specify the type and size of data. Each conversion specification must begin with a percent sign (%). Some conversion specifications are given below:

Conversion Specifications for printf()

Conversion
Character
Meaning
%c print a single character
%d, %i print a decimal integer
%u print an unsigned decimal integer
%o print an unsigned octal integer
%x print an unsigned hexadecimal integer using a, b, c, d, e, f
%X print an unsigned hexadecimal integer using A, B, C, D, E, F
%f print a floating point number (by default 6 digits printed after the point)
%e print a floating point number in exponential format.
%E same as %e, but it prints E for exponent
%g print a floating point number in %f or %e format whichever is shorter
%G print a floating point number in %f or %E format whichever is shorter
%s print a string
%% print a % sign
%p print a pointer in hexadecimal format


Conversion Specifications for scanf()

Conversion
Character
Meaning
%c read a single character
%d read a signed decimal integer
%i read a signed integer, base is decided by the prefix of the input number
 
read a signed hexadecimal integer if prefix is 0x

read a signed octal integer if prefix is 0

otherwise read a signed decimal integer
%u read an unsigned decimal integer
%o read an unsigned octal integer
%x, %X read an unsigned hexadecimal integer
%f read a floating point number
%e, %E read a floating point number
%g, %G read a floating point number
%s read a string


The modifier h can be used before conversion specifications d, i, o, u, x, X to specify short integer and the modifier l can be used before them to specify a long integer. The modifier l can be used before conversion specifications f, e, E, g, G to specify double while modifier L can be used before them to specify a long double. For example %ld, %hd, %Lf, %hx are valid conversion specifications.


printf() Function

The printf() library function is used to display information required by the user and also prints the values of the variables. The printf() function can be written as:

int printf("control string", variable list);

In this function, the control string contains conversion specification characters and text. It should be enclosed within double quotes. If the control string does not contain any conversion specification, the variable names are not specified.


Example 1: Printing string


#include <stdio.h>

int main(void)
{
    printf("Just Coding\n");  
    return 0;
}
Output :
Just Coding

In this example, the control string contains only text and no conversion specification characters, so the output is only text.


Example 2: Printing integer


#include <stdio.h>

int main(void)
{
    int age = 17;
    printf("%d", age);
    return 0;
}

Output :
17

In this example, the control string contains a conversion specification character %d, which implies that an integer value will be displayed. The variable age has the integer value to be displayed as output.


Example 3: Printing integer with some text


#include <stdio.h>

int main(void)
{
    int age=17;
    printf("Your age: %d", age);
    return 0;
}


Output :
Your age: 17

In this example, the control string contains text with conversion specification character %d. The text will be displayed as it is, and the value of variable age will be displayed in place of %d.



Example 4: Printing floating point number


#include <stdio.h>

int main(void)
{
    float pi = 3.14159;
    printf("%f", pi);
    return 0;
}


Output :
3.14159

In this example, the control string contains a conversion specification character %f, which implies that an floating point value will be displayed. The variable pi has the floating point value to be displayed as output.


Example 5: Printing floating point number with some text


#include <stdio.h>

int main(void)
{
    float pi=3.14159;
    printf("The value of pi is %f", pi);
    return 0;
}


Output :
The value of pi is 3.14159

In this example, the control string contains text with conversion specification character %f. The text will be displayed as it is, and the value of variable pi will be displayed in place of %f


Example 6: Printing character


#include <stdio.h>

int main(void)
{
    char ch = 'A';
    printf("%c", ch);
    return 0;
}

Output :
A

In this example, the control string contains a conversion specification character %c, which implies that a single character will be displayed and variable ch has that character value.


Example 7: Printing string


#include <stdio.h>

int main(void)
{
    char str[30] = "Just Coding";
    printf("%s", str);
    return 0;
}

Output :
Just Coding

In this example, the control string contains a conversion specification character %s, which implies that a string will be displayed and variable str is a character array, holding the string which will be displayed.


Example 8: Printing octal equivalent of decimal number


#include <stdio.h>

int main(void)
{
    int num = 10;
    printf("Octal equivalent of decimal %d = %o", num, num);
    return 0;
}

Output :
Octal equivalent of decimal 10 = 12

Here the second conversion specification character is %o, thus the octal equivalent of the decimal number stored in the variable num is displayed.


Return Value :
  • On success, the printf() function returns the number of characters printed by it.
  • On error, it returns EOF.



scanf() Function

The scanf() library function can be used for entering input data. This function can take all types of values (numeric, character, string) as input. The scanf() function can be written as:

int scanf("control string", address1, address2,.....);

This function should have at least two parameters. First parameter is a control string, which contains conversion specification characters. It should be within double quotes. The conversion specification characters may one or more; it depends on the number of variables we want to input. The other parameters are addresses of variables. In the scanf() function at least one address should be present. The address of a variable is found by preceding the variable name by an ampersand (&) sign. This sign is called the address operator and it gives the starting address of the variable name in memory. A string variable is not preceded by an & sign to get the address.

Example 1:

#include <stdio.h>

int main(void)
{
    int result;
    ----------
    scanf("%d", &result);
    ----------
}


In this example, the control string contains only one conversion specification character %d, which implies one integer value should be entered as input. This entered value will be stored in the variable result.

Example 2:


#include <stdio.h>

int main(void)
{
    float length;
    ----------
    scanf("%f", &length);
    ----------
}


In this example, the control string contains only one conversion specification character %f, which implies one floating point value should be entered as input. This entered value will be stored in the variable length.

Example 3:


#include <stdio.h>

int main(void)
{
    char ch;
    ----------
    scanf("%c", &ch);
    ----------
}


In this example, the control string contains only one conversion specification character %c, which means that a single character should be entered as input. This entered value will be stored in the variable ch.

Example 4:


#include <stdio.h>

int main(void)
{
    char name[30];
    ----------
    scanf("%s", name);
    ----------
}


In this example, the control string contains only one conversion specification character %s, which means that a string should be entered as input. This entered value will be stored in the variable name. Note that the variable name is not preceded by ampersand (&) sign.

Example 5:


#include <stdio.h>

int main(void)
{
    int age;
    float height;
    char grade;
    char name[30];
    ----------
    scanf("%d %f %c %s", &age, &height, &grade, name);
    ----------
}


In this example, the control string has four conversion specifications characters %d, %f, %c and %s, which means that one integer value, one floating point value, one single character and a string can be entered as input. These values are stored in the variables age, height, grade and name.

The input data can be entered as:

22 5.11 A Manish

When more than one values are input by scanf(), these values can be separated by whitespace characters like space, tab or newline (default). A specific character can also be placed between two conversion specification characters like colon (:), comma (,), hash (#), slash(/) etc.

Example 6:


#include <stdio.h>

int main(void)
{
    int day, month, year;
    ----------
    scanf("%d/%d/%d", &day, &month, &year);
    ----------
}


Suppose the data is entered as:

1/5/2018

1 is stored in variable day, 5 is stored in variable month and 2018 is stored in variable year. If we include any spaces between the conversion specifications inside the control string, then they are just ignored.

Example 7:


#include <stdio.h>
int main(void)
{

    int n;

    printf("Enter a number: ");
    scanf("%d", &n);
    printf("You entered %d", n);

    return 0;
   
}

Output:
Enter a number: 35
You entered 35

In this example, printf() function is used to display a message that tells the user to enter a number and also displays the integer value. While scanf() function is used to take integer value as input. 

Note : 

Almost all conversion specifiers in scanf() automatically skip all whitespace (blanks, tabs, or newlines) before trying to read anything. 

Consider the following example:

    scanf("%d", &a);
   
scanf("%d", &b);

In the above example the scanf() function will read two integers that are entered on different lines (second %d will consume the newline left over by the first) or on the same line, separated by spaces or tabs (second %d will consume the spaces or tabs).

The conversion specifiers that do not consume leading whitespace, such as %c, can be made to do so by using a whitespace character in the format string:

    scanf("%d", &a);
   
scanf(" %c", &ch); /* ignore the newline(\n) after %d, then read a char */


Example :


#include <stdio.h>

int main(void)
{
    int n;
    char ch;

    printf("Enter a number : ");
    scanf("%d", &n);

    printf("Enter a character : ");
    scanf(" %c", &ch); /* notice the space preceding %c */

    printf("\n");

    printf("n = %d\n", n);
    printf("c = %c\n", ch);

    return 0;
}
Output:
Enter a number : 7
Enter a character : A

n = 7
c = A



Return Value :
  • On success, scanf() function returns the number of input fields successfully scanned, converted, and stored. The return value does not include scanned fields that were not stored.
  • Return value = 0 if no fields were stored.
  • Return value = EOF if scanf() attempts to read at end-of-file.

Character I/O

getchar() and putchar() macros are used for character I/O in C, we will discuss what macros are in upcoming tutorials, but for now treat them as functions. getchar() reads a single character from the standard input (stdin) and returns it as integer. You can use this method in a loop in case you want to read more than one characters. putchar() outputs one character to standard output (stdout) and returns the same character. In case you want to display more than one characters, use putchar() method in loop. Check the following example:

#include <stdio.h>

int main(void)
{
    int c;
   
    printf("Enter a value : ");
    c = getchar();
   
    printf("\nYou entered : ");
    putchar(c);
   
    return 0;

}
Output :
Enter a value : a
You entered : a


When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered.



The standard input is generally associated with the keyboard while the standard output is generally associated with the screen.






No comments:

Post a Comment