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
#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;
}Age: 19 Height: 5.8 feet Grade: A
You can also declare first and give a value later:
Example
int marks;
marks = 88;Basic Data Types
| Type | Stores | Size (usually) | Format specifier |
|---|---|---|---|
int | Whole numbers | 4 bytes | %d |
float | Decimal numbers (about 6 digits) | 4 bytes | %f |
double | Decimal numbers (about 15 digits) | 8 bytes | %lf for scanf, %f for printf |
char | One character | 1 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
#include <stdio.h>
int main(void) {
double price = 149.5;
printf("%f\n", price);
printf("%.2f\n", price);
printf("%.0f\n", price);
return 0;
}149.500000 149.50 150
Naming Rules
- Use letters, digits and
_, but do not start with a digit - Names are case sensitive:
totalandTotalare different - Keywords like
int,returnorwhilecannot be names - Pick clear names:
studentCountis better thansc
Constants
A constant cannot be changed after it is set. Use const, or #define for a fixed value the compiler swaps in:
Example
#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
#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;
}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
#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;
}Enter your age: 20 Next year you will be 21
Here the user typed 20.
Exercise
Exercise
Which format specifier prints a single character?
