C++ Fundamentals: Variable Swapping and Syntax Comments
Exchanging Variable Values
Directly assigning one variible to another overwrites the original data, preventing recovery of the initial value. To successfully interchange contents between two storage locations, a temporary buffer is necessary.
Consider this implementation using standard integer types:
#include <iostream>
using namespace std;
int main() {
int valOne = 15;
int valTwo = 25;
cout << "Before swap: One=" << valOne << ", Two=" << valTwo << endl;
// Use a third variable to hold intermediate data
int tempStorage = valOne;
valOne = valTwo;
valTwo = tempStorage;
cout << "After swap: One=" << valOne << ", Two=" << valTwo << endl;
return 0;
}
Commenting Syntax
Comments allow developers to documetn logic without impacting the execution flow.
Single-Line Comments
Start with //. The compiler ignores all text following this marker on the same line.
int count = 0; // Initialize counter
Multi-Line Comments
Enclose text blocks between /* and */ to ignore multiple lines at once.
/*
Explanation for complex logic
spanning several lines
*/
Practice Exercises
Exercise 1: Output Input
Acccept a single integer from standard input and display it.
#include <iostream>
using namespace std;
int main() {
int inputNumber;
cin >> inputNumber;
cout << inputNumber;
return 0;
}
Exercise 2: Selective Printing
Read three distinct integers and output only the middle value.
#include <iostream>
using namespace std;
int main() {
int first, second, third;
cin >> first >> second >> third;
cout << second;
return 0;
}
Exercise 3: Sequence Generation
Input a base number and print the value plus zero, then plus an increment, repeated twice.
#include <iostream>
using namespace std;
int main() {
int baseValue;
int increment = 25;
cin >> baseValue;
cout << baseValue << " ";
cout << baseValue + increment << " ";
cout << baseValue + increment + increment;
return 0;
}