Code Topic Wise C+++
Code Topic Wise C+++
int main() {
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
std::cout << "Sum: " << num1 + num2 << std::endl;
return 0;
}
‘‘‘
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
if (num > 0) {
std::cout << "Positive" << std::endl;
} else if (num < 0) {
std::cout << "Negative" << std::endl;
} else {
std::cout << "Zero" << std::endl;
}
return 0;
}
‘‘‘
int main() {
int nums[5] = {1, 2, 3, 4, 5};
std::cout << "Element at index 2: " << nums[2] << std::endl;
return 0;
}
‘‘‘
int main() {
int num1 = 5;
int num2 = 7;
int sum = add(num1, num2);
std::cout << "Sum: " << sum << std::endl;
return 0;
}
‘‘‘
void display() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "GPA: " << gpa << std::endl;
}
};
int main() {
Student student1;
student1.name = "John";
student1.age = 20;
student1.gpa = 3.5;
student1.display();
return 0;
}
‘‘‘
int main() {
int num1 = 10;
int* ptr1 = &num1;
std::cout << "Value of num1: " << *ptr1 << std::endl;
int num2 = 20;
int& ref1 = num2;
std::cout << "Value of num2: " << ref1 << std::endl;
*ptr1 = 30;
std::cout << "Value of num1 after update: " << num1 << std::endl;
return 0;
}
‘‘‘
int main() {
int* ptr = new int;
*ptr = 42;
std::cout << "Value at pointer: " << *ptr << std::endl;
return 0;
}
int main() {
std::ofstream outfile("output.txt"); // Create an output file stream
if (outfile.is_open()) {
outfile << "Hello, world!" << std::endl;
outfile.close(); // Close the output file stream
} else {
std::cout << "Failed to open file for writing!" << std::endl;
}
return 0;
}
‘‘‘
int main() {
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
try {
if (num2 == 0) {
throw "Division by zero!";
} else {
std::cout << "Result: " << num1 / num2 << std::endl;
}
} catch (const char* error) {
std::cout << "Error: " << error << std::endl;
}
return 0;
}
‘‘‘
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9, 3};
Note: These code snippets are intended to be simple examples and may not cover all edge cases or error
handling. They are meant to provide a basic understanding of the concepts covered in each module. It’s
always a good practice to thoroughly understand the concepts and write robust code in real-world scenari
os.