【C++语法基础】4.分支和循环结构(✨新手推荐阅读)
前言
在C++编程中,分支和循环结构是控制程序流程的基本工具。分支结构允许程序根据特定条件执行不同的代码块,而循环结构则允许程序重复执行某个代码块。
分支结构
if 语句
if 语句是最基本的分支结构,它根据条件的真假来决定是否执行某段代码。
#include <iostream> int main() { int x = 10; if (x > 5) { std::cout << "x is greater than 5" << std::endl; } return 0;
}
if…else 语句
if…else 语句用于根据条件执行两个不同的代码块中的一个。
#include <iostream> int main() { int x = 3; if (x > 5) { std::cout << "x is greater than 5" << std::endl; } else { std::cout << "x is not greater than 5" << std::endl; } return 0;
}
if…else if…else 语句
if…else if…else 语句用于根据多个条件执行不同的代码块。
#include <iostream> int main() { int x = 3; if (x > 5) { std::cout << "x is greater than 5" << std::endl; } else if (x < 5) { std::cout << "x is less than 5" << std::endl; } else { std::cout << "x is equal to 5" << std::endl; } return 0;
}
三元运算符
三元运算符 ?: 是一个简洁的if-else结构,它返回两个值中的一个,取决于条件的真假。
#include <iostream> int main() { int x = 3; int result = (x > 5) ? x : 5; // 如果x > 5为真,则result为x的值,否则为5 std::cout << "The result is: " << result << std::endl; return 0;
}
循环结构
for 循环
for 循环是一种常用的循环结构,它允许你指定循环的初始化、条件和迭代步骤。
#include <iostream> int main() { for (int i = 0; i < 5; ++i) { std::cout << "i: " << i << std::endl; } return 0;
}
while 循环
while 循环在条件为真时重复执行代码块。
#include <iostream> int main() { int i = 0; while (i < 5) { std::cout << "i: " << i << std::endl; ++i; } return 0;
}
do…while 循环
do…while 循环至少执行一次代码块,然后在条件为真时重复执行。
#include <iostream> int main() { int i = 0; do { std::cout << "i: " << i << std::endl; ++i; } while (i < 5); return 0;
}
循环的嵌套
你可以在循环内部使用另一个循环,这被称为循环的嵌套。
#include <iostream> int main() { for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { std::cout << "i: " << i << ", j: " << j << std::endl; } } return 0;
}
分支和循环结构是编程中非常基础且重要的概念。通过合理地使用这些结构,可以让我们写出的代码更有逻辑性,满足现实的需求。
真心给大家推荐由我主讲的性价比超高的《算法基础课》,想要学习更多ACM/蓝桥杯/CSP/NOIP算法竞赛知识,无论你是想要竞赛拿奖的大学生、想要在笔试面试中脱颖而出、或者是对计算机编程感兴趣的小朋友,都可以学习,一定不要错过!点此了解:https://www.starrycoding.com/course/1
适用对象广泛
内容紧贴考纲,每节课约1.5小时高密度知识
广受好评,学习氛围浓厚,平等互助,拒绝歧视与绑架
视频、习题、文档,想学就学
没错,在学习算法的时候你甚至可以看V。
最最最最最最最最重要的是,由于课程的准备、录制、平台(前后端和评测机)的开发、推广都是由我一人完成,所以成本压的非常非常低,算法基础课仅售39元。欢迎加入StarryCoding官方用户Q群:746470220(官网www.starrycoding.com)
悄悄说:StarryCoding平台还有算法中级课(可以自行了解)。