C Programming Tutorial - ITDeveloper

ITDeveloper : C Programming

C Programming

Step by Step Tutorials


Share with a Friend

Input Output In C

Input is given through the keyboard, and output may be shown on screen or printed through the printer or in another way. Still, for the different devices, there may be a different type of process for input/output, which may be a problem for the programmer. To avoid this, all input/output are done using streams in C, which handles input/output without taking care of where input is coming and the destination of the output. It can be added to any C program by introducing a Standard Input/Output library using stdio.h header.

Stream is the sequence of bytes of data in the form of a sequence of characters. While taking input, we get a sequence of characters entering into our program, that is, the input stream and for output, we send a sequence of characters out from our program, which is the output stream. The main advantage of the stream is it makes input/output programming independent of the device.

Input in C

Have you visited ATMs? If yes, you know ATM is an Electronic Banking outlet that provides transactions to the users based on some set of instructions. Still, for every user, it requires some details like a PIN, which means most algorithms have some set of instructions but need some external data/information to work over it. Input refers to the process of feeding data into the program. Data can be in a command line or from a file. Random Access Memory is kept by the C program while executing. When data come from an external location to the program, it is moved to RAM where the program can access it and that external data is known as input.

Output in C

Let's continue our ATM story so that when users provide PINs and other required inputs, the ATM, after performing all the instructions, provides cash, bank details, or other desired stuff, which means the algorithm, after performing on the input, provides the desired results. Still, it may be in different ways, like the output on screen or a print through a printer or in another way. Output refers to sending data out of the program or simply sending data to the location out of the program memory. The destination of the data may be a screen, printer, or Disk. For getting output, it is not always compulsory to have an input, like an algorithm for generating random numbers will simply return random numbers without any input.

Input and output of basic types in C

We have some input and output functions in C, let's look over them: Input

For taking input in C, we use the built-in function of the C scanf()scanf() method reads the input from standard input stream stdin and scans that input as per the type specified.

Syntax of taking input in C

 

scanf(“%A”, &variableOfAType);

 

The above syntax is for taking input from the user. Where %A defines format specifier in C, it helps the compiler identify the data type of variable for which we will take input, and '&' is the address operator in C. It helps the compiler change the actual value of this variable stored at this address in the memory.

Output

For display output to the user in C, we are using the built-in function of C printf(). printf() method writes the output to the standard output stream stdout and prints the value passed as the parameter to it.

Syntax of display output in C

 printf(“%A”, variableOfAType);

 

The above syntax for displays output to the user. Where %A defines format specifier in C, it helps the compiler identify the data type of variable we are going to output.

The basic type of input and output in C includes data types of variables like int, float, char, etc. The A in the above syntax is replaced with the appropriate format specifier of that type.

Format specifier for different data types

Data type value of A
int %d
float %f
char %c
long %l or %ld
double %lf

Syntax of input and output of basic data types in C

 

Integer:
Input: scanf("%d", & intVariable);
Output: printf("%d", intVariable);

Float:
Input: scanf("%f", & floatVariable);
Output: printf("%f", floatVariable);

Character:
Input: scanf("%c", & charVariable);
Output: printf("%c", charVariable);

 

Example

#include <stdio.h>
 
int main()
{
 
   // Declaring the variables
   int number;
   char character;
   float float_number;
 
   // --- Integer ---
 
   // Taking input for integer 
   printf("Enter the integer: ");
   scanf("%d", &number);
 
   // Printing Output of integer
   printf("\nEntered integer is: %d", number);
   
 
   // --- Float ---
 
   // Taking input of float
   printf("\nEnter the float: ");
   scanf("%f", &float_number);
 
   // Printing Output of float
   
   printf("\nEntered float is: %f", float_number);
 
   // --- Character ---
 
   // Taking input of Character
   printf("\n\nEnter the Character: ");
   scanf("%s", &character);
 
   // Printing Output of Character
   printf("\nEntered Character is: %c", character);
 
   return 0;
}

Output

Enter the integer: 10
Entered integer is: 10

Enter the float: 2.5
Entered float is: 2.500000

Enter the Character: A
Entered Character is: A

The above code takes the inputs for variables of a type character, integer, and float using scanf and then outputs them using printf() with the help of proper format specifiers.

Input and output of advanced types in C

There are various types of Advanced or user-defined data types in C, like:

  1. String
  2. Structure

To take the input or provide the output, we will use the same input and output functions of C that we have used for primary data types, let's discuss how we will do that.

1. String

Strings are simply a one-dimensional character array with an end line character ‘\0’ at the end. In string, all the characters are present in the contiguous memory block, and the maximum size of the string is pre-defined.

Syntax to define a string

char new_string[size];

Here, size is a pre-defined integer that refers to the maximum size of the string. There are four ways to take input of a string:

  1. gets()
  • This function will take the complete line as input from stdin and store it in the string given.
  • gets() function is removed in C11, so using this function may cause some errors.

Syntax:

