Post

Chapter 3: Variables, Data Types, and I/O

Learn about variables, data types, and input/output in C.

Chapter 3: Variables, Data Types, and I/O

Table of Contents

3.1 Variables in C

Variables are used to store data. In C, you must declare a variable before using it. Example:

1
2
int age;
double salary;

3.2 Data Types

C provides several basic data types:

  • int for integers
  • float for floating-point numbers
  • double for double-precision floating-point numbers
  • char for characters

Example:

1
2
3
int count = 10;
float price = 5.99;
char letter = 'A';

3.3 Input and Output

Use scanf for input and printf for output:

1
2
3
4
5
6
7
8
9
#include <stdio.h>

int main() {
    int number;
    printf("Enter a number: ");
    scanf("%d", &number);
    printf("You entered: %d\n", number);
    return 0;
}

3.4 Exercises

  1. Declare an integer variable and assign it a value.
  2. Write a program to read a float from the user and print it.
  3. What is the difference between float and double?

3.5 Solutions

3.5.1 Solution 1

1
int x = 5;

3.5.2 Solution 2

1
2
3
4
5
6
7
8
#include <stdio.h>
int main() {
    float f;
    printf("Enter a float: ");
    scanf("%f", &f);
    printf("You entered: %f\n", f);
    return 0;
}

3.5.3 Solution 3

float is single precision, double is double precision (more accurate, uses more memory).

3.6 What’s Coming in the Next Chapter

Next, you’ll learn about control flow in C: if, else, and loops!

Next Chapter → Control Flow – if, else, and Loops

This post is licensed under CC BY 4.0 by the author.