Bachelor of Science in Computer Science
Course ContentVariables
Habari Future Tech Star! Welcome to the World of Programming!
Ever used M-Pesa? Of course, you have! When you check your balance, the phone doesn't just guess the amount. It fetches a specific piece of information (your balance) stored somewhere. Think of your phone's contact list. You store a phone number under a person's name. In programming, we do the exact same thing! That 'name' you use to store information is what we call a variable. It's one of the most powerful ideas in programming, so let's dive in. Twende kazi!
So, What Exactly is a Variable?
Imagine you have a sanduku (a box). You can put things inside this box. To remember what's inside without opening it, you stick a label on it, right? Maybe you label it "My KCSE Certificates" or "University Textbooks".
In programming, a variable is exactly like that labeled box. It is a named storage location in the computer's memory that holds a piece of data. The label is the variable's name, and the item inside is its value.
Here’s a simple visual:
+-----------------+
| |
| Value | <--- The data, like the number 21, or your name "Kamau".
| (e.g. 21) |
| |
+-----------------+
^
|
variableName (e.g. studentAge) <--- The label on the box.
The best part? The value inside the box can change (it can vary), which is why we call it a variable! Your M-Pesa balance changes, your age changes every year, and the score in a game changes. Variables allow our programs to be dynamic and useful.
The Different Types of "Boxes": Data Types
You wouldn't store soup in a paper bag, would you? You need the right container for the right item. Similarly, in C/C++, you must tell the computer what type of data a variable will hold. This is called a data type.
Here are the most common ones you'll use every day:
- int: Used for integers (whole numbers).
Example: The number of counties in Kenya (47), your age, or the price of a bottle of soda in shillings. - double or float: Used for numbers with decimal points.
Example: Your exam score (like 85.5), the price of fuel (e.g., 195.50 Ksh), or your M-Pesa balance. - char: Used for a single character, letter, or symbol. Always enclosed in single quotes (' ').
Example: Your grade in a unit ('A'), a gender initial ('M' or 'F'). - string: Used for a sequence of characters, like a word or sentence. (In C++, you use `std::string`; in C, it's a bit different, but the idea is the same). Always in double quotes (" ").
Example: Your name ("Akinyi"), your university ("Strathmore University"). - bool: Used for true or false values. Very important for making decisions!
Example: `isKenyan = true;`, `hasCompletedAssignment = false;`.
Creating and Using Variables in C++ (The Fun Part!)
Let's get our hands dirty with some code. Creating a variable has two main steps:
- Declaration: You announce that you need a box and give it a name and type. You tell the computer to reserve some memory space.
- Initialization: You put something inside the box for the first time.
You can do these in two steps or all at once. Sawa?
#include <iostream>
#include <string> // Needed for using strings
int main() {
// --- DECLARATION and INITIALIZATION in one step ---
// An integer for a student's age
int studentAge = 20;
// A double for an M-Pesa balance
double mpesaBalance = 550.75;
// A character for a final grade
char finalGrade = 'A';
// A string for a student's name
std::string studentName = "Wanjiku";
// A boolean to check if the student is registered
bool isRegistered = true;
// --- Now, let's USE these variables! ---
// We use 'std::cout' to print to the screen.
std::cout << "Student Name: " << studentName << std::endl;
std::cout << "Age: " << studentAge << std::endl;
std::cout << "Current M-Pesa Balance: Ksh " << mpesaBalance << std::endl;
std::cout << "Final Grade in Intro to Programming: " << finalGrade << std::endl;
return 0;
}
Strong Naming Rules: Just like you have a unique admission number, your variables need good names!
- Names can contain letters, numbers, and underscores (_).
- They cannot start with a number. `1student` is wrong, but `student1` is fine.
- They cannot have spaces. Use `studentName` (camelCase) or `student_name` (snake_case).
- Names are case-sensitive! `age` and `Age` are two different variables.
Let's Do Some Mahesabu (Calculations)
Variables are fantastic for math. Imagine you are at the campus tuckshop (duka). You buy two mandazis and a soda.
You buy 2 mandazis at 15 Ksh each. You buy 1 soda at 50 Ksh. What is the total cost?
Let's model this with code:
int priceOfMandazi = 15; int numberOfMandazis = 2; int priceOfSoda = 50; int totalCost; // We declare a variable to hold the result // Now, we do the calculation and store the result in our variable totalCost = (priceOfMandazi * numberOfMandazis) + priceOfSoda; // Let's print the result std::cout << "The total cost is: Ksh " << totalCost << std::endl; // Expected Output: The total cost is: Ksh 80
Real-World Scenario: A Simple M-Pesa Transaction
Let's say your starting M-Pesa balance is 1500 Ksh. You need to send your friend, Kamau, 200 Ksh. The transaction cost for this is 12 Ksh. What is your new balance?
This is a perfect job for variables! We can map out the whole process.
// Initial state double currentBalance = 1500.00; double amountToSend = 200.00; int transactionCost = 12; // We calculate the new balance double newBalance = currentBalance - amountToSend - transactionCost; // Display the result std::cout << "Initial Balance: Ksh " << currentBalance << std::endl; std::cout << "Amount Sent: Ksh " << amountToSend << std::endl; std::cout << "Transaction Cost: Ksh " << transactionCost << std::endl; std::cout << "-------------------------" << std::endl; std::cout << "Your new M-Pesa balance is: Ksh " << newBalance << std::endl;
See? By using variables like currentBalance and amountToSend, we've created a small piece of a real-world application. Iko Sawa?
Finally, The Unchanging Variable: Constants
Sometimes, you have a value that should NEVER change in your program. For example, the number of counties in Kenya is always 47. Or the value of Pi (π) is always approximately 3.14159.
To lock a variable and make it unchangeable, we use the const keyword.
const int KENYAN_COUNTIES = 47; const double PI = 3.14159; // If you try to change it later, the compiler will give you an error! // KENYAN_COUNTIES = 48; // ERROR! This is not allowed.
This is great for safety and making your code clear to others.
Congratulations! You've just mastered one of the most essential building blocks of programming. You now know how to create, label, and use storage boxes in your code to hold all kinds of information. You've got this!
Next up: We will learn how to ask the user for information (like their name or age) and store it in these variables using std::cin. Get ready!
Pro Tip
Take your own short notes while going through the topics.