Chaining Assignments
int x, y, z;
x = y = z = 100; // z=100 first, then y=z, then x=y
Ternary operator OR Conditional operator
int age = 20;
// If age >= 18, result is "Adult", otherwise "Minor"
string status = (age >= 18) ? "Adult" : "Minor";
Nested Ternary Operators
int x = 10, y = 20, z = 30;
// Find the maximum of three numbers
int max = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
Expressions:
Total Price Calculator program:
#include <iostream>
using namespace std;
int main() {
// 1. Variables and Constants
const double TAX_RATE = 0.08; // 8% tax
double itemPrice = 100.0;
int quantity = 3;
// 2. Expression (Arithmetic)
double subtotal = itemPrice * quantity;
double taxAmount = subtotal * TAX_RATE;
double finalTotal = subtotal + taxAmount;
// 3. Relational/Logical Expression
bool isExpensive = (finalTotal > 250.0);
// 4. Output
cout << "Subtotal: " << subtotal << endl;
cout << "Tax: " << taxAmount << endl;
cout << "Total: " << finalTotal << endl;
cout << "Is this a luxury purchase? " << isExpensive << endl;
return 0;
}
Control Structures –
Selection Statements (Conditionals):
A. If-Else Statements
int score = 85;
if (score >= 90) {
cout << "Grade: A";
} else if (score >= 80) {
cout << "Grade: B"; // This will execute
} else {
cout << "Grade: C";
}
B. Switch Statement
#include <iostream>
using namespace std;
int main() {
int day;
cout << "Enter a day number (1-7): ";
cin >> day;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << "Invalid day number";
break; // Break is optional in the default case, as it's the end of the block
}
return 0;
}
A. For Loop
for (int i = 0; i < 5; i++) {
cout << "Count: " << i << " ";
}
Range-based for loop:
#include <iostream>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
for (int n : numbers) {
std::cout << n << " ";
}
return 0;
}
Pattern Printing
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << "\n";
}
The Solid Rectangle
for(int i = 1; i <= 4; i++) { // Rows
for(int j = 1; j <= 5; j++) { // Columns
cout << "* ";
}
cout << endl;
}
Right-Angled Triangle:
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
Inverted Right-Angled Triangle
for(int i = 5; i >= 1; i--) {
for(int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
The Pyramid (Equilateral)
int n = 5;
for(int i = 1; i <= n; i++) {
// Print Spaces
for(int j = 1; j <= n - i; j++) {
cout << " ";
}
// Print Stars
for(int k = 1; k <= i; k++) {
cout << "* ";
}
cout << endl;
}
Floyd's Triangle
A variation of the right-angled triangle where you print incrementing numbers instead of stars.
int count = 1;
for(int i = 1; i <= 4; i++) {
for(int j = 1; j <= i; j++) {
cout << count << " ";
count++;
}
cout << endl;
}
Output:
23
456
7 8 9 10