C Tutorial menu

C Variables, Data Types and Input

Variables store values, such as a price, an age or a grade, so your program can use them.

Declaring Variables

In C you must give every variable a type before you use it:

Example

c
#include <stdio.h>

int main(void) {
  int age = 19;
  float height = 5.8;
  char grade = 'A';

  printf("Age: %d\n", age);
  printf("Height: %.1f feet\n", height);
  printf("Grade: %c\n", grade);
  return 0;
}
Output
Age: 19
Height: 5.8 feet
Grade: A

You can also declare first and give a value later:

Example

c
int marks;
marks = 88;

Basic Data Types

TypeStoresSize (usually)Format specifier
intWhole numbers4 bytes%d
floatDecimal numbers (about 6 digits)4 bytes%f
doubleDecimal numbers (about 15 digits)8 bytes%lf for scanf, %f for printf
charOne character1 byte%c

Use %s to print a string (text), and %.2f to print a decimal number with exactly 2 digits after the point.

Printing Decimal Numbers

By default %f shows six digits after the point. Control it with a precision:

Example

c
#include <stdio.h>

int main(void) {
  double price = 149.5;
  printf("%f\n", price);
  printf("%.2f\n", price);
  printf("%.0f\n", price);
  return 0;
}
Output
149.500000
149.50
150

Naming Rules

  • Use letters, digits and _, but do not start with a digit
  • Names are case sensitive: total and Total are different
  • Keywords like int, return or while cannot be names
  • Pick clear names: studentCount is better than sc

Constants

A constant cannot be changed after it is set. Use const, or #define for a fixed value the compiler swaps in:

Example

c
#define PI 3.14159
const int MAX_STUDENTS = 40;

Writing constant names in CAPITAL letters is a common habit. It tells other programmers the value never changes.

Type Conversion

When you divide two int values, C drops the decimal part. Cast one value to double to get the exact result:

Example

c
#include <stdio.h>

int main(void) {
  int total = 7;
  int people = 2;
  printf("%d\n", total / people);
  printf("%.1f\n", (double) total / people);
  return 0;
}
Output
3
3.5

Reading Input with scanf

scanf reads a value typed by the user. Put & before the variable name so scanf knows where to store the value:

Example

c
#include <stdio.h>

int main(void) {
  int age;
  printf("Enter your age: ");
  scanf("%d", &age);
  printf("Next year you will be %d\n", age + 1);
  return 0;
}
Output
Enter your age: 20
Next year you will be 21

Here the user typed 20.

Exercise

Exercise

Which format specifier prints a single character?

Learn C with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp