whileLoopExample(); // 调用while循环示例函数 doWhileLoopExample(); // 调用do-while循环示例函数 return 0; // 程序结束,返回0表示正常退出 } // 使用for循环打印1到10的数字 void forLoopExample() { // for循环初始化变量i为1,循环条件是i小于等于10,每次循环后i增加1 for (int i = 1; i <...
While vs do..while loop in C Using while loop: #include<stdio.h>intmain(){inti=0;while(i==1){printf("while vs do-while");}printf("Out of loop");} Output: Outof loop Same example using do-while loop #include<stdio.h>intmain(){inti=0;do{printf("while vs do-while\n");}wh...
C do...while Loop: Example 1 Input two integers and find their average using do while loop. #include<stdio.h>intmain(){inta,b,avg,count;count=1;do{printf("Enter values of a and b:");scanf("%d%d",&a,&b);avg=(a+b)/2;printf("Average =%d",avg);}while(count<=3);return0;...
C/C++ 中的循环在我们需要重复执行一个语句块时派上用场。 在研究 C 或 C++ 中的“for”循环期间,我们已经看到迭代次数是预先知道的,即循环体需要执行的次数是我们已知的。 C/C++ 中的 while 循环用于我们事先不知道循环的确切迭代次数的情况。循环执行根据测试条件终止。 语法: while(test_expression) { //...
Example 2: do...while loop // Program to add numbers until the user enters zero #include <stdio.h> int main() { double number, sum = 0; // the body of the loop is executed at least once do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(...
Do while loop For loop 1. While Loop While Loopis used when we do not already know how often to run the loop. In While Loop, we write the condition in parenthesis “()” after the while keyword. If the condition is true then the control enters the body of the while Loop and runs...
Do While Loop Examples: Example 1: #include <stdio.h>intmain(void){intx=1;do{printf("%d\n",x);x++;}while(x<=10);} In this example, we’ve created a do while loop that will print out the numbers 1 through 10. The variable x is initialized to 1 and then incremented by 1 ea...
while(condition){ //code } Example: #include<stdio.h> void main() { int i = 20; while( i <=20 ) { printf ("%d " , i ); i++; } } Output: 20 2. do – while loop in C It also executes the code until the condition is false. In this at least once, code is executed ...
For example, the factorial of3is3 * 2 * 1 = 6. Return the factorial of the input numbernum. 1 2 intfactorial(intnum){ } Video: C for Loop Previous Tutorial: C if...else Statement Next Tutorial: C while and do...while Loop ...
例子(Example) #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* do loop execution */ do { printf("value of a: %d\n", a); a = a + 1; }while( a < 20 ); return 0; } 编译并执行上述代码时,会产生以下结果 - ...