cpp practice questions
Sure! Here are some C++ practice questions along with explanations for each step:
Question 1: Print Hello World
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
Explanation:
- We start by including the iostream library, which provides functionality for input and output operations.
- The main()
function is the entry point of our program.
- Inside the main()
function, we use the std::cout
object to print the string "Hello World!" to the console.
- Finally, we return 0 to indicate successful execution of the program.
Question 2: Calculate the sum of two numbers
#include <iostream>
int main() {
int num1, num2, sum;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
sum = num1 + num2;
std::cout << "Sum = " << sum;
return 0;
}
Explanation:
- We include the iostream library to use the input/output stream objects.
- Inside the main()
function, we declare three integer variables: num1
, num2
, and sum
.
- We prompt the user to enter two numbers using std::cout
.
- The user inputs the numbers, which are then stored in num1
and num2
using std::cin
.
- We calculate the sum of num1
and num2
and store it in the sum
variable.
- Finally, we use std::cout
to display the sum to the console.
Question 3: Find the maximum of three numbers
#include <iostream>
int main() {
int num1, num2, num3, max;
std::cout << "Enter three numbers: ";
std::cin >> num1 >> num2 >> num3;
max = (num1 > num2) ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
std::cout << "Maximum number = " << max;
return 0;
}
Explanation:
- We include the iostream library for input/output operations.
- Inside the main()
function, we declare four integer variables: num1
, num2
, num3
, and max
.
- We prompt the user to enter three numbers using std::cout
.
- The user inputs the numbers, which are stored in num1
, num2
, and num3
using std::cin
.
- We use the ternary operator to compare the three numbers and find the maximum among them.
- Finally, we use std::cout
to display the maximum number to the console.
I hope these explanations help! Let me know if you have any further questions.