How to Output a File Again in a While Loop C++

Loops in C


By Alex Allain

Loops are used to repeat a cake of code. Beingness able to take your program repeatedly execute a cake of code is ane of the most basic only useful tasks in programming -- many programs or websites that produce extremely complex output (such equally a bulletin board) are really only executing a single job many times. (They may be executing a minor number of tasks, but in principle, to produce a list of messages merely requires repeating the performance of reading in some information and displaying it.) At present, retrieve virtually what this ways: a loop lets you write a very uncomplicated statement to produce a significantly greater result just by repetition.

One caveat: earlier going further, you lot should sympathise the concept of C's true and false, because it will exist necessary when working with loops (the weather condition are the same 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 most useful type. The syntax for a for loop is

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

The variable initialization allows y'all to either declare a variable and give it a value or give a value to an already existing variable. 2nd, the condition tells the program that while the conditional expression is true the loop should go along 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 exercise things like x++, 10 = x + 10, or even x = random ( 5 ), and if you really wanted to, you could phone call other functions that do aught to the variable but still have a useful upshot on the code. Notice that a semicolon separates each of these sections, that is important. As well annotation that every single i of the sections may be empty, though the semicolons still have to exist there. If the condition is empty, it is evaluated as true and the loop will echo until something else stops information technology.

Example:

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

This program is a very uncomplicated example of a for loop. x is prepare to zippo, while x is less than 10 it calls printf to display the value of the variable x, and information technology adds ane to x until the condition is met. Keep in mind also that the variable is incremented later on the code in the loop is run for the first fourth dimension.

WHILE - WHILE loops are very simple. The bones construction is

while ( condition ) { Code to execute while the condition is truthful } The true represents a boolean expression which could be x == i or while ( x != 7 ) (x does not equal seven). It can be any combination of boolean statements that are legal. Fifty-fifty, (while x ==five || 5 == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is similar a stripped-downward version of a for loop-- it has no initialization or update section. However, an empty condition is non legal for a while loop as it is with a for loop.

Example:

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

This was some other simple example, but it is longer than the higher up FOR loop. The easiest fashion to recall of the loop is that when it reaches the brace at the end it jumps support to the beginning of the loop, which checks the condition again and decides whether to echo the cake another time, or end and move to the next statement later on the cake.

Practice..WHILE - Practice..WHILE loops are useful for things that desire to loop at least once. The construction is

practise { } while ( status );        

Detect that the status is tested at the end of the cake instead of the kickoff, and then the cake volition be executed at least once. If the status is true, we jump back to the beginning of the block and execute it again. A do..while loop is almost the same equally a while loop except that the loop body is guaranteed to execute at least once. A while loop says "Loop while the condition is true, and execute this block of code", a exercise..while loop says "Execute this block of code, and then proceed to loop while the condition is true".

Example:

#include <stdio.h>  int principal() {   int x;    x = 0;   do {     /* "Hello, globe!" is printed at to the lowest degree one time       fifty-fifty though the condition is false */       printf( "Hello, world!\n" );   } while ( ten != 0 );   getchar(); }        

Proceed in mind that you must include a trailing semi-colon after the while in the above example. A mutual fault is to forget that a do..while loop must be terminated with a semicolon (the other loops should non be terminated with a semicolon, adding to the defoliation). Notice that this loop will execute one time, because information technology automatically executes earlier checking the condition.

Suspension and Continue

Two keywords that are very important to looping are break and continue. The break command will leave the most immediately surrounding loop regardless of what the conditions of the loop are. Intermission is useful if we want to get out a loop under special circumstances. For example, let's say the plan nosotros're working on is a ii-person checkers game. The bones construction of the program might look like this:

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

This will make the game alternating between having player ane and player 2 take turns. The only problem with this logic is that there's no style to exit the game; the loop will run forever! Allow'south try something like this instead:

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

This code accomplishes what we desire--the primary loop of the game volition continue under normal circumstances, but under a special status (winning or exiting) the menstruum will stop and our program volition practise something else.
Continue is another keyword that controls the flow of loops. If you are executing a loop and hit a continue statement, the loop volition terminate its current iteration, update itself (in the case of for loops) and begin to execute once again from the summit. Essentially, the go on statement is saying "this iteration of the loop is done, let's continue with the loop without executing whatever code comes after me." Allow's say we're implementing a game of Monopoly. Like above, we desire to use a loop to control whose turn information technology is, but controlling turns is a scrap more complicated in Monopoly than in checkers. The basic structure of our code might and so look something like this:

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

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

Quiz yourself
Previous: If Statements
Next: Functions
Dorsum to C Tutorial Alphabetize

carterstagetheir1962.blogspot.com

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

0 Response to "How to Output a File Again in a While Loop C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel