#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
// Conditional statements
if (n == 1) {
cout << "one";
} else if (n == 2) {
cout << "two";
} else if (n == 3) {
cout << "three";
} else if (n == 4) {
cout << "four";
} else if (n == 5) {
cout << "five";
} else if (n == 6) {
cout << "six";
} else if (n == 7) {
cout << "seven";
} else if (n == 8) {
cout << "eight";
} else if (n == 9) {
cout << "nine";
} else {
cout << "Greater than 9";
}
return 0;
}
Let's break down the code and explain each part:
#include
using namespace std;: This statement allows us to use the standard library functions without explicitly specifying the namespace (e.g., cout, cin).
int main(): This is the main function of the program. It is the entry point for execution.
int n;: We declare a variable n to store the input value.
cin >> n;: This statement reads an input value from the user and assigns it to the variable n using the >> operator.
if (n == 1) { cout << "one"; }: This is an example of an if statement. It checks if n is equal to 1. If the condition is true, it executes the code block inside the curly braces, which in this case outputs the string "one" using cout.
else if (n == 2) { cout << "two"; }: This is an example of an else if statement. It checks if n is equal to 2. If the condition is true, it executes the code block inside the curly braces, which in this case outputs the string "two" using cout.
The program continues with a series of else if statements to check for other values of n (3 to 9) and outputs the corresponding strings based on the conditions.
else { cout << "Greater than 9"; }: This is the final else statement. If none of the previous conditions are true, it executes the code block inside the curly braces, which in this case outputs the string "Greater than 9" using cout.
return 0;: This line indicates that the program execution is successful and returns the value 0 to the operating system.
When you run this program, it will prompt the user to enter a value. Based on the value entered, the program will output the corresponding string. If the value is not between 1 and 9, it will output "Greater than 9".
To use this code in HackerRank's "Conditional Statements" problem, you can copy and paste it into the editor and submit it. The program will prompt the user for input, and the output will be displayed in the output window or terminal, depending on the HackerRank environment.
Remember to include the necessary header file (#include