This is the multi-page printable view of this section. Click here to print.
C++
- Local Network Scanner C++
- Single dimension vector operations in C++
- Switch & Case statement in C++
- Bitwise operators in C++
- logical AND (&&) and OR (||) operators in C++
- Count even and odd numbers with while loop in C++
- for loop with examples in C++
- do while loop with examples in C++
- while loop with examples in C++
- Short long and unsigned modifiers in C++
- Calculate square root of an integer with cmath library in C++
- User input with cin function in C++
- Converting types with static_cast in C++
- How to print an integer in different number systems: hexadecimal, decimal, and octal?
- The use of basic comparison operators in C++
- Char type and usage examples in C++
- Shortcut operators in C++
- The usage of pre-increment and post-increment operators
- Simple demonstration of operator precedence and type casting in C++
- Arithmetic and Logical operators in C++
- float type and its usage in C++
- Comment types in C++
- What are the keywords in C++
- Common data types in C++
- Create variables and assign values to them in C++
- Correct and incorrect variable naming conventions in C++
- The use of octal, binary and hexadecimal literals in C++
- C++ int variable with different defining ways
- C++ Hello World with explanaition
- C++ Defining a Pointer and changing its value
- Factorial calculation with C++ do-while loop
- C++ Example calculating the factorial of the entered number
- C++ adding int and float variables
- C++ Code example to convert Fahrenheit temperature to Celsius
- Printing int, float and string values with printf in C++
- C++ 2 string variable concatenation
- Combining 2 variables of type char in C++
- Finding whether a number is positive or negative with C++
- C++ Nested if statement
- C++ Cascade if else statement
- C++ if else statement
Local Network Scanner C++
If you want to scan your own network to find out live IP addresses, you can use the code below. Use this code with caution, use it only with the network you own.
To compile and run this program:
Save the updated code to a file, e.g., network_scanner.cpp
Compile it:
`g++ -std=c++17 -o network_scanner network_scanner.cpp`
Run it with sudo:
sudo ./network_scanner
Here is the complete code.
#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <array>
#include <chrono>
#include <thread>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
constexpr size_t PACKET_SIZE = 64;
constexpr std::chrono::seconds MAX_WAIT_TIME(1);
class NetworkScanner {
private:
static uint16_t calculateChecksum(uint16_t *buf, int len) {
uint32_t sum = 0;
while (len > 1) {
sum += *buf++;
len -= 2;
}
if (len == 1) {
sum += *reinterpret_cast<uint8_t *>(buf);
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
return static_cast<uint16_t>(~sum);
}
static int ping(const std::string& ip_addr) {
int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd < 0) {
throw std::runtime_error("Socket creation failed");
}
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip_addr.c_str());
std::array<char, PACKET_SIZE> packet{};
auto* icmp_header = reinterpret_cast<struct icmp*>(packet.data());
icmp_header->icmp_type = ICMP_ECHO;
icmp_header->icmp_code = 0;
icmp_header->icmp_id = getpid();
icmp_header->icmp_seq = 0;
icmp_header->icmp_cksum = 0;
icmp_header->icmp_cksum = calculateChecksum(reinterpret_cast<uint16_t*>(icmp_header), PACKET_SIZE);
timeval tv{};
tv.tv_sec = MAX_WAIT_TIME.count();
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
if (sendto(sockfd, packet.data(), PACKET_SIZE, 0, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) <= 0) {
close(sockfd);
return -1;
}
if (recvfrom(sockfd, packet.data(), packet.size(), 0, nullptr, nullptr) <= 0) {
close(sockfd);
return -1;
}
close(sockfd);
return 0;
}
public:
static void scanNetwork(const std::string& base_ip) {
std::ofstream file("scan_results.txt");
if (!file) {
throw std::runtime_error("Error opening file");
}
for (int i = 1; i <= 254; ++i) {
std::string ip = base_ip + std::to_string(i);
std::cout << "Pinging " << ip << "... ";
try {
if (ping(ip) == 0) {
std::cout << ip << " is reachable ";
file << ip << ' ';
} else {
std::cout << ip << " is not reachable ";
}
} catch (const std::exception& e) {
std::cerr << "Error pinging " << ip << ": " << e.what() << ' ';
}
// Add a small delay between pings to avoid overwhelming the network
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << "Scan complete. Results saved in scan_results.txt ";
}
};
int main() {
try {
NetworkScanner::scanNetwork("192.168.1.");
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << ' ';
return 1;
}
return 0;
}
Single dimension vector operations in C++
The provided code demonstrates various operations on a std::vector
in C++.
Code
#include <iostream>
#include <vector>
using namespace std;
/**
* \brief Main function demonstrating various vector operations.
*
* This function performs the following operations on a vector:
* - Initializes a vector with 5 elements.
* - Fills the vector with numbers from 0 to 4.
* - Adds and removes elements from the end of the vector.
* - Inserts and removes elements at the beginning and specific positions.
* - Clears the vector and prints its contents.
*
* \return int Exit status of the program.
*/
int main() {
vector<int> numbers(5);
cout << "Initial vector elements: " << endl;
// Fill the vector with numbers
for (int i = 0; i < numbers.size(); i++) {
numbers[i] = i;
cout << numbers[i] << endl;
}
cout << "-------------------" << endl;
// Add a number to the end of the vector
numbers.push_back(5);
cout << "5 added as the last element: " << numbers.back() << endl;
for (const int number : numbers) {
cout << number << endl;
}
cout << "-------------------" << endl;
// Remove the last number from the vector
numbers.pop_back();
cout << "5 removed, now the last element is: " << numbers[numbers.size() - 1] << endl;
for (const int number : numbers) {
cout << number << endl;
}
cout << "-------------------" << endl;
// Insert a number at the beginning of the vector
numbers.insert(numbers.begin(), 10);
cout << "10 added as front number. Now the front number of the vector is: " << numbers.front() << endl;
for (const int number : numbers) {
cout << number << endl;
}
cout << "-------------------" << endl;
// Remove the first number from the vector
numbers.erase(numbers.begin());
cout << "Front number removed. The new front is: " << numbers.front() << endl;
for (const int number : numbers) {
cout << number << endl;
}
cout << "-------------------" << endl;
// Insert a number at the 3rd position of the vector
numbers.insert(numbers.begin() + 2, 20);
cout << "20 added to the 3rd position: " << numbers[2] << endl;
for (const int number : numbers) {
cout << number << endl;
}
cout << "-------------------" << endl;
// Remove the number at the 3rd position of the vector
numbers.erase(numbers.begin() + 2);
cout << "20 removed from the 3rd position: " << numbers[2] << endl;
for (const int number : numbers) {
cout << number << endl;
}
cout << "-------------------" << endl;
// Clear the vector
numbers.clear();
cout << "Numbers in the vector after clearing: " << endl;
for (const int number : numbers) {
cout << number << endl;
}
cout << "-------------------" << endl;
return 0;
}
Explanation
The provided code demonstrates various operations on a std::vector
in C++. The main
function begins by initializing a vector named numbers
with 5 elements and then fills it with numbers from 0 to 4 using a for
loop:
vector<int> numbers(5);
for (int i = 0; i < numbers.size(); i++) {
numbers[i] = i;
cout << numbers[i] << endl;
}
Next, the code adds an element to the end of the vector using push_back
and prints the last element:
numbers.push_back(5);
cout << "5 added as the last element: " << numbers.back() << endl;
The last element is then removed using pop_back
, and the code prints the new last element:
numbers.pop_back();
cout << "5 removed, now the last element is: " << numbers[numbers.size() - 1] << endl;
The code proceeds to insert an element at the beginning of the vector using insert
and prints the first element:
numbers.insert(numbers.begin(), 10);
cout << "10 added as front number. Now the front number of the vector is: " << numbers.front() << endl;
The first element is then removed using erase
, and the new first element is printed:
numbers.erase(numbers.begin());
cout << "Front number removed. The new front is: " << numbers.front() << endl;
An element is inserted at the third position, and the element at that position is printed:
numbers.insert(numbers.begin() + 2, 20);
cout << "20 added to the 3rd position: " << numbers[2] << endl;
The element at the third position is removed, and the new element at that position is printed:
numbers.erase(numbers.begin() + 2);
cout << "20 removed from the 3rd position: " << numbers[2] << endl;
Finally, the vector is cleared using clear
, and the code prints the contents of the now-empty vector:
numbers.clear();
cout << "Numbers in the vector after clearing: " << endl;
for (const int number : numbers) {
cout << number << endl;
}
This code effectively demonstrates how to manipulate a std::vector
in C++ by adding, removing, and accessing elements at various positions.
Output
Initial vector elements:
0
1
2
3
4
-------------------
5 added as the last element: 5
0
1
2
3
4
5
-------------------
5 removed, now the last element is: 4
0
1
2
3
4
-------------------
10 added as front number. Now the front number of the vector is: 10
10
0
1
2
3
4
-------------------
Front number removed. The new front is: 0
0
1
2
3
4
-------------------
20 added to the 3rd position: 20
0
1
20
2
3
4
-------------------
20 removed from the 3rd position: 2
0
1
2
3
4
-------------------
Numbers in the vector after clearing:
-------------------
Process finished with exit code 0```
## Extra information
Common operations performed on `std::vector` in C++ include:
* **Initialization**:
```cpp
std::vector<int> vec; // Empty vector
std::vector<int> vec(5); // Vector with 5 default-initialized elements
std::vector<int> vec = {1, 2, 3, 4, 5}; // Vector initialized with a list of elements
- Accessing Elements:
int first = vec.front(); // Access the first element
int last = vec.back(); // Access the last element
int element = vec[2]; // Access the element at index 2```
* **Modifying Elements**:
```cpp
vec[2] = 10; // Modify the element at index 2```
* **Adding Elements**:
```cpp
vec.push_back(6); // Add an element to the end
vec.insert(vec.begin(), 0); // Insert an element at the beginning
vec.insert(vec.begin() + 2, 15); // Insert an element at index 2```
* **Removing Elements**:
```cpp
vec.pop_back(); // Remove the last element
vec.erase(vec.begin()); // Remove the first element
vec.erase(vec.begin() + 2); // Remove the element at index 2
vec.clear(); // Remove all elements
- Iterating Over Elements:
for (int i = 0; i < vec.size(); ++i) {
std::cout << vec[i] << std::endl;
}
for (int elem : vec) {
std::cout << elem << std::endl;
}
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << std::endl;
}
- Size and Capacity:
size_t size = vec.size(); // Get the number of elements
size_t capacity = vec.capacity(); // Get the capacity of the vector
bool isEmpty = vec.empty(); // Check if the vector is empty
vec.reserve(10); // Reserve space for at least 10 elements
- Swapping and Assigning:
std::vector<int> vec2 = {7, 8, 9};
vec.swap(vec2); // Swap contents with another vector
vec = vec2; // Assign contents from another vector```
These operations cover the most common use cases for `std::vector` in C++.
Switch & Case statement in C++
The provided C++ code demonstrates the use of a switch-case
statement to handle different user inputs.
Code
#include <iostream>
using namespace std;
/**
* \brief Main function demonstrating the use of switch-case statement in C++.
*
* This program prompts the user to enter a number and then uses a switch-case
* statement to print the corresponding word for numbers 1 to 5. For numbers 6
* and 7, it prints "Six or Seven". For any other number, it prints "Invalid number".
*
* \return int Returns 0 upon successful execution.
*/
int main() {
int number; ///< Variable to store the user input number.
cout << "Enter a number between 1-7: ";
cin >> number;
switch (number) {
case 1:
cout << "One" << endl; ///< Prints "One" if the number is 1.
break;
case 2:
cout << "Two" << endl; ///< Prints "Two" if the number is 2.
break;
case 3:
cout << "Three" << endl; ///< Prints "Three" if the number is 3.
break;
case 4:
cout << "Four" << endl; ///< Prints "Four" if the number is 4.
break;
case 5:
cout << "Five" << endl; ///< Prints "Five" if the number is 5.
break;
case 6:
case 7:
cout << "Six or Seven" << endl; ///< Prints "Six or Seven" if the number is 6 or 7.
break;
default:
cout << "Invalid number" << endl; ///< Prints "Invalid number" for any other number.
}
return 0;
}
Explanation
The provided C++ code demonstrates the use of a switch-case
statement to handle different user inputs. The program begins by including the necessary header file <iostream>
and using the std
namespace to simplify the code.
#include <iostream>
using namespace std;
The main
function is the entry point of the program. It starts by declaring an integer variable number
to store the user’s input.
int main() {
int number;
cout << "Enter a number between 1-7: ";
cin >> number;
The program then uses a switch-case
statement to determine the output based on the value of number
. Each case
corresponds to a specific number, and the program prints the corresponding word for numbers 1 to 5. For example, if the user inputs 1
, the program prints “One”.
switch (number) {
case 1:
cout << "One" << endl;
break;
case 2:
cout << "Two" << endl;
break;
// ... other cases
}
For the numbers 6
and 7
, the program prints “Six or Seven”. This is achieved by grouping these cases together without a break
statement between them.
case 6:
case 7:
cout << "Six or Seven" << endl;
break;
If the user inputs any number outside the range of 1 to 7, the default
case is executed, and the program prints “Invalid number”.
default:
cout << "Invalid number" << endl;
}
Finally, the main
function returns 0
to indicate successful execution.
return 0;
}
This code effectively demonstrates how to use a switch-case
statement in C++ to handle multiple conditions based on user input.
Output
Enter a number between 1-7: 3
Three
Process finished with exit code 0```
Bitwise operators in C++
The provided C++ code demonstrates the use of various bitwise operators.
Code
#include <iostream>
using namespace std;
/**
* Demonstrates the use of bitwise operators in C++.
*
* Bitwise operators used:
* - & (AND)
* - | (OR)
* - ^ (XOR)
* - ~ (NOT)
* - << (LEFT SHIFT)
* - >> (RIGHT SHIFT)
*
* The program performs bitwise operations on two integers and prints the results.
*
* @return int Exit status of the program.
*/
int main() {
int i = 15; // First integer
int j = 22; // Second integer
// Perform bitwise AND operation and print the result
cout << (i & j) << endl; // Expected output: 6
// Perform bitwise OR operation and print the result
cout << (i | j) << endl; // Expected output: 31
// Perform bitwise XOR operation and print the result
cout << (i ^ j) << endl; // Expected output: 25
// Perform bitwise NOT operation on the first integer and print the result
cout << (~i) << endl; // Expected output: -16
// Perform left shift operation on the first integer and print the result
cout << (i << 2) << endl; // Expected output: 60
// Perform right shift operation on the second integer and print the result
cout << (j >> 2) << endl; // Expected output: 5
return 0;
}
Explanation
The provided C++ code demonstrates the use of various bitwise operators. The program begins by including the necessary header file iostream
and using the std
namespace to simplify the code.
#include <iostream>
using namespace std;
The main
function initializes two integer variables, i
and j
, with the values 15 and 22, respectively.
int i = 15; // First integer
int j = 22; // Second integer```
The program then performs several bitwise operations on these integers and prints the results using `cout`.
* **Bitwise AND (`&`)**: This operation compares each bit of `i` and `j` and returns a new integer where each bit is set to 1 only if both corresponding bits of `i` and `j` are 1. The result of `i & j` is 6.
```cpp
cout << (i & j) << endl; // Expected output: 6```
* **Bitwise OR (`|`)**: This operation compares each bit of `i` and `j` and returns a new integer where each bit is set to 1 if at least one of the corresponding bits of `i` or `j` is 1. The result of `i | j` is 31.
```cpp
cout << (i | j) << endl; // Expected output: 31```
* **Bitwise XOR (`^`)**: This operation compares each bit of `i` and `j` and returns a new integer where each bit is set to 1 if only one of the corresponding bits of `i` or `j` is 1. The result of `i ^ j` is 25.
```cpp
cout << (i ^ j) << endl; // Expected output: 25```
* **Bitwise NOT (`~`)**: This operation inverts all the bits of `i`, turning 1s into 0s and vice versa. The result of `~i` is -16.
```cpp
cout << (~i) << endl; // Expected output: -16```
* **Left Shift (`<<`)**: This operation shifts the bits of `i` to the left by 2 positions, effectively multiplying `i` by 2^2 (or 4). The result of `i << 2` is 60.
```cpp
cout << (i << 2) << endl; // Expected output: 60```
* **Right Shift (`>>`)**: This operation shifts the bits of `j` to the right by 2 positions, effectively dividing `j` by 2^2 (or 4). The result of `j >> 2` is 5.
```cpp
cout << (j >> 2) << endl; // Expected output: 5```
Finally, the `main` function returns 0, indicating that the program has executed successfully.
```cpp
return 0;
This code provides a clear and concise demonstration of how bitwise operators work in C++, making it a useful reference for developers looking to understand these operations.
Output
6
31
25
-16
60
5
Process finished with exit code 0```
logical AND (&&) and OR (||) operators in C++
The provided C++ code demonstrates the use of logical operators: AND (&&
), OR (||
), and NOT (!
), through a series of comparisons between three initialized integer variables (x
, y
, and z
).
Code
/**
* @file main.cpp
* @brief Demonstrates the use of logical AND (&&) and OR (||) operators in C++.
*
* This program initializes three integer variables, x, y, and z, and then demonstrates
* the use of logical AND (&&) and OR (||) operators by comparing these variables in
* various expressions. It also shows the use of the NOT (!) operator and explains
* the precedence of logical operators in C++.
*/
#include <iostream>
using namespace std;
int main() {
// Initialize variables
int x = 5, y = 10, z = 15;
// Display the values of x, y, and z
cout << "x = " << x << ", y = " << y << ", z = " << z << endl;
// Demonstrate logical AND (&&)
cout << "x < y && y < z = " << (x < y && y < z) << endl; // True, both conditions are true
cout << "x < y && y > z = " << (x < y && y > z) << endl; // False, second condition is false
// Demonstrate logical OR (||)
cout << "x < y || y > z = " << (x < y || y > z) << endl; // True, first condition is true
cout << "x > y || y > z = " << (x > y || y > z) << endl; // False, both conditions are false
// Demonstrate logical NOT (!)
cout << "!(x < y) = " << !(x < y) << endl; // False, negates true condition
cout << "!(x > y) = " << !(x > y) << endl; // True, negates false condition
// Explain operator precedence
cout << "priority of && is higher than ||" << endl;
// Demonstrate precedence with examples
cout << "x < y && y < z || x > z = " << (x < y && y < z || x > z) << endl;
// True, && evaluated first
cout << "x < y || y < z && x > z = " << (x < y || y < z && x > z) << endl;
// True, && evaluated first despite || appearing first
return 0;
}
Explanation
The provided C++ code demonstrates the use of logical operators: AND (&&
), OR (||
), and NOT (!
), through a series of comparisons between three initialized integer variables (x
, y
, and z
). It serves as an educational example to illustrate how these operators function in conditional statements and their precedence rules.
Initially, the code sets up three variables x
, y
, and z
with values 5, 10, and 15, respectively. This setup is crucial for the subsequent comparisons:
int x = 5, y = 10, z = 15;
The demonstration of the logical AND (&&
) operator is shown through two examples. The first example checks if x
is less than y
AND y
is less than z
, which evaluates to true since both conditions are satisfied:
cout << "x < y && y < z = " << (x < y && y < z) << endl;
The logical OR (||
) operator is similarly demonstrated. An example provided checks if x
is less than y
OR y
is greater than z
. This expression evaluates to true because the first condition is true, illustrating that only one condition needs to be true for the OR operator to result in true:
cout << "x < y || y > z = " << (x < y || y > z) << endl;
The NOT (!
) operator’s demonstration negates the truth value of the condition it precedes. For instance, negating the condition x < y
results in false because x < y
is true, and NOT true is false:
cout << "!(x < y) = " << !(x < y) << endl;
Lastly, the code touches upon the precedence of logical operators, stating that AND (&&
) has a higher precedence than OR (||
). This is crucial in understanding how complex logical expressions are evaluated. The provided examples show that even if OR appears first in an expression, the AND part is evaluated first due to its higher precedence:
cout << "x < y && y < z || x > z = " << (x < y && y < z || x > z) << endl;
This code snippet is a straightforward demonstration aimed at those familiar with C++ but perhaps not with the intricacies of logical operators and their precedence.
Output
x = 5, y = 10, z = 15
x < y && y < z = 1
x < y && y > z = 0
x < y || y > z = 1
x > y || y > z = 0
!(x < y) = 0
!(x > y) = 1
priority of && is higher than ||
x < y && y < z || x > z = 1
x < y || y < z && x > z = 1
Process finished with exit code 0```
Count even and odd numbers with while loop in C++
The provided C++ code is designed to count the number of even and odd numbers entered by the user, excluding the terminating 0.
Code
/*
* Program to count even and odd numbers.
*
* This program prompts the user to enter a sequence of integers, ending the sequence with a 0.
* It then counts the number of even and odd numbers entered (excluding the final 0) and displays the counts.
*
* How it works:
* 1. The program initializes two counters for even and odd numbers.
* 2. It prompts the user to enter a number and reads the user input.
* 3. If the number is not 0, it checks if the number is even or odd and increments the respective counter.
* 4. The program repeats steps 2 and 3 until the user enters 0.
* 5. Finally, it displays the counts of even and odd numbers.
*
* Note: The program considers 0 as neither even nor odd for the purpose of this count.
*/
#include <iostream>
using namespace std;
int main() {
int evenCount = 0; // Counter for even numbers
int oddCount = 0; // Counter for odd numbers
int userInput; // Variable to store the user's input
cout << "Enter a number: ";
cin >> userInput;
while (userInput != 0) {
if (userInput % 2 == 1)
oddCount++; // Increment odd counter if the number is odd
else
evenCount++; // Increment even counter if the number is even
cout << "Enter a number: ";
cin >> userInput;
}
cout << "Even numbers : " << evenCount << endl; // Display the count of even numbers
cout << "Odd numbers : " << oddCount << endl; // Display the count of odd numbers
return 0;
}
Explanation
The provided C++ code is designed to count the number of even and odd numbers entered by the user, excluding the terminating 0. The program operates in a loop, prompting the user to input integers until a 0 is entered, which signals the end of input. It utilizes the modulo operator (%
) to distinguish between even and odd numbers.
Initially, the program declares and initializes two integer variables, evenCount
and oddCount
, to zero. These variables serve as counters for the even and odd numbers, respectively.
int evenCount = 0; // Counter for even numbers
int oddCount = 0; // Counter for odd numbers
The program then enters a loop, first prompting the user to enter a number. This is achieved using cout
for the prompt and cin
to read the user’s input into the variable userInput
.
cout << "Enter a number: ";
cin >> userInput;
Within the loop, the program checks if the input is not 0. If it’s not, it determines whether the number is even or odd by using the modulo operation (userInput % 2
). If the result is 1, the number is odd, and oddCount
is incremented. Otherwise, the number is even, and evenCount
is incremented.
if (userInput % 2 == 1)
oddCount++; // Increment odd counter if the number is odd
else
evenCount++; // Increment even counter if the number is even
This process repeats until the user inputs 0, at which point the loop terminates. Finally, the program outputs the counts of even and odd numbers using cout
.
cout << "Even numbers : " << evenCount << endl;
cout << "Odd numbers : " << oddCount << endl;
This code snippet effectively demonstrates basic C++ input/output operations, conditional statements, and loop control structures, making it a straightforward example for developers familiar with C++ but new to this specific logic.
Output
Enter a number: 13
Enter a number: 212
Enter a number: 345
Enter a number: 23
Enter a number: 0
Even numbers : 1
Odd numbers : 3
Process finished with exit code 0```
for loop with examples in C++
The provided C++ code demonstrates various uses of the for
loop, incorporating control flow statements such as break
, continue
, and return
to manage loop execution.
Code
#include <iostream>
using namespace std;
/**
* Demonstrates various uses of the for loop in C++.
*
* This program includes examples of basic for loops, and for loops with control
* flow statements such as break, continue, and return to manage loop execution.
* It showcases how these control flow statements can alter the loop's behavior.
*/
int main() {
int i = 0;
// Basic for loop example: prints numbers from 0 to 9
for (i = 0; i < 10; i++) {
cout << i << endl;
}
cout << "Done" << endl;
// For loop with break: exits the loop when i equals 5
for (i = 0; i < 10; i++) {
if (i == 5) {
break;
}
cout << i << endl;
}
cout << "Done" << endl;
// For loop with continue: skips the current iteration when i equals 5
for (i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
cout << i << endl;
}
cout << "Done" << endl;
// For loop with return: exits the function when i equals 5
for (i = 0; i < 10; i++) {
if (i == 5) {
return 0;
}
cout << i << endl;
}
cout << "Done" << endl;
// For loop with break and return:
// demonstrates that break has no effect when followed by return
for (i = 0; i < 10; i++) {
if (i == 5) {
break;
}
cout << i << endl;
}
cout << "Done" << endl;
// For loop with continue and return:
// demonstrates that continue has no effect when followed by return
for (i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
cout << i << endl;
}
cout << "Done" << endl;
// For loop with break and continue:
// breaks the loop when i equals 5, continue is never reached
for (i = 0; i < 10; i++) {
if (i == 5) {
break;
}
if (i == 7) {
continue;
}
cout << i << endl;
}
cout << "Done" << endl;
// For loop with break, continue, and return:
// demonstrates control flow with break, continue is never reached
for (i = 0; i < 10; i++) {
if (i == 5) {
break;
}
if (i == 7) {
continue;
}
cout << i << endl;
}
cout << "Done" << endl;
return 0;
}
Explanation
The provided C++ code demonstrates various uses of the for
loop, incorporating control flow statements such as break
, continue
, and return
to manage loop execution. These examples illustrate how to control the flow within loops for different scenarios, making the code a valuable resource for understanding loop control mechanisms in C++.
Initially, a basic for
loop is shown, which iterates from 0 to 9, printing each number. This loop serves as a straightforward example of using a for
loop for simple iterations.
for (i = 0; i < 10; i++) {
cout << i << endl;
}
Following this, the code explores using a break
statement within a for
loop. This loop is designed to exit prematurely when i
equals 5, demonstrating how break
can be used to stop loop execution based on a condition.
for (i = 0; i < 10; i++) {
if (i == 5) {
break;
}
cout << i << endl;
}
Next, a for
loop with a continue
statement is introduced. This loop skips the current iteration when i
equals 5, effectively omitting the number 5 from the output. It showcases how continue
can be used to skip certain iterations within a loop, based on specific conditions.
for (i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
cout << i << endl;
}
Additionally, the code includes a for
loop that uses a return
statement to exit the function when i
equals 5. This example demonstrates how return
can be used within a loop to terminate the program execution based on a condition.
for (i = 0; i < 10; i++) {
if (i == 5) {
return 0;
}
cout << i << endl;
}
The code also presents scenarios where break
and continue
statements are combined with a return
statement in different loops. These examples illustrate the precedence and effect of these control flow statements when used together, highlighting that break
and continue
have no effect when followed by a return
statement.
In summary, the code provides a comprehensive overview of controlling loop execution using for
loops and control flow statements in C++. Each example serves to illustrate the flexibility and control that for
loops offer in C++, enabling developers to manage loop execution with precision.
Output
0
1
2
3
4
5
6
7
8
9
Done
0
1
2
3
4
Done
0
1
2
3
4
6
7
8
9
Done
0
1
2
3
4
Process finished with exit code 0```
do while loop with examples in C++
The provided C++ code demonstrates the use of do-while
loops, a variant of loop that ensures the loop’s body is executed at least once before the condition is checked.
Code
#include <iostream>
using namespace std;
/**
* Demonstrates various uses of the do-while loop in C++.
*
* This program includes examples of basic do-while loops, and do-while loops with control
* flow statements such as break, continue, and return to manage loop execution.
*/
int main() {
int i = 0;
// Basic do-while loop example
// This loop will execute the block at least once and then check the condition at the end.
i = 0;
do {
cout << i << endl; // Prints numbers from 0 to 9
i++;
} while (i < 10);
cout << "Done" << endl; // Indicates the end of the loop
// Do-while loop with break statement
// This loop demonstrates how to exit the loop prematurely using a break statement.
i = 0;
do {
if (i == 5) {
break; // Exits the loop when i equals 5
}
cout << i << endl; // Prints numbers from 0 to 4
i++;
} while (i < 10);
cout << "Done" << endl; // Indicates the end of the loop
// Do-while loop with continue statement
// This loop shows how to skip the rest of the loop body for the current iteration using continue.
i = 0;
do {
if (i == 5) {
i++; // Increment before continue to avoid infinite loop
continue; // Skips printing 5
}
cout << i << endl; // Prints numbers from 0 to 9, skipping 5
i++;
} while (i < 10);
cout << "Done" << endl; // Indicates the end of the loop
// Do-while loop with return statement
// This loop demonstrates using return within a loop to exit the program based on a condition.
i = 0;
do {
if (i == 5) {
return 0; // Exits the program when i equals 5
}
cout << i << endl; // Prints numbers from 0 to 4
i++;
} while (i < 10);
cout << "Done" << endl; // This line is never reached due to the return statement
return 0;
}
Explanation
The provided C++ code demonstrates the use of do-while
loops, a variant of loop that ensures the loop’s body is executed at least once before the condition is checked. This characteristic differentiates do-while
loops from the more common while
loops, where the condition is evaluated before the loop body is executed.
The first example in the code is a basic do-while
loop that prints numbers from 0 to 9. The loop starts with i
initialized to 0 and increments i
in each iteration. The condition i < 10
is checked after the loop body is executed, ensuring that the loop runs at least once.
do {
cout << i << endl;
i++;
} while (i < 10);
Next, the code demonstrates how to use a break
statement within a do-while
loop to exit the loop prematurely. In this example, the loop is designed to break when i
equals 5, thus it prints numbers from 0 to 4 before exiting.
do {
if (i == 5) {
break;
}
cout << i << endl;
i++;
} while (i < 10);
Following that, a do-while
loop with a continue
statement is shown. This loop skips the current iteration when i
equals 5 by using continue
, which causes the loop to immediately proceed to the next iteration. To prevent an infinite loop, i
is incremented before the continue
statement.
do {
if (i == 5) {
i++;
continue;
}
cout << i << endl;
i++;
} while (i < 10);
Lastly, the code includes a do-while
loop with a return
statement. This loop exits not just the loop but the entire program when i
equals 5. This demonstrates how a return
statement can be used within a loop to control the flow of the program based on certain conditions.
do {
if (i == 5) {
return 0;
}
cout << i << endl;
i++;
} while (i < 10);
Each of these examples illustrates different ways to control the execution flow within do-while
loops, showcasing their flexibility and utility in scenarios where at least one iteration of the loop is required.
Output
0
1
2
3
4
5
6
7
8
9
Done
0
1
2
3
4
Done
0
1
2
3
4
6
7
8
9
Done
0
1
2
3
4
Process finished with exit code 0```
while loop with examples in C++
The provided C++ code demonstrates various uses of the while
loop, showcasing how it can be utilized for basic iteration, and how control flow statements like break
, continue
, and return
can be integrated within these loops to manage their execution more precisely.
Code
#include <iostream>
using namespace std;
/**
* Demonstrates various uses of the while loop in C++.
*
* This program includes examples of basic while loops, and while loops with control
* flow statements such as break, continue, and return to manage loop execution.
*/
int main() {
// Basic while loop example
int i = 0;
while (i < 10) {
cout << i << endl; // Prints numbers from 0 to 9
i++;
}
cout << "Done" << endl; // Indicates the end of the loop
// While loop with break statement
i = 0;
while (i < 10) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
cout << i << endl; // Prints numbers from 0 to 4
i++;
}
cout << "Done" << endl; // Indicates the end of the loop
// While loop with continue statement
i = 0;
while (i < 10) {
if (i == 5) {
i++; // Increment before continue to avoid infinite loop
continue; // Skips the rest of the loop body when i equals 5
}
cout << i << endl; // Prints numbers from 0 to 9, skipping 5
i++;
}
cout << "Done" << endl; // Indicates the end of the loop
// While loop with return statement
i = 0;
while (i < 10) {
if (i == 5) {
return 0; // Exits the program when i equals 5
}
cout << i << endl; // Prints numbers from 0 to 4
i++;
}
cout << "Done" << endl; // This line is never reached due to the return statement
return 0;
}
Explanation
The provided C++ code demonstrates various uses of the while
loop, showcasing how it can be utilized for basic iteration, and how control flow statements like break
, continue
, and return
can be integrated within these loops to manage their execution more precisely.
Initially, the code presents a basic while
loop example where a counter i
is incremented in each iteration until it reaches 10. This loop prints numbers from 0 to 9, illustrating the fundamental use of while
for repetitive tasks.
int i = 0;
while (i < 10) {
cout << i << endl;
i++;
}
Following this, the code explores a while
loop that incorporates a break
statement. This loop is designed to exit prematurely when i
equals 5. Until that point, it functions similarly to the first loop, printing numbers from 0 to 4. The break
statement demonstrates how to exit a loop based on a condition, offering a way to halt iteration when a specific criterion is met.
if (i == 5) {
break;
}
Next, the code introduces a while
loop with a continue
statement. This loop skips the current iteration when i
equals 5, effectively omitting the number 5 from the output. It highlights how continue
can be used to skip certain iterations within a loop, based on specific conditions, without exiting the loop entirely.
if (i == 5) {
i++;
continue;
}
Lastly, the code features a while
loop that employs a return
statement to exit not just the loop but the entire program when i
equals 5. This example shows how return
can be used within a loop to terminate the program execution based on a condition, providing a direct way to control the flow of the program from within iterative structures.
if (i == 5) {
return 0;
}
Each of these examples serves to illustrate the flexibility and control that while
loops offer in C++, enabling developers to manage loop execution with precision through the use of control flow statements.
Output
0
1
2
3
4
5
6
7
8
9
Done
0
1
2
3
4
Done
0
1
2
3
4
6
7
8
9
Done
0
1
2
3
4
Process finished with exit code 0```
Short long and unsigned modifiers in C++
The provided C++ code demonstrates the declaration and usage of various fundamental data types and their sizes.
Code
#include <iostream>
using namespace std;
/**
* @brief Main function demonstrating the use of various data types in C++ and their sizes.
*
* This program declares variables of different data types including integer types
* (int, short int, long int, unsigned int, unsigned short int, unsigned long int),
* character types (char, unsigned char, signed char),
* and floating-point types (float, double, long double).
* It then prints the size of each data type in bytes.
*
* @return int Returns 0 upon successful execution.
*/
int main() {
// Integer types
int Integer; // Range: -2147483648 to 2147483647
short int shortInteger; // Range: -32768 to 32767
long int longInteger; // Range: -9223372036854775808 to 9223372036854775807
unsigned int unsignedInteger; // Range: 0 to 4294967295
unsigned short int unsignedShortInteger; // Range: 0 to 65535
unsigned long int unsignedlongInteger; // Range: 0 to 18446744073709551615
// Character types
char normalChar; // Range: -128 to 127
unsigned char unsignedChar; // Range: 0 to 255
signed char signedCchar; // Range: -128 to 127 (same as char)
// Floating-point types
float normalFloat; // Range: 1.4012984643248171e-45 to 3.4028234663852886e+38
double normalDouble; // Range: 2.2250738585072014e-308 to 1.7976931348623157e+308
long double normalLongDouble; // Range: 2.2250738585072014e-308 to 1.7976931348623157e+308
// Printing the size of each data type
cout <<"The size of int is " <<sizeof(Integer) << " bytes" << endl;
cout <<"The size of short int is " <<sizeof(shortInteger) << " bytes" << endl;
cout <<"The size of long int is " <<sizeof(longInteger) << " bytes" << endl;
cout <<"The size of unsigned int is " <<sizeof(unsignedInteger) << " bytes" << endl;
cout <<"The size of unsigned short int is " <<sizeof(unsignedShortInteger) << " bytes" << endl;
cout <<"The size of unsigned long int is " <<sizeof(unsignedlongInteger) << " bytes" << endl;
cout <<"The size of char is " <<sizeof(normalChar) << " bytes" << endl;
cout <<"The size of unsigned char is " <<sizeof(unsignedChar) << " bytes" << endl;
cout <<"The size of signed char is " <<sizeof(signedCchar) << " bytes" << endl;
cout <<"The size of float is " <<sizeof(normalFloat) << " bytes" << endl;
cout <<"The size of double is " <<sizeof(normalDouble) << " bytes" << endl;
cout <<"The size of long double is " <<sizeof(normalLongDouble) << " bytes" << endl;
return 0;
}
Explanation
The provided C++ code demonstrates the declaration and usage of various fundamental data types and their sizes. It begins by including the <iostream>
header, enabling input and output operations, and uses the std
namespace to avoid prefixing standard library entities with std::
.
The main function, which is the entry point of the program, declares variables of different data types, including integer types (int
, short int
, long int
, unsigned int
, unsigned short int
, unsigned long int
), character types (char
, unsigned char
, signed char
), and floating-point types (float
, double
, long double
). Each variable is accompanied by a comment indicating its range, which is crucial for understanding the limits of each data type.
For example, the integer variable declaration is shown as follows:
int Integer; // Range: -2147483648 to 2147483647```
This line declares an `int` variable named `Integer`, which can store values from -2,147,483,648 to 2,147,483,647.
After declaring these variables, the program prints the size of each data type in bytes using the `sizeof` operator. This is a compile-time operator that determines the size, in bytes, of a variable or data type. The output is directed to the console using `cout`, which is part of the `iostream` library.
For instance, the size of the `int` data type is printed with the following line:
```cpp
cout <<"The size of int is " <<sizeof(Integer) << " bytes" << endl;
This line outputs the size of an int
in bytes, helping to understand how much memory each data type consumes.
The program concludes by returning 0, indicating successful execution. This code snippet is a practical demonstration for beginners to understand the sizes of different data types in C++, which is fundamental in choosing the appropriate type for variables based on the range of values they are expected to hold and the memory efficiency.
Output
The size of int is 4 bytes
The size of short int is 2 bytes
The size of long int is 8 bytes
The size of unsigned int is 4 bytes
The size of unsigned short int is 2 bytes
The size of unsigned long int is 8 bytes
The size of char is 1 bytes
The size of unsigned char is 1 bytes
The size of signed char is 1 bytes
The size of float is 4 bytes
The size of double is 8 bytes
The size of long double is 16 bytes
Process finished with exit code 0```
Calculate square root of an integer with cmath library in C++
The provided C++ code is a simple program that calculates the square root of a user-provided number. It begins by including the necessary libraries, iostream
for input/output operations and cmath
for mathematical operations.
Code
#include <iostream>
#include <cmath>
using namespace std;
// Main function of the program
int main() {
// Declare a float variable to store the user's input
float inputNumber;
// Prompt the user to enter a number
cout << "Enter a number to calculate its square root: ";
// Store the user's input in the variable
cin >> inputNumber;
// Check if the input number is non-negative
if (inputNumber >= 0.0) {
// Calculate the square root of the input number
float squareRoot = sqrt(inputNumber);
// Print the input number
cout << "Input number: " << inputNumber << " ";
// Print the square root of the input number
cout << "Square root: " << squareRoot << " ";
}
}
Explanation
The provided C++ code is a simple program that calculates the square root of a user-provided number. It begins by including the necessary libraries, iostream
for input/output operations and cmath
for mathematical operations.
#include <iostream>
#include <cmath>
using namespace std;
The main function of the program starts with the declaration of a float variable inputNumber
which is used to store the user’s input.
float inputNumber;
The program then prompts the user to enter a number using cout
and stores the user’s input in the inputNumber
variable using cin
.
cout << "Enter a number to calculate its square root: ";
cin >> inputNumber;
The program checks if the input number is non-negative using an if
statement. This is important because the square root of a negative number is not a real number and would result in an error.
if (inputNumber >= 0.0) {```
Inside the `if` statement, the program calculates the square root of the input number using the `sqrt` function from the `cmath` library and stores the result in the `squareRoot` variable.
```cpp
float squareRoot = sqrt(inputNumber);
Finally, the program prints the input number and its square root using cout
.
cout << "Input number: " << inputNumber << " ";
cout << "Square root: " << squareRoot << " ";
This code is a simple demonstration of user input, conditional statements, and mathematical operations in C++.
Output
Enter a number to calculate its square root: 15
Input number: 15
Square root: 3.87298
Process finished with exit code 0```
User input with cin function in C++
The provided C++ code is a simple console application that prompts the user to enter an integer, outputs the entered integer, doubles the entered integer, and then outputs the doubled value.
Code
#include <iostream> // Include the iostream library to enable input/output operations
using namespace std; // Use the standard namespace
// Main function
int main() {
int userInput; // Declare an integer variable to store user input
// Prompt the user to enter an integer
cout << "Enter an integer: ";
cin >> userInput; // Read the user input from the console
// Output the entered integer
cout << "You entered: " << userInput << endl;
userInput = 2 * userInput; // Double the user input
// Output the doubled value
cout << "The doubled value is: " << userInput << endl;
return 0; // Return 0 to indicate that the program has run successfully
}
Explanation
The provided C++ code is a simple console application that prompts the user to enter an integer, outputs the entered integer, doubles the entered integer, and then outputs the doubled value.
The code begins with the inclusion of the iostream
library, which is necessary for input/output operations in C++. The using namespace std;
statement is used to avoid having to prefix standard library functions with std::
.
#include <iostream>
using namespace std;
The main
function is the entry point of the program. Inside this function, an integer variable userInput
is declared to store the user’s input.
int main() {
int userInput;
The program then prompts the user to enter an integer using cout
, and reads the user’s input from the console using cin
.
cout << "Enter an integer: ";
cin >> userInput;
The entered integer is then outputted to the console.
cout << "You entered: " << userInput << endl;
The userInput
variable is then doubled by multiplying it by 2.
userInput = 2 * userInput;
Finally, the doubled value is outputted to the console, and the main
function returns 0 to indicate that the program has run successfully.
cout << "The doubled value is: " << userInput << endl;
return 0;
This code is a basic example of user interaction and arithmetic operations in C++.
Output
Enter an integer: 12
You entered: 12
The doubled value is: 24
Process finished with exit code 0```
Converting types with static_cast in C++
The provided C++ code is a simple demonstration of the static_cast
operator, which is used to convert an expression to a new type.
Code
// This program demonstrates the use of static_cast in C++
// static_cast<newtype>(expr) is used to cast an expression to a new type
#include <iostream>
using namespace std;
int main() {
// Declare and initialize integer variables
int numberOne = 56;
int numberTwo = 92;
// Declare and initialize a character variable
char character = 'a';
// Display the character equivalent of numberOne
// static_cast<char>(numberOne) converts the integer to a character
cout << "a" << " " << static_cast<char>(numberOne) << endl;
// Display the character equivalent of numberTwo
// static_cast<char>(numberTwo) converts the integer to a character
cout << "b" << " " << static_cast<char>(numberTwo) << endl;
// Display the integer equivalent of character
// static_cast<int>(character) converts the character to an integer
cout << "c" << " " << static_cast<int>(character) << endl;
// End of program
return 0;
}
Explanation
The provided C++ code is a simple demonstration of the static_cast
operator, which is used to convert an expression to a new type.
The program begins by including the iostream
library and declaring the std
namespace for usage. This is a common practice in C++ to allow for easier usage of standard library functions, such as cout
for console output.
#include <iostream>
using namespace std;
In the main
function, three variables are declared and initialized: two integers (numberOne
and numberTwo
) and one character (character
).
int numberOne = 56;
int numberTwo = 92;
char character = 'a';
The static_cast
operator is then used to convert these variables to different types. The static_cast<char>(numberOne)
expression converts the integer numberOne
to a character, and its result is printed to the console. The same operation is performed for numberTwo
.
cout << "a" << " " << static_cast<char>(numberOne) << endl;
cout << "b" << " " << static_cast<char>(numberTwo) << endl;
Finally, the character
variable is converted to an integer using static_cast<int>(character)
, and the result is printed to the console.
cout << "c" << " " << static_cast<int>(character) << endl;
In summary, this program demonstrates how to use the static_cast
operator in C++ to convert between different data types. It’s a simple but effective illustration of type casting in C++.
Output
a 8
b \
c 97
Process finished with exit code 0```
How to print an integer in different number systems: hexadecimal, decimal, and octal?
The provided C++ code is a simple program that demonstrates how to print an integer in different number systems: hexadecimal, decimal, and octal.
Code
/**
* This is the main function of the program.
* It demonstrates different ways to print an integer
* in different number systems (hexadecimal, decimal, and octal).
*
* The function does the following:
* 1. Declares an integer variable named `byte` and initializes it with the value 255.
* 2. Prints the value of `byte` in hexadecimal format.
* 3. Prints the value of `byte` in the last used number base
* (which is hexadecimal from the previous line),
* then it changes the number base to decimal and prints the `byte` again.
* 4. Changes the number base to octal and prints the `byte`.
*
* @return 0 if the program runs successfully.
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int byte = 255;
cout << hex << byte << endl;
cout << byte << dec << byte << endl;
cout << oct << byte << endl;
// we can achieve same result with setbase function
// setbase accept only 2, 8, 10 or 16 as parameter
// setbase requires iomanip header
cout << setbase(16) << byte << endl;
cout << setbase(10) << byte << endl;
cout << setbase(8) << byte << endl;
cout << setbase(2) << byte << endl;
return 0;
}
Explanation
The provided C++ code is a simple program that demonstrates how to print an integer in different number systems: hexadecimal, decimal, and octal.
The program begins by including the necessary libraries, iostream
for input/output operations and iomanip
for input/output manipulations. The using namespace std;
line allows the program to use the standard namespace, which includes functions like cout
and endl
.
#include <iostream>
#include <iomanip>
using namespace std;
The main
function is the entry point of the program. Inside this function, an integer variable named byte
is declared and initialized with the value 255.
int main() {
int byte = 255;
The program then prints the value of byte
in hexadecimal format using the hex
manipulator.
cout << hex << byte << endl;
Next, the program prints the value of byte
in the last used number base (which is hexadecimal from the previous line), then it changes the number base to decimal using the dec
manipulator and prints the byte
again.
cout << byte << dec << byte << endl;
The number base is then changed to octal using the oct
manipulator and the byte
is printed again.
cout << oct << byte << endl;
Finally, the program demonstrates another way to change the number base using the setbase
function from the iomanip
library. This function accepts only 2, 8, 10, or 16 as parameters, representing binary, octal, decimal, and hexadecimal number systems respectively. cout « setbase(16) « byte « endl; cout « setbase(10) « byte « endl; cout « setbase(8) « byte « endl;
Output
ff
ff255
377
ff
255
377
255
Process finished with exit code 0```
The use of basic comparison operators in C++
The provided C++ code is a simple console application that demonstrates the use of basic comparison operators in C++.
Code
#include <iostream>
using namespace std;
int main() {
// Initialize two integer variables x and y
int x = 0, y = 0;
// Print the question: is x equal to y?
cout << "Question: is x equal to y?" << endl;
// Check if x is equal to y
if (x == y) {
// If x is equal to y, print the result
cout << "x is equal to y" << endl;
}
// Change the values of x and y
x = 0, y = 1;
// Print the question: is x not equal to y?
cout << "Question: is x not equal to y?" << endl;
// Check if x is not equal to y
if (x != y) {
// If x is not equal to y, print the result
cout << "x is not equal to y" << endl;
}
// Change the values of x and y
x = 1, y = 0;
// Print the question: is x greater than y?
cout << "Question: is x greater than y?" << endl;
// Check if x is greater than y
if (x > y) {
// If x is greater than y, print the result
cout << "x is greater than y" << endl;
}
// Change the values of x and y
x = 2, y = 1;
// Print the question: is x greater than or equal to y?
cout << "Question: is x greater than or equal to y?" << endl;
// Check if x is greater than or equal to y
if (x >= y) {
// If x is greater than or equal to y, print the result
cout << "x is greater than or equal to y" << endl;
}
// Change the values of x and y
x = 1, y = 2;
// Print the question: is x less than (or equal to) y?
cout << "Question: is x less than (or equal to) y?" << endl;
// Check if x is less than or equal to y
if (x <= y) {
// If x is less than or equal to y, print the result
cout << "x is less than or equal to y" << endl;
}
// End of the program
return 0;
}
Explanation
The provided C++ code is a simple console application that demonstrates the use of basic comparison operators in C++. It does so by initializing two integer variables, x
and y
, and then comparing them using different operators.
Initially, x
and y
are both set to 0
:
int x = 0, y = 0;
The code then prints a question to the console asking if x
is equal to y
:
cout << "Question: is x equal to y?" << endl;
This is followed by an if
statement that checks if x
is indeed equal to y
using the ==
operator. If the condition is true, it prints a message to the console:
if (x == y) {
cout << "x is equal to y" << endl;
}
The code then changes the values of x
and y
and repeats the process with different comparison operators (!=
, >
, >=
, <
, <=
). Each time, it prints a question to the console, checks the condition, and prints a message if the condition is true.
For example, after changing x
to 0
and y
to 1
, the code checks if x
is not equal to y
:
x = 0, y = 1;
cout << "Question: is x not equal to y?" << endl;
if (x != y) {
cout << "x is not equal to y" << endl;
}
This pattern continues until all the comparison operators have been demonstrated. The program then ends with a return 0;
statement, indicating successful execution.
Output
Question: is x equal to y?
x is equal to y
Question: is x not equal to y?
x is not equal to y
Question: is x greater than y?
x is greater than y
Question: is x greater than or equal to y?
x is greater than or equal to y
Question: is x less than (or equal to) y?
x is less than or equal to y
Process finished with exit code 0```
Char type and usage examples in C++
The provided C++ code is a demonstration of how to manipulate and display characters and their ASCII values. It also includes a brief explanation of escape characters in C++.
Code
#include <iostream>
using namespace std;
// Main function
int main() {
// Declare a character variable
char character = 'A';
// Print the character
cout << "Character: " << character << endl;
// Assign ASCII value of 'A' to the character
character = 65;
// Print the character
cout << "Character (65 in ASCII): " << character << endl;
// Assign escape character for single quote to the character
character = '\'';
// Print the character
cout << "Character: " << character << endl;
// Assign escape character for backslash to the character
character = '\\';
// Print the character
cout << "Character: " << character << endl;
// Assign hexadecimal value for single quote to the character
character = '\x27';
// Print the character
cout << "Character (hexadecimal \\x27): " << character << endl;
// Assign octal value for single quote to the character
character = '\047';
// Print the character
cout << "Character (octal \\047): " << character << endl;
// Char types as int values
/*
*You can always assign a char value to an int variable;
*You can always assign an int value to a char variable,
*but if the value exceeds 255 (the top-most character code in ASCII),
*you must expect a loss of value;
*The value of the char type can be subject to the same operators as the data of type int.
*The value of the char type is always an unsigned char.
*/
// Assign 'A' + 32 to the character
character = 'A' + 32;
// Print the character
cout << "Character: " << character << endl;
// Assign 'A' + ' ' to the character
character = 'A' + ' ';
// Print the character
cout << "Character: " << character << endl;
// Assign 65 + ' ' to the character
character = 65 + ' ';
// Print the character
cout << "Character: " << character << endl;
// Assign 97 - ' ' to the character
character = 97 - ' ';
// Print the character
cout << "Character: " << character << endl;
// Assign 'a' - 32 to the character
character = 'a' - 32;
// Print the character
cout << "Character: " << character << endl;
// Assign 'a' - ' ' to the character
character = 'a' - ' ';
// Print the character
cout << "Character: " << character << endl;
// Return 0 to indicate successful execution
return 0;
}
Explanation
The provided C++ code is a demonstration of how to manipulate and display characters and their ASCII values. It also includes a brief explanation of escape characters in C++.
The main function begins by declaring a character variable char character = 'A';
. This character is then printed to the console using cout << "Character: " << character << endl;
.
The ASCII value of ‘A’, which is 65, is then assigned to the character variable character = 65;
. This is again printed to the console, demonstrating that the character ‘A’ and the integer 65 are interchangeable when dealing with char variables.
The code then explores the use of escape characters. Escape characters are special characters that you can include in your text strings such as newline (
), tab (\t
), backspace (\b
), etc. In this code, the escape characters for a single quote (\'
) and a backslash (\\
) are assigned to the character variable and printed.
The code also demonstrates how to assign hexadecimal and octal values to the character variable using escape sequences. For example, the hexadecimal value for a single quote is assigned using character = '\x27';
and the octal value is assigned using character = '\047';
.
The code then demonstrates some arithmetic operations with characters. For example, it assigns the result of ‘A’ + 32 to the character variable character = 'A' + 32;
. This is equivalent to assigning the ASCII value of ‘a’ to the character variable because ‘A’ has an ASCII value of 65 and ‘a’ has an ASCII value of 97, and the difference between these two values is 32.
Finally, the code includes a comment section that provides additional information about char types, their int values, and the use of escape characters in C++.
Output
Character: A
Character (65 in ASCII): A
Character: '
Character: \
Character (hexadecimal \x27): '
Character (octal \047): '
Character: a
Character: a
Character: a
Character: A
Character: A
Character: A
Process finished with exit code 0```
## Escape Characters
```cpp
// Explanation of escape characters in C++
// All escape characters can be used in C++ strings to print special characters
// = new line character to print new line character in string output
// \t = tab character to print tab character in string output
// \b = backspace character to print backspace character in string output
// \r = carriage return character to print carriage return character in string output
// \f = form feed character to print form feed character in string output
// \v = vertical tab character to print vertical tab character in string output
// \a = alert character to print alert character in string output
// \e = escape character to print escape character in string output
// \0 = null character to print null character in string output
// \\ = backslash character to print backslash character in string output
// \" = double quote character to print double quote character in string output
// \' = single quote character to print single quote character in string output
// \? = question mark character to print question mark character in string output```
Shortcut operators in C++
The provided code is a C++ program that demonstrates the use of shortcut operators. It includes the iostream
library, which is used for input/output operations, and the std
namespace is being used.
Code
/**
* Main function to demonstrate shortcut operators in C++.
*
* @return 0 indicating successful execution
*/
#include <iostream>
using namespace std;
int main() {
int num1 = 1;
int num2 = 2;
int num3 = 3;
int num4 = 4;
int num5 = 5;
int num6 = 6;
int num7 = 7;
int num8 = 8;
int num9 = 9;
int num10 = 10;
num1 += num2;
num3 -= num4;
num5 *= num6;
num7 /= num8;
num9 %= num10;
cout << "num1 = " << num1 << endl;
cout << "num3 = " << num3 << endl;
cout << "num5 = " << num5 << endl;
cout << "num7 = " << num7 << endl;
cout << "num9 = " << num9 << endl;
return 0;
}
Explanation
The provided code is a C++ program that demonstrates the use of shortcut operators. It includes the iostream
library, which is used for input/output operations, and the std
namespace is being used.
The main
function is the entry point of the program. It initializes ten integer variables num1
through num10
with values from 1 to 10 respectively.
int num1 = 1;
int num2 = 2;
// ...
int num10 = 10;
The program then demonstrates the use of various shortcut operators. The +=
operator adds the value of num2
to num1
and assigns the result to num1
. The -=
operator subtracts num4
from num3
and assigns the result to num3
. The *=
operator multiplies num5
by num6
and assigns the result to num5
. The /=
operator divides num7
by num8
and assigns the result to num7
. The %=
operator calculates the remainder of num9
divided by num10
and assigns the result to num9
.
num1 += num2;
num3 -= num4;
num5 *= num6;
num7 /= num8;
num9 %= num10;
Finally, the program prints the values of num1
, num3
, num5
, num7
, and num9
to the console using the cout
object and the <<
operator, which is used to send output to the standard output device (usually the screen).
cout << "num1 = " << num1 << endl;
// ...
cout << "num9 = " << num9 << endl;
The endl
manipulator is used to insert a new line. The program ends by returning 0, indicating successful execution.
Output
num1 = 3
num3 = -1
num5 = 30
num7 = 0
num9 = 9
Process finished with exit code 0```
The usage of pre-increment and post-increment operators
This code snippet demonstrates the usage of pre-increment and post-increment operators in C++.
Code
/**
* Main function that demonstrates the usage of pre-increment and post-increment operators.
*
* @return 0 indicating successful execution
*
* @throws None
*/
#include <iostream>
using namespace std;
int main() {
int numberOne = 1;
int numberTwo = 2;
int numberThree = 3;
int numberFour = 4;
// numberOne current value is 1
int result = numberOne++; // Assignment and increment after the operation
cout << "Number One: " << numberOne << endl;
cout << "Result: " << result << endl;
cout << "----" << endl;
//numberTwo current value is 2
result = ++numberTwo; // Increment and assignment before the operation
cout << "Number Two: " << numberTwo << endl;
cout << "Result: " << result << endl;
cout << "----" << endl;
//numberThree current value is 3
result = numberThree--; // Assignment and decrement after the operation
cout << "Number Three: " << numberThree << endl;
cout << "Result: " << result << endl;
cout << "----" << endl;
//numberFour current value is 4
result = --numberFour; // Decrement and assignment before the operation
cout << "Number Four: " << numberFour << endl;
cout << "Result: " << result << endl;
return 0;
}
Explanation
The provided C++ code is a simple demonstration of the usage of pre-increment (++var
), post-increment (var++
), pre-decrement (--var
), and post-decrement (var--
) operators in C++.
The main function starts by declaring four integer variables numberOne
, numberTwo
, numberThree
, and numberFour
with initial values of 1, 2, 3, and 4 respectively.
The first operation is numberOne++
. This is a post-increment operation, which means the current value of numberOne
is assigned to result
before numberOne
is incremented. Therefore, result
will be 1 (the original value of numberOne
), and numberOne
will be incremented to 2.
Next, the operation ++numberTwo
is a pre-increment operation. Here, numberTwo
is incremented before the assignment operation. So, numberTwo
becomes 3, and this new value is assigned to result
.
The third operation is numberThree--
, a post-decrement operation. Similar to the post-increment, the current value of numberThree
is assigned to result
before numberThree
is decremented. So, result
will be 3, and numberThree
will be decremented to 2.
Finally, the operation --numberFour
is a pre-decrement operation. Here, numberFour
is decremented before the assignment operation. So, numberFour
becomes 3, and this new value is assigned to result
.
After each operation, the new values of the variables and result
are printed to the console for verification. The function then returns 0, indicating successful execution.
Output
Number One: 2
Result: 1
----
Number Two: 3
Result: 3
----
Number Three: 2
Result: 3
----
Number Four: 3
Result: 3
Process finished with exit code 0```
Simple demonstration of operator precedence and type casting in C++
The provided C++ code is a simple demonstration of operator precedence and type casting in C++.
Code
// Let's demonstrate how to use operator priority in C++
#include <iostream>
using namespace std;
int main() {
int num1 = 1;
int num2 = 2;
int num3 = 3;
int num4 = 4;
double result1 = static_cast<double>(num1 + num2 * num3) / num4;
double result2 = static_cast<double>((num1 + num2) * num3) / num4;
double result3 = static_cast<double>((num1 + num2) * (num3 / num4));
double result4 = static_cast<double>((num1 + num2) * num3) / static_cast<double>(num4);
double result5 = static_cast<double>((num1 + num2) * num3) / static_cast<double>(num4);
double result6 = static_cast<double>((num1 + num2) * num3) / static_cast<double>(num4);
cout << result1 << endl;
cout << result2 << endl;
cout << result3 << endl;
cout << result4 << endl;
cout << result5 << endl;
cout << result6 << endl;
return 0;
}
Explanation
The provided C++ code is a simple demonstration of operator precedence and type casting in C++.
The code begins by declaring four integer variables num1
, num2
, num3
, and num4
, each initialized with values from 1 to 4 respectively.
int num1 = 1;
int num2 = 2;
int num3 = 3;
int num4 = 4;
Then, six double variables result1
to result6
are declared. Each of these variables is assigned the result of a mathematical expression involving the previously declared integer variables. The expressions are designed to demonstrate how operator precedence (the order in which operations are performed) can affect the result of a calculation.
For example, result1
is calculated as follows:
double result1 = static_cast<double>(num1 + num2 * num3) / num4;
In this expression, due to operator precedence, multiplication (num2 * num3
) is performed before addition (num1 +
). The entire expression within the parentheses is then type-casted to a double before division by num4
. This ensures that the division operation produces a double result, not an integer.
The other result
variables are calculated in a similar manner, but with different arrangements of parentheses to demonstrate how they can be used to override operator precedence.
Finally, the values of all result
variables are printed to the console using cout
:
cout << result1 << endl;
cout << result2 << endl;
cout << result3 << endl;
cout << result4 << endl;
cout << result5 << endl;
cout << result6 << endl;
This allows the user to see the different results produced by the different expressions, illustrating the effects of operator precedence and type casting in C++.
Output
1.75
2.25
0
2.25
2.25
2.25
Process finished with exit code 0```
## Operator Precedence Rules
In C++, operators have a specific order in which they are evaluated when an expression has several of them. This is known as operator precedence. Here are some common operator precedence rules in C++, from highest to lowest precedence:
* **Parentheses `()`**: Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want.
* **Unary operators `++`, `--`, `!`, `~`, `-`, `+`, `*`, `&`, `sizeof`, `new`, `delete`**: These operators have the next highest precedence after parentheses. They are used with only one operand. For example, the increment (`++`) and decrement (`--`) operators.
* **Multiplicative operators `*`, `/`, `%`**: These operators are evaluated next. They perform multiplication, division, and modulus operations.
* **Additive operators `+`, `-`**: These operators are used for addition and subtraction operations.
* **Shift operators `<<`, `>>`**: These operators are used to shift bits to the left or right.
* **Relational operators `<`, `<=`, `>`, `>=`**: These operators are used to compare two values.
* **Equality operators `==`, `!=`**: These operators are used to check the equality or inequality of two operands.
* **Bitwise AND operator `&`**: This operator performs a bitwise AND operation.
* **Bitwise XOR operator `^`**: This operator performs a bitwise XOR operation.
* **Bitwise OR operator `|`**: This operator performs a bitwise OR operation.
* **Logical AND operator `&&`**: This operator performs a logical AND operation.
* **Logical OR operator `||`**: This operator performs a logical OR operation.
* **Conditional operator `?:`**: This operator works as a simple `if-else` statement.
* **Assignment operators `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`, `&=`, `^=`, `|=`**: These operators are used to assign values to variables.
* **Comma operator `,`**: This operator is used to link related expressions together.
Remember, when operators have the same precedence, the rule of associativity (left-to-right or right-to-left) is used to determine the order of operations.
Arithmetic and Logical operators in C++
This code snippet demonstrates various operators in C++:
Arithmetic operators: Multiplication, Division, Addition, Subtraction, Modulus
Increment and Decrement operators
Assignment operator
Comparison operators: Equal, Greater, Less, Not Equal, Greater or Equal, Less or Equal
Bitwise operators: AND, OR, XOR, NOT
Logical operators: AND, OR It also includes output statements to display the results of these operations.
Code
// Lets explain operators in C++ with examples multiplacaion, division, addition, subtraction,
// modulus, increment, decrement, assignment, comparison, logical and bitwise operators in C++
#include <iostream>
using namespace std;
int main() {
int num1 = 10;
int num2 = 5;
cout << "Multiplication: " << num1 * num2 << endl;
cout << "Division: " << num1 / num2 << endl;
cout << "Addition: " << num1 + num2 << endl;
cout << "Subtraction: " << num1 - num2 << endl;
cout << "Modulus: " << num1 % num2 << endl;
int result = num1;
cout << "Before increment: " << result << endl;
result++;
cout << "After increment: " << result << endl;
result--;
cout << "Decrement: " << result << endl;
result = num1;
cout << "Assignment: " << result << endl;
// num1 value is 10
// num2 value is 5
if (num1 == num2) {
cout << "Equal" << endl;
} else if (num1 > num2) {
cout << "Greater" << endl;
} else {
cout << "Less" << endl;
}
//num1 value is 10 and num2 value is 5
if (num1 != num2) {
cout << "Not Equal" << endl;
} else if (num1 < num2) {
cout << "Not Greater" << endl;
} else {
cout << "Not Less" << endl;
}
// num1 value is 10 and num2 value is 5
if (num1 >= num2) {
cout << "Greater or Equal" << endl;
} else if (num1 <= num2) {
cout << "Less or Equal" << endl;
} else {
cout << "Not Equal" << endl;
}
// Bitwise operators
// num1 value is 10 and num2 value is 5
cout << "Bitwise AND: " << (num1 & num2) << endl; // 0
cout << "Bitwise OR: " << (num1 | num2) << endl; // 15
cout << "Bitwise XOR: " << (num1 ^ num2) << endl; // 15
cout << "Bitwise NOT: " << ~num1 << endl; // -11
// num1 value is 10 and num2 value is 5
cout << "Logical AND: " << (num1 && num2) << endl;
cout << "Logical OR: " << (num1 || num2) << endl;
// num1 value is 10 and num2 value is 5
if (num1 && num2) {
cout << "True" << endl;
} else {
cout << "False" << endl;
}
// num1 value is 10 and num2 value is 5
if (num1 || num2) {
cout << "True" << endl;
} else {
cout << "False" << endl;
}
return 0;
}
Explanation
The provided C++ code is a simple demonstration of various operators in C++. It includes arithmetic, assignment, comparison, logical, and bitwise operators.
The code begins by declaring two integer variables, num1
and num2
, with values 10 and 5 respectively.
int num1 = 10;
int num2 = 5;
The arithmetic operators are then demonstrated. These include multiplication (*
), division (/
), addition (+
), subtraction (-
), and modulus (%
). The results of these operations are printed to the console.
cout << "Multiplication: " << num1 * num2 << endl;
cout << "Division: " << num1 / num2 << endl;
The increment (++
) and decrement (--
) operators are demonstrated next. The variable result
is incremented and decremented, and the results are printed to the console.
result++;
cout << "After increment: " << result << endl;
The assignment operator (=
) is used to assign the value of num1
to result
.
result = num1;
cout << "Assignment: " << result << endl;
The comparison operators (==
, >
, <
, !=
, >=
, <=
) are used to compare num1
and num2
. The results of these comparisons are printed to the console.
if (num1 == num2) {
cout << "Equal" << endl;
}
The bitwise operators (&
, |
, ^
, ~
) are used to perform bitwise operations on num1
and num2
. The results of these operations are printed to the console.
cout << "Bitwise AND: " << (num1 & num2) << endl;
Finally, the logical operators (&&
, ||
) are used to perform logical operations on num1
and num2
. The results of these operations are printed to the console.
cout << "Logical AND: " << (num1 && num2) << endl;
In summary, this code provides a comprehensive demonstration of the various operators available in C++.
Output
Multiplication: 50
Division: 2
Addition: 15
Subtraction: 5
Modulus: 0
Before increment: 10
After increment: 11
Decrement: 10
Assignment: 10
Greater
Not Equal
Greater or Equal
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise NOT: -11
Logical AND: 1
Logical OR: 1
True
True```
float type and its usage in C++
The provided C++ code is a demonstration of how to use and display floating point numbers in different formats using the iostream
and iomanip
libraries.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float f = 3.14159;
float g = .4;
float h = 3.14e-2;
float i = 3.14e2;
float j = 3.14e+2;
cout << "f: " << f << endl;
cout << "g: " << g << endl;
cout << "h: " << h << endl;
cout << "i: " << i << endl;
cout << "j: " << j << endl;
cout << "f (precision 10): " << setprecision(10) << f << endl;
cout << "g (precision 10): " << setprecision(10) << g << endl;
cout << "h (precision 10): " << setprecision(10) << h << endl;
cout << "i (precision 10): " << setprecision(10) << i << endl;
cout << "j: " << setprecision(10) << j << endl;
cout << "f (scientific): " << scientific << f << endl;
cout << "g (scientific): " << scientific << g << endl;
cout << "h (scientific): " << scientific << h << endl;
cout << "i (scientific): " << scientific << i << endl;
cout << "j (scientific): " << scientific << j << endl;
cout << "f (fixed): " << fixed << f << endl;
cout << "g (fixed): " << fixed << g << endl;
cout << "h (fixed): " << fixed << h << endl;
cout << "i (fixed): " << fixed << i << endl;
cout << "j (fixed): " << fixed << j << endl;
cout << "f (precision 10 and scientific): " << setprecision(10) << scientific << f << endl;
cout << "g (precision 10 and scientific): " << setprecision(10) << scientific << g << endl;
cout << "h (precision 10 and scientific): " << setprecision(10) << scientific << h << endl;
cout << "i (precision 10 and scientific): " << setprecision(10) << scientific << i << endl;
cout << "f (precision 10 and fixed): " << setprecision(10) << fixed << f << endl;
cout << "g (precision 10 and fixed): " << setprecision(10) << fixed << g << endl;
cout << "h (precision 10 and fixed): " << setprecision(10) << fixed << h << endl;
cout << "i (precision 10 and fixed): " << setprecision(10) << fixed << i << endl;
cout << "f (precision 10, scientific and uppercase): " << setprecision(10) << scientific << uppercase << f << endl;
cout << "g (precision 10, scientific and uppercase): " << setprecision(10) << scientific << uppercase << g << endl;
cout << "h (precision 10, scientific and uppercase): " << setprecision(10) << scientific << uppercase << h << endl;
cout << "i (precision 10, scientific and uppercase): " << setprecision(10) << scientific << uppercase << i << endl;
return 0;
}
Explanation
The provided C++ code is a demonstration of how to use and display floating point numbers in different formats using the iostream
and iomanip
libraries.
Initially, five floating point variables f
, g
, h
, i
, and j
are declared and assigned different values. These variables are then printed to the console using the cout
object.
float f = 3.14159;
// ... other variable declarations
cout << "f: " << f << endl;
// ... other print statements
The code then uses the setprecision
function from the iomanip
library to control the number of digits displayed when the floating point numbers are printed. The setprecision(10)
call sets the precision to 10 digits.
cout << "f (precision 10): " << setprecision(10) << f << endl;
// ... other print statements
The scientific
and fixed
manipulators are then used to change the format in which the floating point numbers are displayed. The scientific
manipulator causes the number to be displayed in scientific notation, while the fixed
manipulator causes the number to be displayed in fixed-point notation.
cout << "f (scientific): " << scientific << f << endl;
// ... other print statements
cout << "f (fixed): " << fixed << f << endl;
// ... other print statements
Finally, the uppercase
manipulator is used in conjunction with the scientific
manipulator to display the numbers in scientific notation with an uppercase ‘E’.
cout << "f (precision 10, scientific and uppercase): " << setprecision(10) << scientific << uppercase << f << endl;
// ... other print statements
In summary, this code demonstrates various ways to control the display of floating point numbers in C++.
Output
f: 3.14159
g: 0.4
h: 0.0314
i: 314
j: 314
f (precision 10): 3.141590118
g (precision 10): 0.400000006
h (precision 10): 0.03139999881
i (precision 10): 314
j: 314
f (scientific): 3.1415901184e+00
g (scientific): 4.0000000596e-01
h (scientific): 3.1399998814e-02
i (scientific): 3.1400000000e+02
j (scientific): 3.1400000000e+02
f (fixed): 3.1415901184
g (fixed): 0.4000000060
h (fixed): 0.0313999988
i (fixed): 314.0000000000
j (fixed): 314.0000000000
f (precision 10 and scientific): 3.1415901184e+00
g (precision 10 and scientific): 4.0000000596e-01
h (precision 10 and scientific): 3.1399998814e-02
i (precision 10 and scientific): 3.1400000000e+02
f (precision 10 and fixed): 3.1415901184
g (precision 10 and fixed): 0.4000000060
h (precision 10 and fixed): 0.0313999988
i (precision 10 and fixed): 314.0000000000
f (precision 10, scientific and uppercase): 3.1415901184E+00
g (precision 10, scientific and uppercase): 4.0000000596E-01
h (precision 10, scientific and uppercase): 3.1399998814E-02
i (precision 10, scientific and uppercase): 3.1400000000E+02
Process finished with exit code 0```
Comment types in C++
We are demontrating single line and multi line comments in C++
#include <iostream>
using namespace std;
// we will demonstrate the use of comments in this program
int main() {
// This is a single line comment
cout << "Hello, World!" << endl; // This is also a single line comment
/* This is a multi-line comment
This is a multi-line comment
This is a multi-line comment
*/
return 0;
}
In the above code, we have used single-line comments and multi-line comments.
Single-line comments start with // and end at the end of the line.
Multi-line comments start with /* and end with */. Comments are ignored by the compiler and are used to make the code more readable and understandable. Output: Hello, World! In the above code, we have used comments to explain the code. You can also use comments to disable a part of the code.
What are the keywords in C++
C++ has a set of reserved keywords that have special meanings to the compiler. These keywords cannot be used as identifiers (names for variables, functions, classes, etc.). Here is a list of C++ keywords:
alignas
alignof
and
and_eq
asm
auto
bitand
bitor
bool
break
case
catch
char
char8_t
char16_t
char32_t
class
compl
concept
const
consteval
constexpr
constinit
const_cast
continue
co_await
co_return
co_yield
decltype
default
delete
do
double
dynamic_cast
else
enum
explicit
export
extern
false
float
for
friend
goto
if
inline
int
long
mutable
namespace
new
noexcept
not
not_eq
nullptr
operator
or
or_eq
private
protected
public
register
reinterpret_cast
requires
return
short
signed
sizeof
static
static_assert
static_cast
struct
switch
template
this
thread_local
throw
true
try
typedef
typeid
typename
union
unsigned
using
virtual
void
volatile
wchar_t
while
xor
xor_eq
Please note that some of these keywords are only available in newer versions of C++.
Common data types in C++
C++ supports several different data types. Here are some of the most common ones:
Integer types (
int
): These are used to store whole numbers. The size of anint
is usually 4 bytes (32 bits), and it can store numbers from -2,147,483,648 to 2,147,483,647.Floating-point types (
float
,double
): These are used to store real numbers (numbers with fractional parts). Afloat
typically occupies 4 bytes of memory, while adouble
occupies 8 bytes.Character types (
char
): These are used to store individual characters. Achar
occupies 1 byte of memory and can store any character in the ASCII table.Boolean type (
bool
): This type is used to store eithertrue
orfalse
.String type (
std::string
): This is used to store sequences of characters, or strings. It’s not a built-in type, but is included in the C++ Standard Library.Array types: These are used to store multiple values of the same type in a single variable.
Pointer types: These are used to store memory addresses.
User-defined types (classes, structs, unions, enums): These allow users to define their own data types. Each of these types has its own characteristics and uses, and understanding them is fundamental to programming in C++.
Create variables and assign values to them in C++
In C++, you can create variables and assign values to them in the following way:
Declare a variable by specifying its type followed by the variable name. For example,
int myVariable;
declares a variable namedmyVariable
of typeint
.Assign a value to the variable using the assignment operator
=
. For example,myVariable = 5;
assigns the value5
tomyVariable
. Here is an example of creating different types of variables and assigning values to them:
// Include the necessary libraries
#include <iostream> // for input/output operations
#include <string> // for using string data type
// Main function where the program starts execution
int main() {
// Declare an integer variable
int myInt;
// Assign a value to the integer variable
myInt = 10;
// Declare a double variable and assign a value to it
double myDouble = 20.5;
// Declare a character variable and assign a value to it
char myChar = 'A';
// Declare a string variable and assign a value to it
std::string myString = "Hello, World!";
// Declare a boolean variable and assign a value to it
bool myBool = true;
// End of main function, return 0 to indicate successful execution
return 0;
}
Explanation
The provided code is a simple C++ program that demonstrates the declaration and initialization of variables of different types.
The program begins by including necessary libraries. The iostream
library is included for input/output operations, and the string
library is used to handle string data types.
#include <iostream> // for input/output operations
#include <string> // for using string data type```
The `main` function is where the program starts execution. Inside this function, several variables of different types are declared and initialized.
```cpp
int main() {
...
return 0;
}
An integer variable myInt
is declared and then assigned a value of 10
.
int myInt;
myInt = 10;
A double variable myDouble
is declared and assigned a value of 20.5
in the same line.
double myDouble = 20.5;
Similarly, a character variable myChar
is declared and assigned the character ‘A’.
char myChar = 'A';
A string variable myString
is declared and assigned the string “Hello, World!”.
std::string myString = "Hello, World!";
Lastly, a boolean variable myBool
is declared and assigned the value true
.
bool myBool = true;
The function ends with a return 0;
statement, indicating successful execution of the program. As it stands, the program does not produce any output. It simply demonstrates how to declare and initialize variables of different types in C++.
Correct and incorrect variable naming conventions in C++
This program example demonstrates the correct and incorrect variable naming conventions in C++
/**
* @file main.cpp
* @brief This program demonstrates the correct and incorrect variable naming conventions in C++.
*/
#include <iostream>
using namespace std;
int main() {
// Correct variable naming conventions
int number; ///< Variable names can start with a letter
int Number; ///< Variable names are case sensitive
string NUMBER; ///< Variable names can be in uppercase
float number1; ///< Variable names can contain numbers
bool number_1; ///< Variable names can contain underscores
int number_1_; ///< Variable names can end with an underscore
int _number; ///< Variable names can start with an underscore
int _number_; ///< Variable names can start and end with an underscore
int _1number; ///< Variable names can contain numbers after an underscore
int _1_number; ///< Variable names can contain underscores and numbers
int _1_number_; ///< Variable names can start and end with an underscore and contain numbers
int number1_; ///< Variable names can end with a number and an underscore
// Incorrect variable naming conventions
// int 1number; // Variable names cannot start with a number
// int number$; // Variable names cannot contain special characters
// int number one; // Variable names cannot contain spaces
// int number-one; // Variable names cannot contain special characters
// int number@; // Variable names cannot contain special characters
// int number#; // Variable names cannot contain special characters
return 0;
}
Explanation
The provided C++ code is a simple program designed to illustrate the correct and incorrect conventions for naming variables in C++.
The program begins with the inclusion of the iostream
library, which is used for input/output operations. The using namespace std;
statement is used to avoid having to prefix standard library components with std::
.
#include <iostream>
using namespace std;
The main
function is where the execution of the program starts. Inside this function, several variables are declared to demonstrate the correct naming conventions in C++.
int number; ///< Variable names can start with a letter
int Number; ///< Variable names are case sensitive
string NUMBER; ///< Variable names can be in uppercase```
In C++, variable names can start with a letter, are case sensitive, and can be in uppercase. They can also contain numbers and underscores. For example, `number1`, `number_1`, and `number_1_` are all valid variable names.
```cpp
float number1; ///< Variable names can contain numbers
bool number_1; ///< Variable names can contain underscores
int number_1_; ///< Variable names can end with an underscore```
Variable names can also start with an underscore, and they can contain numbers after an underscore. For instance, `_number`, `_1number`, and `_1_number` are all valid variable names.
```cpp
int _number; ///< Variable names can start with an underscore
int _1number; ///< Variable names can contain numbers after an underscore
int _1_number; ///< Variable names can contain underscores and numbers
The program also includes commented-out lines of code that demonstrate incorrect variable naming conventions. In C++, variable names cannot start with a number, contain special characters, or contain spaces.
// int 1number; // Variable names cannot start with a number
// int number$; // Variable names cannot contain special characters
// int number one; // Variable names cannot contain spaces
Finally, the main
function returns 0, indicating successful execution of the program.
The use of octal, binary and hexadecimal literals in C++
This function defines three integer variables, each initialized with a different type of literal (hexadecimal, octal, binary). It then prints the values of these variables to the console.
/**
* @file main.cpp
* @author ibrahim
* @date 30-06-2024
* @brief This program demonstrates the use of octal, binary and hexadecimal literals in C++.
*/
#include <iostream>
using namespace std;
/**
* @brief The main function of the program.
*
* This function defines three integer variables,
* each initialized with a different type of literal (hexadecimal, octal, binary).
* It then prints the values of these variables to the console.
*
* @return int Returns 0 upon successful execution.
*/
int main() {
int a = 0x1A; ///< @brief Integer variable 'a' initialized with a hexadecimal literal. The value of 'a' is 26.
int b = 032; ///< @brief Integer variable 'b' initialized with an octal literal. The value of 'b' is 26.
int c = 0b1101; ///< @brief Integer variable 'c' initialized with a binary literal. The value of 'c' is 13.
cout << "Hexadecimal literal: " << a << endl; ///< Prints the value of 'a' to the console.
cout << "Octal literal: " << b << endl; ///< Prints the value of 'b' to the console.
cout << "Binary literal: " << c << endl; ///< Prints the value of 'c' to the console.
return 0; ///< Returns 0 upon successful execution.
}
Explanation
The provided C++ code is a simple program that demonstrates the use of different types of integer literals in C++. It includes hexadecimal, octal, and binary literals.
The program begins by including the iostream
library, which provides facilities for input/output operations. The using namespace std;
statement is used to avoid prefixing the cout
and endl
with std::
.
#include <iostream>
using namespace std;
The main
function is the entry point of the program. Inside this function, three integer variables a
, b
, and c
are declared and initialized with a hexadecimal, octal, and binary literal, respectively.
int a = 0x1A;
int b = 032;
int c = 0b1101;
In C++, hexadecimal literals are prefixed with 0x
or 0X
, octal literals are prefixed with 0
, and binary literals are prefixed with 0b
or 0B
. The hexadecimal literal 0x1A
and the octal literal 032
both represent the decimal number 26, while the binary literal 0b1101
represents the decimal number 13.
The program then uses cout
to print the values of these variables to the console. The endl
manipulator is used to insert a new line.
cout << "Hexadecimal literal: " << a << endl;
cout << "Octal literal: " << b << endl;
cout << "Binary literal: " << c << endl;
Finally, the main
function returns 0 to indicate successful execution of the program.
return 0;
This code is a good demonstration of how different types of integer literals can be used in C++.
C++ int variable with different defining ways
We are explaining the use of int variables with different defining ways
// Creator: ibrahim (30.06.2024 00:00)
/**
* @file main.cpp
* @brief Demonstrates the use of int with different defining ways in C++
*/
#include <iostream>
/**
* @brief Main function of the program
*
* Defines four integer variables in different ways and prints their values.
*
* @return int Returns 0 upon successful execution
*/
int main() {
int numberOne = 5; ///< 5 is a decimal number by default in C++
int numberTwo = 1111111111; ///< 1111111111 is a decimal number by default in C++
int numberThree = 1'111'111'111; ///< 1'111'111'111 is a decimal number by default in C++
int numberFour = -1'111'111'111; ///< -1'111'111'111 is a decimal number by default in C++
std::cout << "numberOne: " << numberOne << std::endl;
std::cout << "numberTwo: " << numberTwo << std::endl;
std::cout << "numberThree: " << numberThree << std::endl;
std::cout << "numberFour: " << numberFour << std::endl;
return 0;
}
The provided C++ code is a simple demonstration of how to define integer variables in different ways. It includes the use of single quotes as digit separators for readability, which is a feature available in C++14 and later versions.
The code begins by including the iostream
library, which provides facilities for input/output operations.
#include <iostream>
In the main
function, four integer variables are defined: numberOne
, numberTwo
, numberThree
, and numberFour
. Each of these variables is assigned a different integer value.
int numberOne = 5;
int numberTwo = 1111111111;
The third and fourth variables, numberThree
and numberFour
, are defined using digit separators (single quotes) for better readability. This does not change the value of the integer; it’s purely for making the code easier to read.
int numberThree = 1'111'111'111;
int numberFour = -1'111'111'111;
The code then uses std::cout
to print the values of these variables to the console. Each variable is printed on a new line.
std::cout << "numberOne: " << numberOne << std::endl;
Finally, the main
function returns 0, indicating successful execution of the program.
C++ Hello World with explanaition
We tried to explain the most simple C++ program for beginners.
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
The provided code is a simple C++ program that prints “Hello, World!” to the console.
The first line #include <iostream>
is a preprocessor directive that includes the iostream standard library. This library allows for input/output operations. In this case, it’s used to output text to the console.
The next part is the main
function. In C++, execution of the program begins with the main
function, regardless of where the function is located within the code. The main
function is defined with the syntax int main()
. The int
before main
indicates that the function will return an integer value.
Inside the main
function, there’s a statement std::cout << "Hello, World!" << std::endl;
. Here, std::cout
is an object of the ostream
class from the iostream
library. The <<
operator is used to send the string “Hello, World!” to the cout
object, which then outputs it to the console. The std::endl
is a manipulator that inserts a newline character and flushes the output buffer.
Finally, the main
function ends with return 0;
. This statement causes the program to exit and return a status of 0 to the operating system. In the context of the main
function, returning 0 typically indicates that the program has run successfully without any errors.
C++ Defining a Pointer and changing its value
In this example, we define a pointer and show how to view and change its value.
/**
* @brief Main function that demonstrates pointer manipulation.
*
* This function initializes an integer variable `value` with the value 10.
* It then creates a pointer `pointer` that points to the memory address of `value`.
* The program prints the initial value of `value`, its address,
* and the value pointed to by `pointer`.
*
* The program then updates the value pointed to by `pointer` to 20.
* Finally, it prints the new value of `value`.
*
* @return 0 indicating successful execution of the program
*/
#include <iostream>
using namespace std;
int main() {
int value = 10; // Initialize an integer variable with the value 10
int* pointer = &value; // Create a pointer that points to the memory address of value
cout << "Initial value: " << value << endl; // Print the initial value of value
cout << "Address of value: " << &value << endl; // Print the memory address of value
cout << "Value pointed to by pointer: " << *pointer << endl; // Print the value pointed to by pointer
*pointer = 20; // Update the value pointed to by pointer to 20
cout << "New value of value: " << value << endl; // Print the new value of value
return 0; // Return 0 indicating successful execution of the program
}
Factorial calculation with C++ do-while loop
In this example, we show how to calculate factorial using the do while loop.
#include <iostream>
using namespace std;
int calculateFactorial(int number) {
int result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
return result;
}
int main() {
int inputNumber;
char exitKey;
do {
cout << "Enter a number between 1 and 10: ";
cin >> inputNumber;
if (inputNumber < 1) {
cout << "Number must be greater than 0. ";
} else if (inputNumber > 10) {
cout << "Number must be less than or equal to 10. ";
} else {
int factorial = calculateFactorial(inputNumber);
cout << "Result: " << factorial << endl;
}
cout << "Press 'h' to exit, any other key to continue: ";
cin >> exitKey;
} while (exitKey != 'h');
return 0;
}
C++ Example calculating the factorial of the entered number
In this example, we show how to calculate the factorial of the entered number with the help of a function.
#include <iostream>
using namespace std;
int factorial(int num) {
int result = 1;
for (int i = 2; i <= num; i++) {
result *= i;
}
return result;
}
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
int factorialResult = factorial(number);
cout << "Factorial: " << factorialResult << endl;
return 0;
}
C++ adding int and float variables
In this example, we show how to find the sum of 2 variables of type int and float.
#include <iostream>
int main() {
int firstNumber = 11;
float secondNumber = 12.8;
float sum = firstNumber + secondNumber;
std::cout << "Sum: " << sum << std::endl;
return 0;
}
C++ Code example to convert Fahrenheit temperature to Celsius
In this example, the entered Fahrenheit temperature value is converted to Celsius value with the help of a function.
#include <iostream>
#include <iomanip>
#include <limits>
float temperatureConversion(const float temperatureInFahrenheit) {
constexpr float conversionFactor = 5.0 / 9.0;
return (temperatureInFahrenheit - 32) * conversionFactor;
}
int main() {
float fahrenheitTemperature;
std::cout << "Enter the Fahrenheit temperature: ";
std::cin >> fahrenheitTemperature;
float celsiusTemperature = temperatureConversion(fahrenheitTemperature);
std::cout << std::fixed << std::setprecision(std::numeric_limits<float>::digits10) << "Celsius value: " <<
celsiusTemperature << std::endl;
return 0;
}
Printing int, float and string values with printf in C++
This code defines a main function where the int and float variables are constants and the text variable is not. Prints the values number, realNumber, and text and then returns 0.
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main() {
constexpr int number = 123;
constexpr float realNumber = 3.146;
string text = "Hello World";
printf("Number: %d ", number);
printf("Pi value: %.2f ", realNumber);
printf("Text: %s ", text.c_str());
return 0;
}
C++ 2 string variable concatenation
In this article, we show an example of combining 2 string variables.
#include <iostream>
#include <string>
int main() {
std::string firstString = "prs";
std::string secondString = "def";
std::string result;
result = firstString + secondString;
std::cout << result << std::endl;
return 0;
}
Combining 2 variables of type char in C++
In this example, you can see how to combine 2 char variables with a length of 50 characters using the strcat method.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
constexpr size_t bufferSize = 50;
char firstString[bufferSize] = "abc";
char secondString[bufferSize] = "def";
cout << "First string: " << firstString << ' ';
cout << "Second string: " << secondString << ' ';
strcat(firstString, secondString);
cout << "Concatenated string: " << firstString << ' ';
return 0;
}
Finding whether a number is positive or negative with C++
In this example, we check whether the number entered from the keyboard is positive, negative or zero by using if-else if.
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Please enter a number: ";
cin >> number;
if (number > 0) {
cout << "Number is positive";
} else if (number < 0) {
cout << "Number is negative";
} else {
cout << "Number is zero";
}
return 0;
}
C++ Nested if statement
In this article, we share an example showing C++ nested if statement.
#include <iostream>
using namespace std;
int main() {
/* nested if else statement */
int a;
cout << "Enter a positive integer number: ";
cin >> a;
if (a < 20) {
cout << "a is less than 20 ";
if (a < 10)
cout << "a is less than 10 ";
else
cout << "a is not less than 10 ";
} else {
if (a == 20) {
cout << "a is equal to 20 ";
} else
cout << "a is greater than 20 ";
}
return 0;
}
C++ Cascade if else statement
You can see the usage of cascade if-else statement example below.
#include <iostream>
using namespace std;
int main() {
/* cascade if else statement */
int a;
cout << "Enter a positive integer number: ";
cin >> a;
if (a < 20) {
cout << "a is less than 20 ";
} else if (a == 20) {
cout << "a is equal to 20 ";
} else {
cout << "a is greater than 20 ";
}
return 0;
}
C++ if else statement
In this article, you can examine the use of C++ if else statement.
#include <iostream>
using namespace std;
int main() {
/* if else statement */
int a;
cout << "Enter a positive integer number: ";
cin >> a;
if (a < 20) {
cout << "a is less than 20 ";
} else {
cout << "a is not less than 20 ";
}
return 0;
}