前哨控制环
前哨控制的循环也称为无限重复循环,因为在循环开始执行之前未知迭代次数。在哨兵控制的循环中,称为哨兵值的特殊值用于将回路控制表达式从true更改为false,以确定是否执行循环主体。当我们事先不知道循环将执行多少次时,前哨控制循环很有用。前哨控制循环的一个示例是处理大小未知的文本文件中的数据。
下面是说明C语言中的哨兵控制循环的程序:
C
// The following program does the work
// of finding a length of a string using
// sentinel controlled loop
#include
// Function to find the
// length of the string
void lengthOfString(char* string)
{
int count = 0, i = 0;
char temp;
// Pointer to string
temp = string[0];
// Iterate till temp points to NULL
while (temp != '\0') {
count++;
i++;
temp = string[i];
}
// Print the length of the string
printf("The length of string is %d",
count);
}
// Driver Code
int main()
{
// Given String
char string[] = "GeeksForGeeks";
// Function Call
lengthOfString(string);
return 0;
}
C
// Program to print first K
// natural numbers
#include
// Function to print the Natural Number
void printNaturalNumbers(int K)
{
int i = 1;
while (i <= K) {
// Print the number i
printf("%d ", i);
i++;
}
return;
}
// Driver Code
int main()
{
// Given Number N
int N = 5;
// Function Call
printNaturalNumbers(N);
return 0;
}
输出:
The length of string is 13
计数器控制回路
计数器控制的循环也称为定重复循环,因为在循环开始执行之前已知迭代次数。计数器控制的循环具有以下组件:
- 控制变量。
- 增量(或减量)值,通过该值在循环的每次迭代中修改控制变量。
- 检查循环是否应该继续的循环终止条件。
由于计数器控制的循环是由一个计数器值控制的,因此在每次迭代时,计数器值将以确定的值增加或减少,并且将检查条件,因此循环执行的次数将变为确定的。任何涉及确定迭代的任务都可以使用计数器控制的循环来解决,例如打印前10个自然数。
C
// Program to print first K
// natural numbers
#include
// Function to print the Natural Number
void printNaturalNumbers(int K)
{
int i = 1;
while (i <= K) {
// Print the number i
printf("%d ", i);
i++;
}
return;
}
// Driver Code
int main()
{
// Given Number N
int N = 5;
// Function Call
printNaturalNumbers(N);
return 0;
}
输出:
1 2 3 4 5
C中的Sentinel和计数器控制循环之间的主要区别在于,在Sentinel受控循环中,确切地知道将执行多少次循环体,而在Counter Controlled循环中,已知将执行多少次循环体。
C中的Sentinel和计数器控制的循环之间的区别如下:
S.NO. | BASIS OF COMPARISON | SENTINEL CONTROLLED LOOP | COUNTER CONTROLLED LOOP |
---|---|---|---|
1. | Definition | A sentinel controlled loop is the indefinite repetition loop as the number of repetitions is not known before the loop begins executing | A counter controlled loop is the definite repetition loop as the number of repetitions is known before the loop begins executing |
2. | Controlling variable | Controlled variable variable used is know as sentinel variable. | Controlled variable used is know as counter. |
3. | Number of iteration | Unknown number of iteration | Known number of iteration. |
4. | Value of variable | The value of the variable is not strict and it varies. | The value of the variable is strict. |
5. | Limitation of variable | The Limitation of the variable is strict. | The Limitation of the variable is strict also. |
6. | Example | A do….while loop is an example of sentinel controlled loop. | A while loop is an example of counter controlled loop. |
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。