How to Make Your Code Run Again

Loops in C


By Alex Allain

Loops are used to repeat a block of lawmaking. Existence able to have your program repeatedly execute a cake of code is 1 of the most basic but useful tasks in programming -- many programs or websites that produce extremely complex output (such as a bulletin lath) are really only 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 operation of reading in some data and displaying it.) Now, think about what this means: a loop lets you write a very simple statement to produce a significantly greater result merely by repetition.

Ane caveat: earlier going further, yous should empathise the concept of C's truthful and false, because it volition exist necessary when working with loops (the conditions are the aforementioned as with if statements). This concept is covered in the previous tutorial. There are three types of loops: for, while, and do..while. Each of them has their specific uses. They are all outlined below.

FOR - for loops are the nigh useful type. The syntax for a for loop is

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

The variable initialization allows you lot to either declare a variable and give it a value or give a value to an already existing variable. Second, the condition 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. It is possible to do things similar x++, x = ten + 10, or even ten = random ( five ), and if you really wanted to, yous could call other functions that do aught to the variable merely still have a useful effect on the lawmaking. Find that a semicolon separates each of these sections, that is of import. Also note that every single one of the sections may be empty, though the semicolons all the same take to be there. If the condition is empty, it is evaluated as truthful and the loop will repeat until something else stops it.

Example:

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

This plan is a very elementary example of a for loop. x is gear up to naught, while x is less than 10 it calls printf to display the value of the variable x, and it adds 1 to x until the condition is met. Keep in heed also that the variable is incremented later the lawmaking in the loop is run for the get-go 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 != seven ) (ten does not equal 7). It can be whatsoever combination of boolean statements that are legal. Even, (while 10 ==5 || v == 7) which says execute the code while x equals five or while 5 equals 7. Notice that a while loop is similar a stripped-down version of a for loop-- it has no initialization or update section. Yet, an empty condition is not legal for a while loop as information technology is with a for loop.

Example:

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

This was another simple example, simply it is longer than the higher up FOR loop. The easiest way to think of the loop is that when it reaches the brace at the end information technology jumps support to the beginning of the loop, which checks the status over again and decides whether to repeat the block another time, or stop and motion to the adjacent statement later on the block.

DO..WHILE - Exercise..WHILE loops are useful for things that desire to loop at least once. The structure is

do { } while ( condition );        

Notice that the condition is tested at the terminate of the cake instead of the kickoff, so the block volition exist executed at to the lowest degree one time. If the status is true, we jump back to the beginning of the block and execute information technology once again. A exercise..while loop is almost the same every bit a while loop except that the loop body is guaranteed to execute at least once. A while loop says "Loop while the condition is truthful, and execute this block of code", a do..while loop says "Execute this block of code, and so continue to loop while the condition is true".

Example:

#include <stdio.h>  int master() {   int 10;    x = 0;   do {     /* "Hello, world!" is printed at least i time       even though the status is fake */       printf( "Hello, earth!\due north" );   } while ( ten != 0 );   getchar(); }        

Proceed in listen that y'all must include a trailing semi-colon later the while in the in a higher place example. A mutual error is to forget that a practice..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop volition execute once, because it automatically executes earlier checking the status.

Break and Go along

Ii keywords that are very of import to looping are interruption and continue. The break command volition exit the most immediately surrounding loop regardless of what the conditions of the loop are. Interruption is useful if nosotros want to exit a loop nether special circumstances. For example, let's say the program we're working on is a two-person checkers game. The basic structure of the program might look like this:

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

This volition make the game alternate between having thespian 1 and player 2 take turns. The only problem with this logic is that at that place's no manner to exit the game; the loop will run forever! Allow's try something like this instead:

while(true) {     if (someone_has_won() || someone_wants_to_quit() == Truthful)     {break;}     take_turn(player1);     if (someone_has_won() || someone_wants_to_quit() == Truthful)     {pause;}     take_turn(player2); }

This code accomplishes what we desire--the primary loop of the game will continue under normal circumstances, but nether a special condition (winning or exiting) the flow will stop and our program will practise something else.
Continue is another keyword that controls the menstruum of loops. If y'all are executing a loop and hit a continue statement, the loop volition finish its electric current iteration, update itself (in the example of for loops) and brainstorm to execute once again from the top. Essentially, the go along statement is saying "this iteration of the loop is washed, allow's keep with the loop without executing whatever lawmaking comes afterward me." Let's say we're implementing a game of Monopoly. Like to a higher place, we desire to use a loop to control whose turn it is, but controlling turns is a bit more than complicated in Monopoly than in checkers. The basic construction of our code might and then look something like this:

for (actor = 1; someone_has_won == Simulated; player++)     {         if (role player > total_number_of_players)         {player = i;}         if (is_bankrupt(player))         {continue;}         take_turn(player);     }

This mode, if one player can't take her turn, the game doesn't stop for everybody; we just skip her and keep going with the next player'south turn.

Quiz yourself
Previous: If Statements
Next: Functions
Back to C Tutorial Index

cockrumsymproverse.blogspot.com

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

Related Posts

0 Response to "How to Make Your Code Run Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel