C Input/Output (scanf, printf)

๐Ÿ”ค C Input and Output – Using printf() and scanf()

In C programming, printf() is used to display output to the user, while scanf() is used to take input from the user. These functions are part of the standard input/output library (stdio.h).

๐Ÿ”น printf() – Output Function

The printf() function is used to print text, variables, and formatted data to the screen.

๐Ÿ“ Example: Printing a Message

This simple program displays a greeting message.

#include <stdio.h>

int main() {
    printf("Hello, C Programmer!\n");
    return 0;
}
  

Try It Now

๐Ÿ”น scanf() – Input Function

The scanf() function is used to get input from the user. It requires the address of the variable using the & operator.

๐Ÿ“ Example: Taking Input from the User

This program asks for your name and age, then prints it back.

#include <stdio.h>

int main() {
    char name[50];
    int age;

    printf("Enter your name: ");
    scanf("%s", name);

    printf("Enter your age: ");
    scanf("%d", &age);

    printf("Hello %s, you are %d years old.\n", name, age);
    return 0;
}
  

Try It Now

๐Ÿ”ธ Format Specifiers

Here are some common format specifiers used in printf() and scanf():

  • %d โ€“ Integer
  • %f โ€“ Float
  • %c โ€“ Character
  • %s โ€“ String

โš ๏ธ Important Notes

  • Always use & before variable names in scanf() except for strings (arrays).
  • Use \n inside printf() to print a new line.

๐Ÿงช Practice Time

Modify the input program to take your favorite color or your birth year. Experiment with different format specifiers!