💻

Fundamentals of C Input and Output

Nov 27, 2024

Basic Input and Output in C

Overview

  • C language uses standard libraries for input and output operations.
  • The stdio.h or standard input-output library in C contains methods for input and output.

Input Function: scanf()

  • Purpose: Reads value from the console and stores it in a specified address.
  • Syntax: scanf("%X", &variableOfXType);
    • %X: Format specifier indicating the data type of the variable.
    • &: Address operator, indicating where the input should be stored in memory.

Output Function: printf()

  • Purpose: Prints the value passed as a parameter to the console screen.
  • Syntax: printf("%X", variableOfXType);
    • %X: Format specifier indicating the data type of the variable.

Input and Output of Basic Types

  • 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 Code for Basic Types

#include<stdio.h>

int main() {
    int num;
    char ch;
    float f;
    
    // Integer
    printf("Enter the integer: ");
    scanf("%d", &num);
    printf("\nEntered integer is: %d", num);

    // Float
    while((getchar()) != '\n'); // Clearing buffer
    printf("\n\nEnter the float: ");
    scanf("%f", &f);
    printf("\nEntered float is: %f", f);

    // Character
    printf("\n\nEnter the Character: ");
    scanf("%c", &ch);
    printf("\nEntered character is: %c", ch);

    return 0;
}

Input and Output of Advanced Types

  • String
    • Input: scanf("%s", stringVariable);
    • Output: printf("%s", stringVariable);

Example Code for Strings

#include<stdio.h>

int main() {
    char str[50];

    // Reading a word
    printf("Enter the Word: ");
    scanf("%s", str);
    printf("\nEntered Word is: %s", str);

    // Reading a sentence
    printf("\n\nEnter the Sentence: ");
    scanf("%[^\n]s", str);
    printf("\nEntered Sentence is: %s", str);

    return 0;
}

Related Resources

Summary

  • Understanding basic input and output in C is crucial for interacting with users and files, forming the core for more complex programs and data structures.
  • Mastery of scanf() and printf() facilitates effective data handling in C programming.