Prinf and Scanaf

In C programming, printf() and scanf() are essential functions used for output and input operations. Both functions are defined in the stdio.h header file and are fundamental for interacting with the console.

printf() Function

The printf() function is used to print output to the console. It formats and displays data based on the specified format string.

Syntax:

printf("format string", argument_list);

format string: A string that specifies how to format the output. It can include placeholders (format specifiers) for variables.

argument_list: A list of variables or values that replace the placeholders in the format string.

Common Format Specifiers:

%d or %i: Integer

%c: Character

%s: String

%f: Floating-point number

Example:

#include <stdio.h>

int main() {
    int age = 25;
    float height = 5.9;

    printf("Age: %d\n", age); // Output: Age: 25
    printf("Height: %.1f\n", height); // Output: Height: 5.9

    return 0;
}

scanf() Function

The scanf() function is used to read input from the console. It reads the input data based on the specified format string and stores it in the provided variables.

Syntax:

scanf("format string", &variable_list);

format string: A string that specifies the format for reading input. It should match the expected type of the input.

variable_list: A list of pointers to variables where the input data will be stored.


Common Format Specifiers:


%d or %i: Integer

%c: Character

%s: String

%f Floating-point number

Example:

#include <stdio.h>

int main() {
    int age;
    float height;

    printf("Enter your age: ");
    scanf("%d", &age); // Reads an integer from the user

    printf("Enter your height: ");
    scanf("%f", &height); // Reads a floating-point number from the user

    printf("Age: %d\n", age);
    printf("Height: %.1f\n", height);

    return 0;
}

Key Points

• printf(): Used for output; formats and displays data.

• scanf(): Used for input; reads data from the user and stores it in variables.

• Ensure that the format specifiers in printf() and scanf() match the data types of the variables you are working with.

• Always use the address-of operator (&) with scanf() when reading values into variables.