gets(new_string);
  1. fgets()
  • This function takes input from a specific stream of characters. We send the maximum number of characters to take as input and based on this there are three cases possible:
    • If the number of characters in the stream is equal to or greater than the given maximum size, it will take the first n characters (where n is maximum size).
    • If the number of characters in the stream is less than the given size, it will take the complete line as input.
    • It stops when the newline character hits.
  • As the gets() function is removed, this function is one of the alternatives. Syntax:
  fgets(new_string,size,stdin);
  1. scanf() by using %[^\n]%*c as access specifier
  • This function will take the complete line as input, including the whitespaces.
  • %[^\n]%*c breaks into sub-parts:
    • In the scanf() function, we can use a regular expression to restrict the input here %[^\n] is used to take input only until no new line appears.
    • %c is used to take input of characters,
    • "*" is used to inform the scanf() function not to assign input to the variable until the whole input is taken.

Syntax:

scanf("%[^\n]%*c",new_string);
  1. scanf() by using %s as an access specifier
  • This function will take input only up to the first space character.

Syntax:

scanf("%s",new_string);

Note: In scanf() for string, we don't have to use "&" as the name of the string is a pointer to its first position and all of the functions mentioned above are present in stdio.h header file.

We use the printf() function to print the string by taking %s as a format specifier. Syntax:

printf("%s",new_string);

Example

#include <stdio.h>

int main() {
  // declaring maximum size of string
  int size = 50;

  // declaring the string 
  char new_string[size];

  // using gets function to take input
  gets(new_string);

  // using printf method to send output:
  printf("output 1: %s\n", new_string);

  // using gets function to take input
  fgets(new_string, size, stdin);

  // using printf method to send output:
  printf("output 2: %s\n", new_string);

  // using gets function to take input
  scanf("%[^\n]%*c", new_string);

  // using printf method to send output:
  printf("output 3: %s\n", new_string);

  // using gets function to take input 
  scanf("%s", new_string);

  // using printf method to send output:
  printf("output 4: %s\n", new_string);

  return 0;
}

For input:

input_1
input_2
input_3
input_4

Output:

output 1: input_1
output 2: input_2

output 3: input_3
output 4: input_4

In the above code we take the input for strings using different methods as discussed above and then print the strings using printf().

2. Structure

Structure is the user-defined data type, usually used to combine various data types together. A structure is consists of various data members and when we access its data members using dot operator they behave like normal data-types variables. So, the process of input/output for structure variables is similar to other data types variables using above-defined input and output functions of C. Let’s take an example for better understanding:

Example: We have created a structure, an object of it, then with the help of the dot operator access structure data members to take input with the help of scanf() function. At last, printed every variable by accessing it with dot operator and printing with printf() function. Code for this is mentioned below:

#include <stdio.h>

// structure consists of various type of data types
struct Person {
  char name[50]; // string data type
  int age; // int data type
  int house_number; // int data type
  float height; // float data type
};

int main() {
  // creating object of structure
  struct Person obj;

  // taking input for all data types 
  scanf("%s%d%d%f", obj.name, &obj.age, &obj.house_number, &obj.height);

  // printing all the data types
  printf("Name of the person is %s\n", obj.name);
  printf("Age of the person is %d\n", obj.age);
  printf("House Number of the person is %d\n", obj.house_number);
  printf("Height of the person is %f\n", obj.height);

  return 0;
}

Let us provides input as: Person_name 21 34 5.7

Output:

Name of the person is Person_name
Age of the person is 21
House Number of the person is 34
Height of the person is 5.700000

Built-in functions

 

scanf() and printf()

As we discussed above, scanf() and printf() are used for input and output methods of the programming language of c.

scanf() function helps to read the file or input which we provide and in scanf() function we use format specifiers like %c, %d, etc to detect the data type of variable which we give as input. Return type of scanf() is integer. scanf() functions return the total numbers of variables which are scanned successfully means total number of inputs. It has three types of return value they are -

  • Greater than zero if the variables are passed successfully.
  • Equal to zero if no variable provided.
  • Less than zero if error occurs or EOF (end-of-file).

Syntax

scanf(“%A”, &variableOfAType);  

Example1

scanf("%d%c", &val1, &val2);  

In the below example we are scanning two variables at a time. In which %d is used for first one val1 and %c is used for another one val2. So here the return value of it will be 2 because here it scanned 2 variables. If you observe, you can identify the data type of both variables are different, the first one is integer and the second one is character. We can easily identify it with the help of the Format specifier.

// C program to show scanf() return type

#include <stdio.h>

int main() {
 int val1;
 char val2;
 int result;

 printf("Enter value of val1 and val2: ");
 result = scanf("%d %c", &val1, &val2);
 printf("Total inputs passed successfully are: %d\n", result);

 return 0;
}

Output

Enter value of val1 and val2: 11 c
Total inputs passed successfully are: 2

printf() function is used for displaying output to the screen and in printf() function we use format specifiers like %c, %d, etc to detect the data type of variable which we give as input. Return type of printf function is integer. It returns the total no of characters given as output by printf().

Syntax

printf(“%A”, &variableOfAType);  

For example

printf("%d%c",val1,val2);  

