-->

Learn to code the on-demand coding Languages in an easy way. We help you understand programming concepts and coding Techniques Better.

Friday, January 29, 2021

printf() and scanf() in C

 Methods In C :


    The scanf() and  printf() functions are used to read the input from the console and output to the console. Both the functions are built-in functions defined in stdio.h(standard input output) header file. C has many built-in library functions. Whenever we use any built-in functions we need to declare the header file to which the built-in function belongs to.

 scanf(): The scanf() function is used to read the input from the console/user.

 syntax: 

 scanf("format specifiers",&variables_list);

 Example: 

 scanf("%d %d", &var1,&var2); [no of specifiers = no of variables]

        %d: %d in scanf allows the function to recognize user input as being of an integer data type.

        &: The ampersand(&) allows us to pass the address[place in memory] of the variable where we store the information that the scanf read. 


printf(): The print() function is used for output to the console.

Syntax: 

printf("format specifiers", variable_list);

 No need for an ampersand(&) symbol in printf().

 Example: 

  printf("%d %d",var1,var2);

Format Specifiers: The format specifiers are used in C for input and output purposes. Using these format specifiers, the compiler can understand that what type of data is in a variable during taking input using the scanf() function and printing using printf() function.        

Format specifier

                 Type

        %d

Signed integer

[both positive and negative values]

        %i

Unsigned integer [only positive values]

        %l

Long integer

        %lld

Long long integer

        %c

character

        %f

Float values

        %lf

Double values

        %Lf

Long double

        %s

String 



Examples:

    1. write a program for the input of two variables and print those variables.
        
         program:
        
     

        Output:

     

    Explanation: For every variable input or output we must specify its corresponding format specifier. The output of the variables format depends on its declaration. 

2. write a program to display numbers from 0 to a given number.
    
      program:
        
  

     Output:

  


 Rules to remember while writing the code :
    
      1. Declare variables before they used in the code.
      2. Be thorough with the syntaxes.
      3. Don't forget to put the semicolon at the end of each statement;
      4. Follow the indentation for a better understanding and to modify code easily.
      5. For every block there must be opening and closing curly braces. 

prev<---Jump statements                                           Next Topic--->Arrays in C





No comments:

Post a Comment