ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Programming Fundamentals
    CC-112
    Progress0 / 39 topics
    Topics
    1. Introduction to Problem Solving, Algorithms, Programming, and C Language2. Problem Solving, a brief review of Von-Neumann Architecture3. The C Programming Language, Pseudo-code, Concept of Variable4. Data types in Pseudo-code, The C Standard Library and Open Source5. Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6. Concept of Integer division, Flowchart and its notations7. Typical C Program Development Environment, Role of Compiler and Linker8. Test Driving C Application9. Introduction to C Programming: A Simple C Program: Printing Text, Adding Two Integer10. Memory Concepts, Arithmetic in C, Operators11. Decision Making: Equality and Relational Operators12. Structured Program Development: The if, if...else, while Nested Control Statements13. Program Control: for, switch, do...while, break, continue, Logical Operators14. Functions: Modularizing Program in C, Math Library Functions15. Function Definitions and Prototypes, Function-Call Stack and Stack Frames16. Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17. Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration18. Arrays: Defining Arrays, Character Arrays, Static and Automatic Local Arrays19. Passing Arrays to Function, Sorting and Searching Arrays20. Multidimensional and Variable Length Arrays21. Pointers: Pointer Definitions and Initialization, Pointer Operators22. Passing Arguments to Function by Reference, Using the const and sizeof Operator23. Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24. Function Pointers25. Characters and Strings: Strings and Characters, Character Handling Library26. String Functions, Library Functions27. Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf28. Structures: Defining Structures, Accessing Structure Member, Structures and Functions29. typedef, Unions30. Bit Manipulation and Enumeration: Bitwise Operators, Bit Fields, Enumeration Constants31. File Processing: Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File32. Preprocessor: #include, #define, Conditional Compilation, #error and #pragma33. # and ## Operators, Predefined Symbolic Constants, Assertions34. Other Topics: Variable Length Argument List, Using Command Line Arguments35. Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36. Suffixes for Integer and Floating-Point Literals, Signal Handling37. Dynamic Memory Allocation: calloc and realloc, goto38. Advance Topics: Self-Referential Structures, Linked Lists39. Efficiency of Algorithms, Selection and Insertion Sort
    CC-112›Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf
    Programming FundamentalsTopic 27 of 39

    Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with scanf

    7 minread
    1,230words
    Intermediatelevel

    Formatted Input/Output in C: Streams, printf, and scanf

    Formatted input and output (I/O) in C is essential for interacting with users and displaying data in a readable format. The printf and scanf functions are used to handle formatted output and input, respectively. These functions enable you to display data in a specific format and to read user input in a controlled manner. Understanding streams and how to use these functions is vital in C programming.


    1. Streams in C

    In C, a stream is a sequence of data elements that are made available for processing. Streams are used to represent input and output channels, such as standard input (keyboard), standard output (screen), and files.

    Standard Streams:

    • stdin: Standard input (usually the keyboard).
    • stdout: Standard output (usually the screen).
    • stderr: Standard error (used for error messages).

    These streams are automatically opened when the program starts and can be accessed via functions like scanf, printf, and fprintf.


    2. Formatted Output with printf

    The printf function is used to print formatted output to the standard output stream (stdout). It allows you to display text, variables, and formatted data in a controlled manner using format specifiers.

    Syntax of printf:

    int printf(const char *format, ...);
    
    • format: A string containing text and format specifiers.
    • ...: The variables to be printed, corresponding to the format specifiers.

    Common Format Specifiers in printf:

    • %d: Integer (decimal)
    • %f: Floating-point number
    • %s: String
    • %c: Character
    • %x: Hexadecimal integer (lowercase letters)
    • %X: Hexadecimal integer (uppercase letters)
    • %o: Octal integer
    • %p: Pointer (address)
    • %u: Unsigned integer

    Example of Formatted Output:

    #include <stdio.h>
    
    int main() {
        int num = 10;
        float pi = 3.14159;
        char ch = 'A';
        char name[] = "John";
    
        printf("Integer: %d\n", num);         // Prints an integer
        printf("Floating-point: %.2f\n", pi); // Prints a floating-point number with 2 decimal places
        printf("Character: %c\n", ch);       // Prints a character
        printf("String: %s\n", name);        // Prints a string
    
        return 0;
    }
    

    Explanation:

    • The %d format specifier is used to print the integer num.
    • The %.2f specifier prints pi with 2 decimal places.
    • The %c specifier prints the character ch.
    • The %s specifier prints the string name.

    Output:

    Integer: 10
    Floating-point: 3.14
    Character: A
    String: John
    

    Field Width and Precision:

    You can specify the width of the output and the precision for floating-point numbers using format specifiers.

    • Field Width: Specifies the minimum number of characters to be printed.
      • Example: %5d prints an integer with a minimum width of 5 characters.
    • Precision: For floating-point numbers, precision specifies the number of digits after the decimal point.
      • Example: %.3f prints a floating-point number with 3 digits after the decimal point.

    Example:

    #include <stdio.h>
    
    int main() {
        float pi = 3.14159;
    
        // Print with a field width and precision
        printf("Pi: %8.3f\n", pi);  // Prints "   3.142" (width 8, 3 decimal places)
    
        return 0;
    }
    

    Explanation:

    • The %8.3f specifier ensures that the number is printed in a field of width 8, with 3 digits after the decimal point.

    3. Formatted Input with scanf

    The scanf function is used to read formatted input from the standard input stream (stdin). It reads data from the user and stores it in the specified variables.

    Syntax of scanf:

    int scanf(const char *format, ...);
    
    • format: A string containing format specifiers that define the type and layout of the expected input.
    • ...: The variables where the input values will be stored, matching the format specifiers.

    Common Format Specifiers in scanf:

    • %d: Integer input
    • %f: Floating-point input
    • %s: String input
    • %c: Character input
    • %x: Hexadecimal integer input
    • %u: Unsigned integer input

    Example of Formatted Input:

    #include <stdio.h>
    
    int main() {
        int num;
        float pi;
        char name[20];
    
        // Reading an integer
        printf("Enter an integer: ");
        scanf("%d", &num);
    
        // Reading a floating-point number
        printf("Enter a floating-point number: ");
        scanf("%f", &pi);
    
        // Reading a string
        printf("Enter your name: ");
        scanf("%s", name);
    
        printf("\nYou entered:\n");
        printf("Integer: %d\n", num);
        printf("Floating-point: %.2f\n", pi);
        printf("Name: %s\n", name);
    
        return 0;
    }
    

    Explanation:

    • scanf("%d", &num) reads an integer and stores it in num.
    • scanf("%f", &pi) reads a floating-point number and stores it in pi.
    • scanf("%s", name) reads a string (up to the first space) and stores it in name.

    Output:

    Enter an integer: 10
    Enter a floating-point number: 3.14159
    Enter your name: John
    
    You entered:
    Integer: 10
    Floating-point: 3.14
    Name: John
    

    4. Handling Multiple Inputs

    You can read multiple values in a single scanf call by specifying multiple format specifiers.

    Example:

    #include <stdio.h>
    
    int main() {
        int a, b;
        float x;
    
        printf("Enter two integers and a float: ");
        scanf("%d %d %f", &a, &b, &x);
    
        printf("\nYou entered:\n");
        printf("Integer 1: %d\n", a);
        printf("Integer 2: %d\n", b);
        printf("Float: %.2f\n", x);
    
        return 0;
    }
    

    Explanation:

    • The scanf("%d %d %f", &a, &b, &x) reads two integers and one floating-point number.

    Output:

    Enter two integers and a float: 10 20 3.1415
    
    You entered:
    Integer 1: 10
    Integer 2: 20
    Float: 3.14
    

    5. Field Width and Precision in scanf

    You can specify field widths for input in scanf just like with printf. This ensures that the input fits into the specified space.

    Example:

    #include <stdio.h>
    
    int main() {
        int num;
        float pi;
    
        printf("Enter an integer (max 5 digits): ");
        scanf("%5d", &num);  // Max 5 digits for integer input
    
        printf("Enter a floating-point number (max 8 characters): ");
        scanf("%8f", &pi);  // Max 8 characters for floating-point input
    
        printf("\nYou entered:\n");
        printf("Integer: %d\n", num);
        printf("Floating-point: %.2f\n", pi);
    
        return 0;
    }
    

    Explanation:

    • scanf("%5d", &num) ensures that only 5 digits will be read for the integer.
    • scanf("%8f", &pi) ensures that only 8 characters will be read for the floating-point number.

    6. Important Notes about scanf

    • Whitespace Handling: In scanf, whitespace characters (spaces, tabs, newlines) are automatically ignored unless explicitly included in the format string (e.g., %c for a character).

    • Buffer Overflow: Always ensure that the destination variable (such as a character array) is large enough to hold the input, otherwise, a buffer overflow might occur.


    Summary of Key Points

    • Streams represent input/output channels, with stdin for input, stdout for output, and stderr for errors.
    • printf is used for formatted output, allowing you to control the appearance of the data displayed.
    • scanf is used for formatted input, enabling the program to read data in a structured manner.
    • Both functions use format specifiers like %d, %f, %s, etc., to specify the type of data being processed.

    By understanding how to use formatted I/O functions effectively, you can handle user input and output in a flexible, readable, and controlled manner.

    Previous topic 26
    String Functions, Library Functions
    Next topic 28
    Structures: Defining Structures, Accessing Structure Member, Structures and Functions

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,230
      Code examples0
      DifficultyIntermediate