逆向基本数据结构

顺序结构

顺序结构的程序设计是最简单的,起包含的语句按。照书写的顺序执行,且每条语句都将被执行。其他的结构可以包括顺序结构,也可以作为顺序结构的组成部分。

他的执行是自上而下的

img

例如输出三个字符,将他们反向输出

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
int main()
{
char ch1, ch2 ,ch3;
printf("请输入三个字符:")
ch1 = getchar();
ch2 = getchar();
ch3 = getchar(); //依次输入三个字符
putchar(ch3);
putchar(ch2);
putchar(ch1); //反向输出三个字符
return 0;
}

运行结果

1
2
请输入三个字符:ABC
CBA

选择结构

1.if语句

简单的if语句用于实现单分支的数据结构。

语法格式:

1
2
3
4
if (条件表达式)
{
//条件表达式为 ture 时执行的代码
}

条件为真,执行if中的语句,然后再执行if条件之外的语句,反之则不执行if中的语句,直接执行if条件之后的语句

根据年龄判断是否已成年

1
2
3
4
5
int age = 20;
if( age > 18 )
{
printf("年龄达到18周岁,已经成年了");
}

判断一个数是否在5-10之间

1
2
3
4
5
int num = 8 ;
if( num > 5 &amp;&amp; num < 10 )
{
printf("num是5到10之间的数");
}

2.if…else语句

C语言中还提供了if else语句,用于实现双分支的选择结构。

1
2
3
4
5
6
7
8
if (条件表达式)
{
//条件表达式为 true 时执行的代码
}
else
{
//条件表达式为 false 时执行的代码
}

条件为真,执行if中的语句,然后再执行if…else之后的语句;反之执行else中的语句,然后再执行if…else之后的语句

img

循环结构

1.while循环

1
2
3
4
5
6
while(表达式)
{
语句;
………
}
语句;

(1)首先判断while后边括号内的表达式是否为真,若为真即执行大括号内的语句,若为假,则跳过while循环结构执行大括号下方的第一条语句。

(2)若为真,当执行完大括号内语句后,再次按照(1)去判断,执行。

(3)直到while后小括号内表达式的表达式为假,结束循环。

注意:若在while的大括号内执行了break语句,则立刻结束循环结构,开始执行大括号外下方的第一条语句。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
int main()
{
int a = 5, b = 10;
while(b > a) //即若b > a 为真就执行大括号内的语句,
{ //若为假则执行大括号下方语句
printf("while looping a = %d, b = %d\n", a, b);
a++;
}
printf("while loop over\n");

return 0;
}

运行结果

img

2.do…while

例1:do…while循环

1
2
3
4
5
6
7
8
9
10
11
12
#include  <stdio.h>
int main()
{
int a = 10, b = 10;
do
{
printf("while looping a = %d, b = %d\n", a, b);
}while(b > a);

printf("while loop over\n");
return 0;
}

运行结果

1
2
while looping  a = 10, b = 10
while loop over

例2:while循环

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main()
{
int a = 10, b = 10;
while(b > a)
{
printf("while looping a = %d, b = %d\n", a, b);
}
printf("while loop over\n");
return 0;
}

运行结果:

1
while loop over

以上两个例子,while的表达式和while循环体内的语句是一模一样的,执行后会产生不一样的结果,你会看到do…while…的结构会执行一次循环体内的打印输出语句,而while循环则,因b>a为假而没有执行。

即:do…while…结构先执行一次循环体内的语句然后再判断while后括号内的表达式的真假,除此之外跟上边的while结构是一样的。

3.for循环

for循环是一种跟为灵活的循环控制结构,完全可以替代上面的while循环

1
2
3
4
5
6
7
for(循环变量赋初值;循环条件判断;循环变量值变化)
{
语句1;
语句2;
语句3;
…………;
}

执行流程

img

例如:

1
2
3
4
5
6
7
8
9
10
#include  <stdio.h>
int main()
{
int i;
for(i = 0; i < 3; i++)
{
printf("print the value of i =%d\n", i);
}
return 0;
}

运行结果

1
2
3
print the value of i = 0
print the value of i = 1
print the value of i = 2

我们可以看到:

循环变量赋初值:将i的初始值变成0循环条件判断:判断i是否小于3,若小于3则为真,

其它为假

循环变量值变化:i的值自动加1