Variables
beginnerPart of C Fundamentals
Theory
C is a statically typed language — every variable must be declared with its type before use. The type determines how much memory is allocated and what operations are allowed.
Basic data types:
int— integer (typically 4 bytes, range -2^31 to 2^31-1)float— single-precision floating-point (4 bytes)double— double-precision floating-point (8 bytes)char— single character (1 byte, stores ASCII value)
Modifiers alter the range or size: short, long, unsigned, signed.
unsigned int positive = 100;
long big_number = 1000000;
short small = 10;Variable declaration and initialization:
int age; // declaration
age = 25; // initialization
int count = 0; // declaration + initializationConstants are values that cannot change:
constkeyword:const int DAYS = 7;#definepreprocessor:#define PI 3.14159
The sizeof operator returns the size of a type or variable in bytes.
Format specifiers are used with printf() and scanf():
%d— int%f— float%lf— double%c— char%s— string (char array)%u— unsigned int%ld— long int
printf() prints formatted output. scanf() reads formatted input from the keyboard. scanf requires the addresses of variables (using &).
Type conversion happens when different types are mixed:
- Implicit conversion (automatic):
int+float→ float - Explicit conversion (casting):
(float)int_var
Type casting syntax: (type)value
int a = 5;
int b = 2;
float result = (float)a / b; // 2.5, not 2Practical Examples
Exercises
Rectangle Calculator
Write a C program that declares variables for length and width of a rectangle (use float). Calculate and print the area and perimeter. Use const for a variable that won't change.
Starter Code:
#include <stdio.h>\n\nint main() {\n float length = 5.5;\n float width = 3.2;\n // Calculate area and perimeter\n return 0;\n}Expected Output:
Rectangle: 5.50 x 3.20\nArea: 17.60\nPerimeter: 17.40User Input Calculator
Write a program that asks the user for two integers using scanf(), then prints their sum, difference, product, and quotient (as a float using casting).
Starter Code:
#include <stdio.h>\n\nint main() {\n int a, b;\n // Your code here\n return 0;\n}Expected Output:
Enter first number: 15\nEnter second number: 4\nSum: 19\nDifference: 11\nProduct: 60\nQuotient: 3.75ASCII Art Generator
Write a program that takes a character from the user using scanf() and prints a pattern using that character. Print the character's ASCII value as an integer.
Expected Output:
Enter a character: #\nASCII value: 35\nPattern:\n #\n ###\n#####Mini Quiz
Mini Quiz
Mini Project
Mini Project: Temperature Conversion Tool
Create a C program that converts temperatures between Celsius and Fahrenheit. Use different data types and demonstrate type casting.
Requirements:
Bonus Challenge
Add support for Kelvin conversion and display all three scales.