ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-112Formatted Io Streams
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-112

    Programming Fundamentals

    Progress0 / 39 done
    Topics39
    1Introduction to Problem Solving, Algorithms, Programming, and C Language2Problem Solving, a brief review of Von-Neumann Architecture3The C Programming Language, Pseudo-code, Concept of Variable4Data types in Pseudo-code, The C Standard Library and Open Source5Input/Output, Arithmetic expressions, Assignment statement, Operator precedence6Concept of Integer division, Flowchart and its notations7Typical C Program Development Environment, Role of Compiler and Linker8Test Driving C Application
    9A Simple C Program: Printing Text, Adding Two Integer10Memory Concepts, Arithmetic in C, Operators
    11Equality and Relational Operators
    12The if, if...else, while Nested Control Statements
    13for, switch, do...while, break, continue, Logical Operators
    14Modularizing Program in C, Math Library Functions15Function Definitions and Prototypes, Function-Call Stack and Stack Frames16Stack rolling and unrolling, Headers, Passing Arguments by Value and by Reference17Random Number Generation, Scope Rules, Recursion, Recursion vs Iteration
    18Defining Arrays, Character Arrays, Static and Automatic Local Arrays19Passing Arrays to Function, Sorting and Searching Arrays20Multidimensional and Variable Length Arrays
    21Pointer Definitions and Initialization, Pointer Operators22Passing Arguments to Function by Reference, Using the const and sizeof Operator23Pointer Expressions and Arithmetic, Pointers and Arrays, Array of Pointers24Function Pointers
    25Strings and Characters, Character Handling Library26String Functions, Library Functions
    27Streams, Formatted Output with printf, Formatted Input with scanf
    28Defining Structures, Accessing Structure Member, Structures and Functions29typedef, Unions
    30Bitwise Operators, Bit Fields, Enumeration Constants
    31Files and Streams, Creating, Reading and Writing data to a Sequential and a Random-Access File
    32#include, #define, Conditional Compilation, #error and #pragma33# and ## Operators, Predefined Symbolic Constants, Assertions
    34Variable Length Argument List, Using Command Line Arguments35Compiling Multiple-Source-File Programs, Program Termination with exit and atexit36Suffixes for Integer and Floating-Point Literals, Signal Handling
    37calloc and realloc, goto
    38Self-Referential Structures, Linked Lists39Efficiency of Algorithms, Selection and Insertion Sort
    7 min read
    Topic 27 of 39
    Topic Study Note Illustration
    27

    Formatted Input/Output: Streams, Formatted Output with printf, Formatted Input with 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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    7mremaining
    1.2kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Programming Fundamentals