惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
云风的 BLOG
云风的 BLOG
T
Tailwind CSS Blog
IT之家
IT之家
V
Visual Studio Blog
S
SegmentFault 最新的问题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Cyberwarzone
Cyberwarzone
T
Tor Project blog
Last Week in AI
Last Week in AI
NISL@THU
NISL@THU
L
Lohrmann on Cybersecurity
V
V2EX
小众软件
小众软件
博客园 - 【当耐特】
S
Schneier on Security
酷 壳 – CoolShell
酷 壳 – CoolShell
Spread Privacy
Spread Privacy
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
Kaspersky official blog
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
N
News and Events Feed by Topic
Know Your Adversary
Know Your Adversary
Apple Machine Learning Research
Apple Machine Learning Research
Forbes - Security
Forbes - Security
博客园 - Franky
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
美团技术团队
S
Securelist
有赞技术团队
有赞技术团队
Engineering at Meta
Engineering at Meta
Simon Willison's Weblog
Simon Willison's Weblog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
U
Unit 42
Scott Helme
Scott Helme
GbyAI
GbyAI
N
Netflix TechBlog - Medium
Recent Commits to openclaw:main
Recent Commits to openclaw:main
P
Privacy International News Feed
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
L
LangChain Blog
Latest news
Latest news
Microsoft Azure Blog
Microsoft Azure Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Y
Y Combinator Blog
L
LINUX DO - 热门话题

lzw-723's blog

raylib基础学习 | lzw-723's blog Lojban教程 - 逻辑语学习中常见专有名词列表 | lzw-723's blog Lojban基础教程 - 字母 | lzw-723's blog 扩充巴科斯范式(ABNF)初识 | lzw-723's blog 【译】5分钟入门Nim编程语言 | lzw-723's blog Cakewalk安装无反应的解决办法 | lzw-723's blog C语言教程 - while循环 | lzw-723's blog C++ FAQ | lzw-723's blog 《Moe Era》 - 时代潮流中不值一提的我 | lzw-723's blog
C语言教程 - for循环 | lzw-723's blog
2021-09-04 · via lzw-723's blog

2021-09-05 2 min read # C # 教程 # 翻译

C语言中的for循环非常简单。

Tutorial

C语言中的for循环非常简单。你能用它创建一个循环—一块运行多次的代码块。
for循环需要一个用来迭代的变量,通常命名为i

for循环能够做这些:

  • 用一个初始值初始化迭代器变量
  • 检查迭代变量是否达到最终值
  • 增加迭代变量的值

如果想运行代码块10次,可以这样写:

int i;
for (i = 0; i < 10; i++) {
    printf("%d\n", i);
}

这段代码会打印从0到9的数字。

for循环能够用来获取数组的每一个值。要计算一个数组所有值的和,可以这样使用i

int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
int i;

for (i = 0; i < 10; i++) {
    sum += array[i];
}

/* 求a[0]到a[9]的和 */
printf("Sum of the array is %d\n", sum);

Exercise

计算数组array的阶乘(从array[0]乘到array[9])。

Tutorial Code

#include <stdio.h>

int main() {
  int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  int factorial = 1;
  int i;

  /* 在这里使用for循环计算阶乘*/

  printf("10! is %d.\n", factorial);
}

Expected Output

10! is 3628800.

Solution

#include <stdio.h>

int main() {
  int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  int factorial = 1;

  int i;

  for(i=0;i<10;i++){
    factorial *= array[i];
  }

  printf("10! is %d.\n", factorial);
}
    • Tutorial
    • Exercise
    • Tutorial Code
    • Expected Output
    • Solution