Using a While Loop to Make a Program Run Again C#

Loops in C


By Alex Allain

Loops are used to echo a block of code. Being able to have your program repeatedly execute a block of code is one of the near basic but useful tasks in programming -- many programs or websites that produce extremely circuitous output (such as a bulletin board) are really merely executing a single task many times. (They may be executing a small number of tasks, but in principle, to produce a list of messages only requires repeating the performance of reading in some data and displaying information technology.) At present, recall nigh what this means: a loop lets you write a very simple argument to produce a significantly greater result simply past repetition.

One caveat: before going further, you should empathise the concept of C'south true and false, because it will exist necessary when working with loops (the weather condition are the same every bit with if statements). This concept is covered in the previous tutorial. At that place are three types of loops: for, while, and practice..while. Each of them has their specific uses. They are all outlined below.

FOR - for loops are the most useful blazon. The syntax for a for loop is

for ( variable initialization; condition; variable update ) {   Code to execute while the condition is true }        

The variable initialization allows you lot to either declare a variable and give it a value or requite a value to an already existing variable. Second, the status tells the program that while the provisional expression is true the loop should continue to repeat itself. The variable update section is the easiest way for a for loop to handle changing of the variable. Information technology is possible to do things similar x++, x = x + 10, or even x = random ( 5 ), and if you actually wanted to, you could telephone call other functions that do nothing to the variable but still have a useful effect on the lawmaking. Notice that a semicolon separates each of these sections, that is important. Besides note that every single one of the sections may be empty, though the semicolons still take to exist in that location. If the condition is empty, it is evaluated as true and the loop will repeat until something else stops it.

Example:

#include <stdio.h>  int primary() {     int x;     /* The loop goes while x < 10, and x increases by one every loop*/     for ( x = 0; 10 < 10; x++ ) {         /* Keep in mind that the loop condition checks             the conditional statement before it loops once more.            consequently, when x equals 10 the loop breaks.            x is updated earlier the condition is checked. */            printf( "%d\n", x );     }     getchar(); }        

This program is a very simple example of a for loop. x is set up to zero, while 10 is less than 10 it calls printf to display the value of the variable ten, and it adds 1 to ten until the condition is met. Continue in heed as well that the variable is incremented after the code in the loop is run for the first time.

WHILE - WHILE loops are very simple. The basic structure is

while ( condition ) { Code to execute while the condition is true } The truthful represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). Information technology tin can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while 10 equals 5 or while v equals seven. Discover that a while loop is similar a stripped-downwards version of a for loop-- information technology has no initialization or update department. Still, an empty condition is not legal for a while loop as it is with a for loop.

Example:

#include <stdio.h>  int principal() {    int 10 = 0;  /* Don't forget to declare variables */      while ( x < 10 ) { /* While x is less than 10 */       printf( "%d\n", x );       x++;             /* Update x so the condition can exist met eventually */   }   getchar();  }        

This was another simple example, simply information technology is longer than the higher up FOR loop. The easiest way to think of the loop is that when information technology reaches the brace at the cease information technology jumps support to the beginning of the loop, which checks the condition again and decides whether to repeat the block some other time, or terminate and movement to the next argument later the block.

DO..WHILE - Exercise..WHILE loops are useful for things that want to loop at least one time. The structure is

exercise { } while ( condition );        

Discover that the condition is tested at the end of the block instead of the commencement, and then the block will be executed at least once. If the condition is truthful, we jump back to the beginning of the cake and execute it once more. A do..while loop is almost the aforementioned equally a while loop except that the loop body is guaranteed to execute at least one time. A while loop says "Loop while the condition is true, and execute this block of code", a practise..while loop says "Execute this block of lawmaking, and then continue to loop while the condition is true".

Case:

#include <stdio.h>  int chief() {   int ten;    x = 0;   do {     /* "Hello, globe!" is printed at least one time       even though the condition is simulated */       printf( "Hello, earth!\northward" );   } while ( x != 0 );   getchar(); }        

Proceed in listen that you must include a abaft semi-colon afterward the while in the above case. A common error is to forget that a practise..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, calculation to the confusion). Notice that this loop will execute one time, considering it automatically executes before checking the status.

Pause and Continue

Two keywords that are very of import to looping are interruption and go along. The break command will leave the almost immediately surrounding loop regardless of what the atmospheric condition of the loop are. Break is useful if we want to leave a loop under special circumstances. For instance, let's say the program we're working on is a ii-person checkers game. The bones structure of the program might await similar this:

while (true)  {     take_turn(player1);     take_turn(player2); }

This will make the game alternating between having thespian 1 and thespian 2 take turns. The only problem with this logic is that at that place's no way to leave the game; the loop will run forever! Let'southward try something like this instead:

while(truthful) {     if (someone_has_won() || someone_wants_to_quit() == TRUE)     {interruption;}     take_turn(player1);     if (someone_has_won() || someone_wants_to_quit() == TRUE)     {break;}     take_turn(player2); }

This code accomplishes what nosotros desire--the master loop of the game volition continue under normal circumstances, but under a special condition (winning or exiting) the flow will finish and our program will do something else.
Continue is another keyword that controls the flow of loops. If you are executing a loop and hit a continue argument, the loop volition stop its current iteration, update itself (in the case of for loops) and begin to execute over again from the top. Substantially, the continue statement is saying "this iteration of the loop is done, let'south proceed with the loop without executing whatever code comes later me." Let's say we're implementing a game of Monopoly. Like above, we desire to use a loop to control whose plow it is, but decision-making turns is a bit more complicated in Monopoly than in checkers. The basic structure of our code might then expect something like this:

for (player = 1; someone_has_won == Imitation; player++)     {         if (player > total_number_of_players)         {histrion = 1;}         if (is_bankrupt(role player))         {continue;}         take_turn(thespian);     }

This way, if 1 role player can't take her turn, the game doesn't stop for everybody; we but skip her and keep going with the next actor's plow.

Quiz yourself
Previous: If Statements
Side by side: Functions
Dorsum to C Tutorial Index

meissnerwithish.blogspot.com

Source: https://www.cprogramming.com/tutorial/c/lesson3.html

0 Response to "Using a While Loop to Make a Program Run Again C#"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel