8_while & do-while Loops.pdf

Full Transcript

PRG 155 – Programming Fundamentals Using C 8. “while” Loop A while loop is usually used to repeatedly execute a statement/block of statements as long as a given condition is TRUE (nonzero). Syntax while (condition) { statements;... update...

PRG 155 – Programming Fundamentals Using C 8. “while” Loop A while loop is usually used to repeatedly execute a statement/block of statements as long as a given condition is TRUE (nonzero). Syntax while (condition) { statements;... update expression; } while Statement Flowchart How it works? 1. The condition is evaluated. The condition may be a direct integer value, a variable, or an expression.  Any nonzero value is considered TRUE.  If the condition contains a variable, the variable must be initiated before it is used.  If the condition is TRUE, the statements within the loop will be executed including the update expression.  If the condition is FALSE, the loop statements will not be executed. Program control jumps to the next statement after while loop. 2. The condition is evaluated again. Step 2 is repeated until the condition becomes false or loop is terminated using break statement. 1 PRG 155 – Programming Fundamentals Using C Example: #include int main(){ int n, counter=1, sum=0; printf("Enter integer number: "); scanf("%d", &n); while(counter

Use Quizgecko on...
Browser
Browser