Ad Code

Responsive Advertisement

How To Take Input and Output In C Language

How To Take Input and Output In C Language

So lets start ......



1. The printf() function

The printf() function is the most used function in the C language. This function is defined in the stdio.h header file and is used to show output on the console (standard output).

Following is how the printf() function is defined in the C stdio.h library.

int printf(const char *format, ...);

It writes the C string pointed by the format pointer to the standard output (stdout). On success, the total number of characters written is returned.

This function is used to print a simple text sentence or value of any variable which can be of intcharfloat, or any other datatype.

printf() Code Examples

Let's start with a simple example.

1. Print a sentence

Let's print a simple sentence using the printf() function.

#include <stdio.h>

int main() {
   // using printf()
   printf("Welcome to Winsome reader");

   return 0;
}



We have seen many code examples like above, up until now in this tutorial series.

To understand the complete code and structure of a basic C language program, check Hello World Program in C.

2. Print an Integer value

We can use the printf() function to print integer value coming from a variable using the %d format specifier.

For example,

#include <stdio.h>

int main() {  
   int x = 10;
   // using printf()
   printf("Value of x is: %d", x);

   return 0;
}



In the program, above we have used the %d format specifier, to specify the type of the value that will be added there. The format specifiers %d and %i are used for integer value.

3. Print a Character value

The %c format specifier is used to print character variable value using the printf() function.


#include <stdio.h>

int main() {
   // using printf()
   char gender = 'M';
      
   printf("John's Gender is: %c", gender);
   return 0;
}


4. Print a Float and a Double value

In the code example below, we have used the printf() function to print values of a float and double variable.

For float value we use the %f format specifier and for double value we use the %lf format specifier.

#include <stdio.h>
int main() {
   // using printf() 
   float num1 = 15.50;
   double num2 = 15556522.0978678;
   
   printf("Value of num1 is: %f \n", num1);
   printf("Value of num2 is: %lf", num2);

   return 0;
}



5. Print multiple outputs

We can use a single printf() function to display values of multiple variables.

#include <stdio.h>

int main() {
   // using printf() for multiple outputs 
   int day = 20;
   int month = 11;
   int year = 2021;
   
   printf("The date is: %d-%d-%d", day, month, year);

   return 0;
}



We can also perform some simple calculations inside printf(). Here is a simple example for that,

#include <stdio.h>
int main()
{
    int a = 5, b = 6;
    printf("%d", a + b);
    return 0;
}


The scanf() function

When we want to take input from the user, we use the scanf() function and store the input value into a variable.

Following is how the scanf() function is defined in the C stdio.h library.

int scanf(const char *format, ...);


It reads data from stdin and stores it according to the parameter format into the locations pointed by the additional arguments. On success, the function returns the number of items of the argument list successfully filled.

The scanf() function can be used to take any datatype input from user, all we have to take care is that the variable in which we store the value should have the same datatype.

Here is the syntax for scanf():

scanf("%x", &variable);

where, %x is the format specifier.

Using the format specifier, we tell the compiler what type of data is in a variable and & is the address operator which tells the compiler the address of the variable so that the compiler can assign the variable with the value entered by the user.

scanf() Code Examples

Let's start with a simple example.

1. Input Integer value

If we have to take an integer value input from the user, we have to define an integer variable and then use the scanf() function.



#include <stdio.h>

int main() {

   // using scanf() 

   int user_input;

   

   printf("Please enter a number: ");

   scanf("%d", &user_input);

   printf("You entered: %d", user_input);


   return 0;

}


While running the code example above, there is a button for Input at top-right corner of editor, you can click on it and provide custom value for input.

In the above code example, we have used %d format specifier to inform the scanf() function that user input will be of type int.

And we have also used & symbol before the name of the variable, because &user_input refers to the address of the user_input variable where the input value will be stored.



2. Input Float value

Just like integer value, we can take input for any different datatype. Let's see an example for float type value.

#include <stdio.h>

int main() {

   // using scanf() 

   float user_input;

   

   printf("Please enter a decimal number: ");

   scanf("%f", &user_input);

   printf("You entered: %f", user_input);


   return 0;

}


We have used the %f format specifier and defined a float type variable. Try doing the same for taking a double type value as user input. The format specifier for double is %lf.

3. Input Character value

Let's see how we can take a simple character input from user.

#include <stdio.h>

int main() {

   // using scanf() 

   char gender;

   

   printf("Please enter your gender (M, F or O): ");

   scanf("%c", &gender);

   printf("Your gender: %c", gender);


   return 0;

}

4. Take Multiple Inputs from User

In the below code example, we are taking multiple inputs from the user and saving them into different variables.


#include <stdio.h>

int main() {

   // using scanf() for multiple inputs

   char gender;

   int age;


   printf("Enter your age and then gender(M, F or O): ");

   scanf("%d %c", &age, &gender);

   printf("You entered: %d and %c", age, gender);


   return 0;

}


Return Value of printf() & scanf()

The printf() function returns the number of characters printed by it, and scanf() function returns the number of characters read by it.

int i = printf("Saurabh yadav");

printf("Value of i is: %d", i);


In this program printf("studytonight"); will return 12 as result, which will be stored in the variable i, because the word studytonight has 12 characters.

The first printf() statement will print the statement studytonight on the output too.

Format Specifiers

To print values of different data types using the printf() statement and while taking input using the scanf() function, it is mandatory to use format specifiers.

It is a way to tell the compiler what type of data is in a variable. Some examples are %c%d%f, etc.


4. gets() & puts() functions

The gets() function reads a line from stdin(standard input) into the buffer pointed to by str pointer, until either a terminating newline or EOF (end of file) occurs.

Here is the syntax for the gets() function:

char* gets(char* str);

The puts() function writes the string str with a newline character ('\n') at the end to stdout. On success, a non-negative value is returned.

Here is the syntax for the gets() function:

int puts(const char* str);

#include <stdio.h>


void main()

{

    /* character array of length 100 */

    char str[100];

    printf("Enter a string: ");

    gets(str);

    puts(str);

    getch();

    return 0;

}

The fgets() function

Here is the syntax for the fgets() function:

char* fgets(char* str, int num, FILE* stream);

It reads characters and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first. A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str. On success, the function returns the str.

For example,

#include <stdio.h>

#define MAX 10

int main()

{

    char str[MAX];

    fgets(str, MAX, stdin);

    printf("The string is: %s", str);

    return 0;

}

Difference between scanf() and gets()

The main difference between these two functions is that scanf() stops reading characters when it encounters a space, but gets() reads space as a character too.

If you enter a name as Study Tonight using scanf() it will only read and store Study and will leave the part of the string after space. But gets() function will read it completely.

Let's see the scanf() function in action:

#include <stdio.h>

int main() {

   // using scanf() 

   char n1[50], n2[50];

   printf("Please enter n1: ");

   scanf("%s", n1);


   printf("You entered: %s", n1);

   return 0;

}

Conclusion

In this tutorial we learned about Input and Output in the C language. With many code examples, we understood how to use printf() function and scanf() function to show output to user and take input from the user.

We also learned about a few other functions used for showing output and taking user input.


Post a Comment

0 Comments

Close Menu