In the below example, we print two variables val1 and val2 but you can see data type of val1 is integer and val2 is character and in integer you can give input -2e31 to 2e31-1 and in the character you can only give one character. So the printf() function returns the total number of characters in int plus one character. And here we do not providing any space or line gap between the val1 and val2 otherwise it was also counted.

// C program to show printf() return type

#include <stdio.h>

int main() {
 int result;
 int val1;
 char val2;
 printf("Enter value of val1 and val2: ");
 scanf("%d %c", &val1, &val2);
 result = printf("%d%c", val1, val2);
 printf("\nTotal printed characters are: %d\n", result);

 return 0;
}

Output

Enter value of val1 and val2: 1234 c 1234c
Total printed characters are: 5

getchar() and putchar()

putchar() function is the function of the standard output console. It displays only a single character at a time and character is a type of unsigned char (means char uses all 8 bits and there is no sign bit). And the character which is passed to this function is passed as a parameter. Return type of this function is int and it return the ASCII value of the character which is passed to it. If the function is executed successfully it returns the ASCII value of the character which passed as parameter to this function and otherwise return EOF if error occurs.

Syntax

int putchar(int char)  

Example 1

#include <stdio.h>
  
int main()
{
    char Character = 'A';
    putchar(Character);
 
    return (0);
}

Output

A

Example 2

#include <stdio.h>
  
int main()
{
    char Character = 'A';
    for(char i = Character;i <= 'Z'; i++){
      putchar(i);  
    }
    
    return (0);
}

Output

ABCDEFGHIJKLMNOPQRSTUVWXYZ

getchar() function is the function of the standard input console. It takes a single character as input at a time and it does not take any parameter. Return type of its character type of unsigned char which it reads as input and return EOF(end-of-file) if error occurs.

Syntax

int getchar (void);  
ch=getchar();

Example

#include <stdio.h>      
void main()  
{  
    char c;   
    printf ("\n write a char: ");  
    c = getchar();   
    printf(" value of char which we take as input: ");  
    putchar(c);      
} 

Output

 write a char: A
 value of char which we take as input: A

gets() and puts()

Puts functions are the part of output and gets functions are the part of input. They are declared in stdio.h header file.

puts() function used for print/displaying the output on the screen but here passes variables only in the form of line or string. It prints the passed string in the new line, and its return type is integer. It gives only two type of return value, they are-

  • Number of character which been printed to console if successful execution.
  • Any error or EOF (end of file).

Syntax

int puts(const char* str);  

Example

#include<stdio.h>
int main()
{
    char string[] = "Hello world!";
     
    int val = puts(string);
    printf("Returned Value Val = %d", val);
     
    return 0;
}

Output

Hello world!
Returned Value Val = 13

gets() function is used for the input method. It reads the line and stores it in the character array. Due to this function, we can get a input of string followed by enter or space as input.

The return type of this function is string. It returns a string (which passes as parameter in the gets() function) on successful execution and returns EOD (end of file) if any error occurs. Syntax

char *gets(char *str);  

Example


#include <stdio.h>

int main () {
   char string[50];

   printf("Enter a string : ");
   gets(string);

   printf("You entered: ");
   puts(string);
    
   return(0);
}
Enter a string : hello world!!
You entered: hello world!! 

fprintf()

fprintf() function is used for printing output in the file instead of the standard output screen.

Syntax

int fprintf(FILE *stream, const char *format, [arguments ...]);  

In the above syntax, stream represents the file where we have to print the output. format is a string, which is basically our output and it may be embedded by some format tags which are replaced by values passed as arguments.

Let's see an example for more understanding:

// C program to show fprintf()
  
#include<stdio.h>
int main()
{

  char str[50];

  //create file 
  FILE *fptr = fopen("example.txt", "w");
  if (fptr == NULL)
  {
    printf("Could not open file");
    return 0;
  }
  
  puts("Enter string");
  scanf("%[^\n]%*c", str);
  fprintf(fptr,"%s\n", str);
  fclose(fptr);

  return 0;
}

Output

Enter string
Hello world!

example.txt

Hello world!

In the above code, we created a file and taken a string as input. Then we write the taken input to the file using fprintf() function.

putch() & getche()

putch() function is declared in the conio.h header file. It is used to print a single character on the screen and the character is a type of alphanumeric char ( value can be alphabet or number).

getche() function is also declared in the conio.h header file. It is used to take characters from standard input keyboards and after taking input it immediately prints the output on output screen, we don't need to hit enter to give command for output.

Syntax

putch(ch);  
ch=getche();   

Format specifiers for input/output

Format specifier is used to define the data type of variable in input and output function in C. It helps compiler to identify the data type of variable. It is use inside the scanf() function for taking input and inside the prinf() function for displaying output. Total we have eight format specifier in c.

Data type Format specifiers Description
int %d use for decimal integer value
  %u use for unsigned integer value
  %o use for unsigned octal value
  %x use for unsigned hexadecimal value
long int %ld use for long int value
double %f use for double value
  %lf use for long double value
float %f use for floating point value
  %e use for floating point value in decimal or exponential form.
char %c use for single character value
  %s use for string of value of character