Home Backend Development C++ Conditional statement usage and examples in C++

Conditional statement usage and examples in C++

Aug 22, 2023 am 08:25 AM
Conditional statements Example demonstration c++ syntax

C, as a high-level programming language, has a variety of flow control statements to implement the decision-making structure and loop structure of the program. Among them, the conditional statement is one of the most commonly used statements in C programming. It determines the execution path of the program by judging whether the condition is met. This article will introduce the usage and examples of conditional statements in C in detail to help readers better understand and apply this syntax.

1. Basic syntax of conditional statements

Conditional statements in C mainly include three types: if statement, if else statement and switch statement. Their basic syntax is as follows:

  1. if statement:
if (condition)
{
    // 如果条件成立,执行这里的语句
}
Copy after login

The meaning of the if statement is: if the condition is true, execute the statement in {}.

  1. if else statement:
if (condition)
{
    // 如果条件成立,执行这里的语句
}
else
{
    // 如果条件不成立,执行这里的语句
}
Copy after login

The meaning of the if else statement is: if the condition is true, execute the statement in if{}; otherwise, execute else{} statements in.

  1. switch statement:
switch (expression)
{
    case value1:
        // 如果expression等于value1执行这里的语句
        break;

    case value2:
        // 如果expression等于value2执行这里的语句
        break;

    default:
        // 如果expression不等于value1和value2执行这里的语句
        break;
}
Copy after login

The meaning of the switch statement is: according to the value of expression, execute the corresponding case statement. If there is no match, execute default{} statements in. Note that a break statement must be added after each case to jump out of the switch statement.

2. Examples of conditional statements

  1. Usage examples of if statements
#include <iostream>
using namespace std;

int main()
{
    int a = 10;
    if (a > 0)
    {
        cout << "a是正数" << endl;
    }
    else
    {
        cout << "a是负数" << endl;
    }

    return 0;
}
Copy after login

Explanation: Define an integer variable a and assign it a value of 10, If a is greater than 0, output "a is a positive number", otherwise output "a is a negative number".

Output result: a is a positive number.

  1. Usage example of if else statement
#include <iostream>
using namespace std;

int main()
{
    int score = 80;
    if (score >= 90)
    {
        cout << "A" << endl;
    }
    else if (score >= 80)
    {
        cout << "B" << endl;
    }
    else if (score >= 70)
    {
        cout << "C" << endl;
    }
    else if (score >= 60)
    {
        cout << "D" << endl;
    }
    else
    {
        cout << "F" << endl;
    }

    return 0;
}
Copy after login

Explanation: Define an integer variable score and assign it a value of 80. If the score is greater than or equal to 90, output "A"; if If the score is greater than or equal to 80 and less than 90, "B" is output; and so on, if none of the conditions are met, "F" is output.

Output result: B.

  1. Use examples of switch statement
#include <iostream>
using namespace std;

int main()
{
    char grade = 'B';
    switch (grade)
    {
        case 'A':
            cout << "优秀" << endl;
            break;

        case 'B':
            cout << "良好" << endl;
            break;

        case 'C':
            cout << "及格" << endl;
            break;

        default:
            cout << "不及格" << endl;
            break;
    }

    return 0;
}
Copy after login

Explanation: Define a character variable grade and assign it a value of 'B', and execute the corresponding case statement based on its value. If If none of them match, the statement in default{} will be executed and "failed" will be output.

Output result: Good.

3. Notes in practice

  1. If there is only one statement in the if statement or if else statement, the braces can be omitted, but this is not recommended.
  2. Each case in the switch statement must be followed by a break statement, otherwise the next case statement will continue to be executed until a break statement is encountered.
  3. When using conditional statements, pay attention to the consistency of variable types to avoid type conversion errors and unpredictable results.

In short, the conditional statement is one of the very important control structures in the program, which can select different execution paths according to different conditions. Mastering the usage and application of various conditional statements in C can make programming more flexible and efficient.

The above is the detailed content of Conditional statement usage and examples in C++. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Basic elements of Java test classes: detailed analysis and example display Basic elements of Java test classes: detailed analysis and example display Jan 24, 2024 am 10:51 AM

Basic points of Java test classes: detailed analysis and example demonstration In Java development, testing is a crucial link. Testing can ensure the quality and functional correctness of the code and reduce the occurrence of potential bugs. The test class is the key to testing Java code. This article will analyze the basic points of Java test classes in detail and give specific code examples for demonstration. 1. Why test classes are needed During the development process, the code we write needs to go through different tests to verify its correctness. test

