Think of data types as different kinds of containers. Just like you wouldn't store soup in a envelope or mail in a bowl, different types of data need different types of storage!
Using the right data type is like using the right tool for a job. You wouldn't use a hammer to cut paper or scissors to drive a nail!
Declaring a variable is like putting a label on a container before filling it.
// Declaration: Creating the container
int age; // Empty container for whole numbers
double price; // Empty container for decimals
char grade; // Empty container for single character
bool isPassed; // Empty container for true/false
string name; // Empty container for text
// Initialization: Filling the container
age = 21;
price = 49.99;
grade = 'A';
isPassed = true;
name = "Sarah";
// Declaration + Initialization: Create and fill at once
int score = 100;
double temperature = 98.6;
char initial = 'J';
bool isReady = false;
string city = "New York";
Each data type uses different amounts of computer memory, like different sized boxes in storage.
Sometimes you need to convert data from one type to another, like pouring water from a cup to a bottle.
Operators are like mathematical tools that work with your data.
The modulus operator gives you the remainder after division. It's like dividing cookies among friends and seeing how many are left over!
These are shortcuts for common operations, like speed dial on a phone!
int score = 10;
// Long way vs. Short way
score = score + 5; // Long way
score += 5; // Short way (same result!)
// All compound operators
score += 3; // score = score + 3
score -= 2; // score = score - 2
score *= 4; // score = score * 4
score /= 2; // score = score / 2
score %= 3; // score = score % 3
These operators add or subtract 1, perfect for counting!
These operators compare values and return true or false, like asking yes/no questions.
Logical operators let you combine multiple conditions, like asking "Do you have milk AND eggs?" or "Do you want coffee OR tea?"
Complete this calculator program that performs basic operations:
#include <iostream>
using namespace std;
int main() {
double num1, num2, result;
char operation;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter operation (+, -, *, /): ";
cin >> operation;
cout << "Enter second number: ";
cin >> num2;
// TODO: Complete the calculator logic
// Hint: Use if statements to check the operation
cout << "Result: " << result << endl;
return 0;
}
Use if statements to check which operation was entered, then perform the calculation.
if (operation == '+') {
result = num1 + num2;
} else if (operation == '-') {
result = num1 - num2;
} else if (operation == '*') {
result = num1 * num2;
} else if (operation == '/') {
if (num2 != 0) {
result = num1 / num2;
} else {
cout << "Error: Division by zero!" << endl;
return 1;
}
}
Create a program that:
#include <iostream>
using namespace std;
int main() {
double test1, test2, test3, average;
char grade;
bool passed;
// Your code here
return 0;
}