C++ Level 2 Tasks: Solutions And Explanations

by Alex Johnson 46 views

This article provides detailed solutions and explanations for a collection of Level 2 C++ tasks. Each task focuses on fundamental programming concepts, including conditional statements and input/output operations. Let's dive into each problem and understand its solution.

Task 1: Finding the Maximum of Two Numbers

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    int a, b;
    cin >> a >> b;
    if (a > b){
        cout << a;
    }
    else
        cout << b;

    return 0;
}

In this C++ program, our main goal is to determine the larger of two input numbers. We begin by including the necessary header files: iostream for input and output operations and algorithm which although not explicitly used here, is often included as a standard practice in C++ programs for its rich set of functions including max() that would have been an alternative to finding the max. The using namespace std; line simplifies our code by allowing us to use elements from the standard namespace without explicitly prefixing them with std::. Inside the main() function, which serves as the entry point of our program, we declare two integer variables, a and b, to store the input numbers. We then use cin >> a >> b; to read these numbers from the user's input. Following this, we employ an if statement to compare the values of a and b. If a is greater than b, we print the value of a to the console using cout << a;. Otherwise, we print the value of b using cout << b;. This ensures that the larger of the two numbers is always displayed. Finally, the return 0; statement indicates that the program has executed successfully. This simple yet effective program demonstrates the use of conditional statements to make decisions based on input values, a fundamental concept in programming. Understanding how to compare values and execute different code paths based on those comparisons is crucial for building more complex and intelligent applications. This task provides a solid foundation for further exploration of C++ programming.

Task 2: Determining the Sign of a Number

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    int a;
    cin >> a;
    if (a > 0){
        cout << "musbət";
    }
    else if(a < 0){
        cout << "menfi";
    }
    else
        cout << "sifir";

    return 0;
}

This C++ code snippet checks whether a given number is positive, negative, or zero. First, we include the iostream header for input and output, and algorithm for good measure. Then, the program prompts the user to enter an integer, which is stored in the variable a. After receiving the input, the code uses a series of if-else if-else statements to determine the sign of the number. If a is greater than 0, the program outputs "musbət" (positive in Azerbaijani). If a is less than 0, it outputs "menfi" (negative). If neither of these conditions is met, it means a must be 0, so the program outputs "sifir" (zero). The return 0; statement at the end indicates that the program has completed successfully. This task is a basic example of using conditional statements to classify numerical input. The core concept demonstrated here is the use of conditional logic to handle different scenarios based on the value of a variable. The if-else if-else structure allows the program to test multiple conditions in sequence, ensuring that the correct output is produced for any given input. This type of conditional checking is fundamental in many programming tasks, such as data validation, decision-making algorithms, and control flow management. Mastering this concept is essential for anyone learning to program in C++ or any other language. The Azerbaijani words in the cout statements could easily be replaced with their English counterparts to make the code more universally understandable, but the underlying logic remains the same.

Task 3: Finding the Maximum of Three Numbers

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    int a, b, c;
    cin >> a >> b >> c;
    if(a > b && a > c){
        cout << a;
    }
    else if(b > a && b > c){
        cout << b;
    }
    else
        cout << c;
}

This C++ program efficiently identifies the largest among three input numbers. We start by including the iostream header for input/output operations and algorithm for using function max(). The program takes three integer inputs, a, b, and c, using cin. The program uses a series of if and else if statements to determine the largest number. The first if statement checks if a is greater than both b and c. If it is, then a is the largest, and the program prints a. The else if statement checks if b is greater than both a and c. If it is, then b is the largest, and the program prints b. If neither of the above conditions is true, then c must be the largest, and the program prints c. The use of && (the logical AND operator) ensures that both conditions within each if statement must be true for that statement to execute. This approach ensures that the program correctly identifies the largest of the three numbers. This task reinforces the concept of conditional logic and comparison operators in C++. Alternatives to solving this task include using nested if statements or the std::max function (from the <algorithm> header) to compare two numbers at a time. However, the presented solution is straightforward and easy to understand, making it suitable for beginners learning C++. Understanding how to compare multiple values and determine the maximum is a valuable skill in programming, with applications in sorting algorithms, data analysis, and optimization problems. This program serves as a good foundation for understanding more complex algorithms that involve finding maximum or minimum values within datasets.

Task 4: Checking if a Number is Even or Odd

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    int a;
    cin >> a;
    if(a % 2 == 0){
        cout << "cutdur";
    }
    else
        cout << "tekdir";
}

This C++ program determines whether an input number is even or odd. The code starts by including the iostream for input and output and algorithm libraries. The program prompts the user to enter an integer, which is stored in the variable a. The core logic of the program lies in the if statement. The expression a % 2 calculates the remainder when a is divided by 2. If the remainder is 0, it means that a is divisible by 2, and therefore, it is an even number. In this case, the program outputs "cutdur" (even in Azerbaijani). If the remainder is not 0, it means that a is not divisible by 2, and therefore, it is an odd number. In this case, the program outputs "tekdir" (odd). This simple program demonstrates the use of the modulo operator (%) to determine the divisibility of a number. Understanding the concept of even and odd numbers is fundamental in computer science and has applications in various algorithms and data structures. The modulo operator is a powerful tool for performing various tasks such as checking divisibility, generating patterns, and implementing cryptographic algorithms. The Azerbaijani words in the cout statements could be replaced with English words to make the code more universal. This program illustrates a basic but essential concept in programming: using arithmetic operations to make decisions and classify data.

