User Input in C — PBA Institute Tutorial
Chapter 02 · C Programming Series
10 min read Beginner

User Input in C

Understanding user input in C involves learning different functions used to accept data from users. The scanf() function is the most commonly used input function in C programming.

scanf() Function

The scanf() function is used to take formatted input from the user. It reads data from the keyboard and stores it into variables.

Syntax
scanf("format_specifier", &variable_name);
  • %d → Integer
  • %f → Float
  • %c → Character
  • %s → String

Basic Example of User Input

C Program
#include<stdio.h>

main()
{
    int number;

    printf("Enter a number: ");
    scanf("%d",&number);

    printf("You entered: %d",number);
}
Output Enter a number: 5
You entered: 5

Problems & Solutions

Program 1 — Total Marks & Average
#include<stdio.h>

main()
{
    float p,c,b,total,avg;

    printf("Enter Physics marks: ");
    scanf("%f",&p);

    printf("Enter Chemistry marks: ");
    scanf("%f",&c);

    printf("Enter Biology marks: ");
    scanf("%f",&b);

    total = p+c+b;
    avg = total/3;

    printf("Total Marks = %f\n",total);
    printf("Average Marks = %f",avg);
}
Output Enter Physics marks: 70
Enter Chemistry marks: 80
Enter Biology marks: 90
Total Marks = 240.000000
Average Marks = 80.000000
Program 2 — Area of Rhombus
#include<stdio.h>

main()
{
    int d1,d2,area;

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

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

    area = (d1*d2)/2;

    printf("Area = %d",area);
}
Output Enter d1: 8
Enter d2: 4
Area = 16
Program 3 — Area & Circumference of Circle
#include<stdio.h>

main()
{
    float r,area,c;

    printf("Enter radius: ");
    scanf("%f",&r);

    area = 3.14*r*r;
    c = 2*3.14*r;

    printf("Area = %f\n",area);
    printf("Circumference = %f",c);
}
Output Enter radius: 7
Area = 153.860001
Circumference = 43.959999
Program 4 — Swap Two Numbers
#include<stdio.h>

main()
{
    int a,b,temp;

    printf("Enter first number: ");
    scanf("%d",&a);

    printf("Enter second number: ");
    scanf("%d",&b);

    temp = a;
    a = b;
    b = temp;

    printf("After swapping:\n");
    printf("a = %d\n",a);
    printf("b = %d",b);
}
Output Enter first number: 10
Enter second number: 20
After swapping:
a = 20
b = 10
Program 5 — Even or Odd
#include<stdio.h>

main()
{
    int n;

    printf("Enter a number: ");
    scanf("%d",&n);

    if(n%2==0)
    {
        printf("Even Number");
    }
    else
    {
        printf("Odd Number");
    }
}
Output Enter a number: 7
Odd Number

Conclusion

User Input is one of the most important concepts in C programming because it allows programs to interact with users. By using functions like scanf(), developers can create dynamic and interactive applications.