C program to print 'even' or 'odd' without using conditional statements C program to print 'even' or 'odd' without using conditional statements Sep 15, 2023 pm 09:21 PM

In this section, we will see how to check whether a number is odd or even without using any conditional statements like <, <=, !=, >, >=, ==. We can easily check if the number is odd or even by using conditional statement. We can divide the number by 2 and check if the remainder is 0. If 0, it is an even number. Otherwise, we can AND the number with 1. If the answer is 0, it is an even number, otherwise it is an odd number. Conditional statements cannot be used here. We'll see two different ways to check whether an odd or even number is present. Method 1 Here we will create an array of strings. The index 0 position will hold "even" and the index 1 position will hold "odd". We can divide numbers

5 essential Python entry example codes 5 essential Python entry example codes Jan 13, 2024 am 08:39 AM

Getting Started with Python Code: 5 Essential Examples for Learning Python is a simple and easy-to-learn high-level programming language that is widely used in data analysis, machine learning, web crawlers and other fields. For beginners, it is important to master some basic Python code. This article will introduce 5 simple example codes to help beginners quickly get started with Python programming. Print Hello,World!print("Hello,World!") This is Python

C++ syntax error: The same constructor signature appears multiple times, how to solve it? C++ syntax error: The same constructor signature appears multiple times, how to solve it? Aug 22, 2023 pm 04:49 PM

C++ is a powerful programming language, but it is inevitable to encounter various problems during use. Among them, the same constructor signature appearing multiple times is a common syntax error. This article explains the causes and solutions to this error. 1. Cause of the error In C++, the constructor is used to initialize the data members of the object when creating the object. However, if the same constructor signature is defined in the same class (that is, the parameter types and order are the same), the compiler cannot determine which constructor to call, causing a compilation error. For example,

Java Email Sending Guide: Easy Getting Started and Practical Demonstrations Java Email Sending Guide: Easy Getting Started and Practical Demonstrations Dec 27, 2023 am 09:17 AM

Java Email Sending Tutorial: Quick Start and Example Demonstration In recent years, with the popularity and development of the Internet, email has become an indispensable part of people's daily life and work. Sending emails through the Java programming language can not only achieve fast and efficient email sending, but also greatly improve work efficiency through automation. This article will introduce how to use the JavaMail library to send emails in Java and demonstrate it through specific code examples. Step 1: Import and configure the JavaMail library first

C++ syntax error: functions cannot be included in class definitions, how to deal with it? C++ syntax error: functions cannot be included in class definitions, how to deal with it? Aug 21, 2023 pm 10:16 PM

C++ is an object-oriented programming language, and the definition of classes is one of its core concepts. When writing classes, we often encounter some syntax errors, including errors that functions cannot be included in class definitions. So how do we deal with this syntax error? Reason Analysis In the C++ language, a class definition can only contain member variables and member functions, and functions cannot be defined directly in the class definition. This is because the functions defined in the class definition are member functions and must be called through an instance of the class. The function defined in the class definition cannot determine the instance to which the function belongs.

Conditional statement usage and examples in C++ Conditional statement usage and examples in C++ Aug 22, 2023 am 08:25 AM

As a high-level programming language, C++ has a variety of flow control statements to implement the decision-making structure and loop structure of the program. Among them, the conditional statement is one of the most commonly used statements in C++ programming. It determines the execution path of the program by judging whether the condition is met. This article will introduce the usage and examples of conditional statements in C++ in detail to help readers better understand and apply this syntax. 1. Basic syntax of conditional statements Conditional statements in C++ mainly include three types: if statement, ifelse statement and switch statement. their basic language

Naive Bayes examples in Python Naive Bayes examples in Python Jun 09, 2023 pm 11:36 PM

Python is a simple and easy-to-learn programming language with a rich set of scientific computing libraries and data processing tools. Among them, the Naive Bayes algorithm, as a classic machine learning method, is also widely used in the Python language. This article will use examples to introduce the usage and steps of Naive Bayes in Python. Introduction to Naive Bayes The Naive Bayes algorithm is a classification algorithm based on Bayes' theorem. Its core idea is to infer new data through the characteristics of the known training data set.

See all articles