Skip to main content
Advertisement

C Language - Variables and Data Types

1. Variables and Constants

In C, a variable is a named location in memory and must be declared with a specific data type.

int age = 20; // Declaration and initialization
age = 21; // Value can be changed

const float PI = 3.14159f; // Constant declaration
// PI = 3.14; // Compilation error

2. Primitive Data Types

  • int: Integer (typically 4 bytes, format specifier: %d)
  • float: Single-precision floating-point (4 bytes, format specifier: %f)
  • double: Double-precision floating-point (8 bytes, format specifier: %lf)
  • char: Character (1 byte, format specifier: %c)
  • void: A keyword indicating the absence of a type

3. Conditional Statements (If, Switch)

int score = 85;

if (score >= 90) {
printf("Grade A\n");
} else if (score >= 80) {
printf("Grade B\n");
} else {
printf("Grade C or lower\n");
}

int choice = 2;
switch (choice) {
case 1:
printf("Option 1 chosen\n");
break;
case 2:
printf("Option 2 chosen\n");
break;
default:
printf("Default option\n");
}

4. Loops (For, While)

for (int i = 0; i < 5; i++) {
printf("Iteration %d\n", i);
}

int j = 0;
while (j < 3) {
printf("While %d\n", j);
j++;
}
Advertisement