Welcome to the C++ Puzzle Questions lesson! In this comprehensive guide, we'll dive into various interesting puzzles designed to strengthen your C++ coding skills. Let's get started!
In this lesson, we'll explore a collection of C++ puzzles that will help you practice and deepen your understanding of the language. We'll cover both beginner and intermediate-level puzzles, ensuring there's something for everyone.
Before we dive into the puzzles, let's ensure you have a development environment set up. You can use tools like Code::Blocks or Visual Studio Code for this purpose.
Write a program that prints "Hello, World!" to the console.
#include <iostream>
int main() {
std::cout << "Hello, World!";
return 0;
}Write a program that takes the length and width of a rectangle as input and calculates and prints its area.
#include <iostream>
int main() {
int length, width;
std::cout << "Enter the length: ";
std::cin >> length;
std::cout << "Enter the width: ";
std::cin >> width;
int area = length * width;
std::cout << "The area of the rectangle is: " << area;
return 0;
}What is the purpose of the `std::cin` statement in the second puzzle?
Write a program that generates a random number between 1 and 100 and asks the user to guess it. The program should provide feedback on whether the user's guess is too high, too low, or correct.
#include <iostream>
#include <ctime>
#include <cstdlib>
int main() {
srand(time(0)); // Ensures random number is different every time program runs
int secretNumber = rand() % 100 + 1;
int userGuess;
bool correctGuess = false;
while (!correctGuess) {
std::cout << "Guess a number between 1 and 100: ";
std::cin >> userGuess;
if (userGuess > secretNumber) {
std::cout << "Too high! Try again.";
} else if (userGuess < secretNumber) {
std::cout << "Too low! Try again.";
} else {
correctGuess = true;
std::cout << "Congratulations! You guessed the number correctly.";
}
}
return 0;
}What is the purpose of the `srand(time(0))` statement in the third puzzle?
Practice makes perfect! Continue solving these puzzles and challenge yourself with more complex ones as your skills grow. Happy coding! š”