(Learn C Programming for Beginners — Day 3)
Welcome back to your 30-Day C Programming Adventure! 🚀
Yesterday, you wrote your very first "Hello, World!" program. You felt the power of making the computer speak. Today, we’re going to give your programs a memory.
Imagine trying to cook a complex meal without any bowls or containers. You’d have ingredients everywhere! In programming, variables are those containers. They hold your data so you can use, change, and display it.
Today, we unlock the power of Variables, Data Types, and Constants. By the end of this post, you'll be able to write programs that can store and manipulate information, not just print static text.
🎯 Goals for Today
- Understand Variables — What they are and how to create them.
- Master Data Types — Integers, floats, characters, and more.
- Learn Constants — Values that never change.
- Write Code — Create a program that stores and prints different types of data.
📦 What is a Variable?
A variable is simply a named storage location in your computer's memory. Think of it like a labeled box.
- The Label: The variable's name (e.g.,
age,score,initial). - The Content: The value stored inside (e.g.,
25,98.5,'A').
In C, you must declare a variable before you use it. This tells the compiler, "Hey, I need a box named score that can hold a whole number."
Syntax for Declaring a Variable:
data_type variable_name;
Or, you can declare and assign a value at the same time (initialization):
data_type variable_name = value;
🏗️ The Building Blocks: Data Types in C
C is a statically typed language. This means you have to tell the computer exactly what kind of data you plan to store in your variable. You can't put soup in a colander, and you can't put a decimal number in an integer variable (without losing data!).
Here are the fundamental data types you'll use 90% of the time:
1. int (Integer)
Used for whole numbers (no decimal points).
* Examples: 10, -5, 42, 0
* Size: Usually 4 bytes.
* Format Specifier: %d
int age = 25;
int year = 2025;
2. float (Floating Point)
Used for numbers with decimal points. Good for precision up to about 6-7 decimal places.
* Examples: 3.14, 99.99, -0.005
* Size: Usually 4 bytes.
* Format Specifier: %f
float pi = 3.14;
float price = 19.99;
3. double (Double Precision Float)
Used for more precise decimal numbers. It holds double the precision of a float.
* Examples: 3.1415926535, 123456.789
* Size: Usually 8 bytes.
* Format Specifier: %lf (long float)
double atomWidth = 0.0000000012;
4. char (Character)
Used for a single character (letter, number, or symbol). Must be enclosed in single quotes.
* Examples: 'A', 'z', '7', '!'
* Size: 1 byte.
* Format Specifier: %c
char grade = 'A';
char initial = 'S';
🔒 Constants: The Unchangeable Values
Sometimes, you have values that should never change during the execution of your program—like the value of Pi, or the maximum score in a game. These are called constants.
You can define a constant using the const keyword:
const float PI = 3.14159;
const int MAX_LIVES = 3;
If you try to change MAX_LIVES later in your code (e.g., MAX_LIVES = 4;), the compiler will throw an error. This is a great safety feature!
💻 Let's Code: Putting It All Together
Let's write a program that uses all these concepts. We'll create a "Profile Printer" that stores information about a fictional character and prints it out.
Step 1: Open VS Code and create a new file named day3_variables.c.
Step 2: Type the following code:
#include <stdio.h>
int main() {
// 1. Declare and Initialize Variables
int age = 30;
float height = 5.9;
char initial = 'J';
double bankBalance = 12345.6789;
// 2. Declare a Constant
const int LUCKY_NUMBER = 7;
// 3. Print the values
printf("--- Character Profile ---\n");
printf("Initial: %c\n", initial);
printf("Age: %d years old\n", age);
printf("Height: %.1f feet\n", height); // %.1f prints only 1 decimal place
printf("Bank Balance: $%.2lf\n", bankBalance); // %.2lf prints 2 decimal places
printf("Lucky Number: %d\n", LUCKY_NUMBER);
return 0;
}
Step 3: Save, Compile, and Run!
* Compile: gcc day3_variables.c -o day3_variables
* Run (Windows): day3_variables
* Run (Mac/Linux): ./day3_variables
🔍 Code Breakdown:
%c,%d,%f: These are format specifiers. They act as placeholders. Whenprintfsees%d, it looks for the corresponding integer variable after the comma and swaps them.%.1f: This tells C to print a float but round it to 1 decimal place. Neat, right?
🧠 Variable Naming Rules (The "Do's and Don'ts")
You can't just name a variable anything. C has rules:
1. Must start with a letter (a-z, A-Z) or an underscore (_).
2. Cannot start with a number. (1stPlace is illegal!)
3. Can contain letters, numbers, and underscores.
4. Case-sensitive: age, Age, and AGE are three different variables.
5. No keywords: You can't name a variable int, return, or float.
Best Practice: Use meaningful names like studentAge or totalScore instead of x or y. It makes your code readable!
📝 Day 3 Summary
- Variables are named containers for data.
- Data Types (
int,float,double,char) define what kind of data a variable can hold. - Constants (
const) are variables that cannot be changed. - Format Specifiers (
%d,%f,%c) are used to print variable values.
🚀 Challenge for Tomorrow
Try modifying the code above!
1. Change the age and initial to your own.
2. Create a new variable called isHappy (hint: C doesn't have a native boolean type in the old standard, but you can use int where 1 is true and 0 is false, or include <stdbool.h>).
3. Try to print it!
Next Up: Day 4: Input/Output — We'll learn how to make your programs interactive by taking input from the user!
Found this helpful? Clap 👏 and follow to keep up with the adventure!
Comments
Post a Comment