Task 5: Grading System Based on Marks

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    int a;
    cin >> a;
    if(a >= 0 && a <= 50){
        cout << "F";
    }
    else if (a > 50 && a <= 60){
        cout << "E";
    }
    else if (a > 60 && a <= 70){
        cout << "D";
    }
    else if (a > 70 && a <= 80){
        cout << "C";
    }
    else if (a > 80 && a <= 90){
        cout << "B";
    }
    else if (a > 90 && a <= 100){
        cout << "A";
    }
}

This C++ program implements a grading system based on numerical marks. It begins by including the necessary header files (iostream for input and output operations, algorithm for using functions). The program prompts the user to enter a numerical grade, which is stored in the integer variable a. The code then uses a series of else if statements to determine the corresponding letter grade. The first if statement checks if a is between 0 and 50 (inclusive). If it is, the program outputs "F". Each subsequent else if statement checks if a falls within a specific range, and if it does, the corresponding letter grade is outputted. For example, if a is greater than 50 and less than or equal to 60, the program outputs "E". This process continues until a matching range is found. If none of the conditions are met, no output is produced (though ideally, an error message would be displayed for invalid input). This task demonstrates the use of conditional statements to map numerical values to categorical values. This type of mapping is commonly used in various applications, such as data analysis, decision-making systems, and user interface design. The program also highlights the importance of considering all possible input values and handling them appropriately. In a real-world scenario, it would be beneficial to add error handling to ensure that the input is within the valid range (0-100) and to provide a default output for invalid inputs. The code could also be made more readable and maintainable by using a lookup table (e.g., an array or a map) to store the grade ranges and their corresponding letter grades.

Task 6: Determining the Season Based on Month Number

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int ay;
    cout << "Ay nomresini daxil edin (1-12): ";
    cin >> ay;

    if (ay == 12 || ay == 1 || ay == 2)
        cout << "Qis fesli";
    else if (ay >= 3 && ay <= 5)
        cout << "Yaz fesli";
    else if (ay >= 6 && ay <= 8)
        cout << "Yay fesli";
    else if (ay >= 9 && ay <= 11)
        cout << "Payiz fesli";
    else
        cout << "Yanlis ay nomresi";

    return 0;
}

This C++ program determines the season corresponding to a given month number. It starts by including the iostream header for input and output and algorithm for using functions. The program prompts the user to enter a month number between 1 and 12, which is stored in the integer variable ay. The code uses a series of if and else if statements to determine the season. The first if statement checks if ay is 12, 1, or 2, which correspond to December, January, and February, respectively. If any of these conditions are true, the program outputs "Qis fesli" (Winter in Azerbaijani). The else if statements check if ay falls within the ranges for Spring (3-5), Summer (6-8), and Autumn (9-11), respectively. If ay does not fall within any of these ranges, the else statement is executed, and the program outputs "Yanlis ay nomresi" (Invalid month number). This task demonstrates the use of conditional statements to map numerical values to categorical values, specifically, month numbers to seasons. This type of mapping is useful in various applications, such as calendar programs, weather forecasting, and data analysis. The program also highlights the importance of handling invalid inputs. In a real-world scenario, it would be beneficial to add input validation to ensure that the month number is within the valid range (1-12). The Azerbaijani words in the cout statements could be replaced with English words to make the code more universal. Additionally, the code could be improved by using a switch statement or a lookup table to make it more readable and maintainable.

Task 7: Checking if a Year is a Leap Year

#include <iostream>
#include <algorithm>
using namespace std;
int main(){
    int a;
    cin>>a;
    if (a%4==0 && a%100!=0){
        cout<<"artiq ildir";
    }
    else if (a%400==0){
        cout<<"artiq ildir";
    }

}

This C++ program checks if a given year is a leap year. The program includes the standard iostream and algorithm libraries. The program prompts the user to enter a year, which is stored in the integer variable a. The code then uses conditional statements to determine if the year is a leap year. According to the Gregorian calendar, a year is a leap year if it is divisible by 4, unless it is also divisible by 100. However, if a year is divisible by 400, it is a leap year. The first if statement checks if a is divisible by 4 and not divisible by 100. If both conditions are true, the program outputs "artiq ildir" (leap year in Azerbaijani). The else if statement checks if a is divisible by 400. If it is, the program outputs "artiq ildir". This task demonstrates the use of conditional statements and the modulo operator to implement a rule-based decision. Understanding leap years is essential in various applications, such as calendar programs, date calculations, and financial systems. The program also highlights the importance of understanding the specific rules that govern a particular problem domain. The Azerbaijani words in the cout statements can be replaced with English words to make the code more universal. Additionally, the code can be improved by adding input validation to ensure that the input is a valid year.

In conclusion, these level 2 C++ tasks provide a solid foundation for understanding basic programming concepts such as conditional statements, input/output operations, and logical operators. By working through these tasks, beginners can gain valuable experience in problem-solving and algorithm design. For more information on C++ programming, you can visit the C++ documentation.