User Input in C

Understanding user input in C involves grasping the different functions available to read data from the user and how to properly handle various types of input. Here’s an in-depth look at handling user input in C.

  • Scanf() function :
  • The scanf function is used for reading formatted input. It reads data from the standard input stream stdin based on the format specifiers provided. Common format specifiers include %d for integers, %f for floats, %c for characters, and %s for strings.

  • syntax :
  • scanf(format, &variable);
    Example :
    int number;
    scanf("%d", &number);

  • Basic example of user input :
  • C Code
    #include <stdio.h> main() { int number; // Prompt the user to enter a number printf("Enter a number: "); // Read the number entered by the user scanf("%d", &number); // Display the number entered by the user printf("You entered: %d\n", number); }

    Output :
    Enter a number: 5
    You entered: 5

  • Problems & solutions :
  • C Code
    # Write a program to accept the marks of student in Physics, Chemistry and Biology. Display the total marks and average marks. #include<stdio.h> main() { float p,c,b,t,a; printf("Enter the marks in physics: "); scanf("%f",&p); printf("Enter the marks in chemistry : "); scanf("%f",&c); printf("Enter the marks in biology : "); scanf("%f",&b); t=p+c+b; a=(p+c+b)/3; printf("Total marks obtained=%f",t); printf("Average marks obtained=%f",a); }

    Output :
    Enter the marks in physics: 70
    Enter the marks in chemistry : 80
    Enter the marks in biology : 90
    Total marks obtained=240.000000
    Average marks obtained=80.000000

    C Code
    # Write a program to find area of Rhombus. #include<stdio.h> main() { int a,d1,d2; printf("Enter the value of d1 :"); scanf("%d",&d1); printf("Enter the value of d2 :"); scanf("%d",&d2); a=(d1*d2)/2; printf("Area=%d",a); }

    Output :
    Enter the value of d1 :8
    Enter the value of d2 :4
    Area=16

    C Code
    # Write a program to find the base area , surface area and volume of square pyramid. #include<stdio.h> main() { int B,S,V,b,s,h; printf("Enter the value of b:"); scanf("%d",&b); printf("Enter the value of s:"); scanf("%d",&s); printf("Enter the value of h:"); scanf("%d",&h); B=b*b; S=2*b*s+b*b; V=1/3*b*b*h; printf("Base area=%d",B); printf("Surface Area=%d",S); printf("Volume=%d",V); }

    Output :
    Enter the value of b:5
    Enter the value of s:10
    Enter the value of h:15
    Base area=25
    Surface Area=125
    Volume=125

  • Conclusion :
  • User input plays a crucial role in programming and software development by enabling interactivity, customization, flexibility, decision-making, data acquisition, error detection, collaboration, and innovation. Incorporating user input effectively enhances user experiences, drives user engagement, and contributes to the success of software products and services.