In C programming, printf and scanf (not "get statement") are fundamental functions used for input and output. Here's an overview of both:

printf Function

The printf function is used to print formatted output to the console. Its syntax is:

#include <stdio.h>


int printf(const char *format, ...);

Parameters:

  • format: A string that specifies how to format the output. It can include format specifiers that begin with a % symbol.
  • ...: Additional arguments that are substituted in the format string.

Common Format Specifiers:

  • %d: Integer
  • %f: Floating-point number
  • %c: Character
  • %s: String
  • %x: Hexadecimal representation of an integer

Example:

#include <stdio.h>


int main() {

    int age = 40;

    float height = 5.9;

    char initial = 'A';

    char name[] = "Dr ahmed hamed";


    printf("Name: %s, Age: %d, Height: %.1f, Initial: %c\n", name, age, height, initial);

    return 0;

}

Output:

scanf Function

The scanf function is used to read formatted input from the console. Its syntax is:

#include <stdio.h>


int scanf(const char *format, ...);

Parameters:

  • format: A string that specifies the format of the input to be read.
  • ...: Addresses of variables where the input will be stored, typically passed using the & (address-of) operator.

Common Format Specifiers (similar to printf):

  • %d: Integer
  • %f: Floating-point number
  • %c: Character
  • %s: String

Example:

#include <stdio.h>


int main() {

    int age;

    float height;

    char name[20];


    printf("Enter your name: ");

    scanf("%s", name);

    printf("Enter your age: ");

    scanf("%d", &age);

    printf("Enter your height: ");

    scanf("%f", &height);


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

    return 0;

}

Sample Input:

Enter your name: Dr ahmed hamed
Enter your age: 40
Enter your height: 5.9

Output:
Name: Dr ahmed hamed, Age: 40, Height: 5.9

Summary

  • Use printf to display output to the user, formatting it according to your needs.
  • Use scanf to read input from the user, storing it in variables.

Both functions are essential for basic interaction in C programs.


Comments

Post a Comment

Popular posts from this blog