C ++ medan och gör ... medan Loop (med exempel)

I den här handledningen lär vi oss användningen av while och do… medan loopar i C ++ programmering med hjälp av några exempel.

Vid datorprogrammering används slingor för att upprepa ett kodblock.

Låt oss till exempel säga att vi vill visa ett meddelande 100 gånger. I stället för att skriva utskriftsuttrycket 100 gånger kan vi använda en slinga.

Det var bara ett enkelt exempel; vi kan uppnå mycket mer effektivitet och sofistikering i våra program genom att använda slingor effektivt.

Det finns 3 typer av öglor i C ++.

  1. for slinga
  2. while slinga
  3. do… while slinga

I föregående handledning lärde vi oss om C ++ för loop. Här ska vi lära oss om whileoch do… whileloopar.

C ++ medan Loop

Slingans syntax whileär:

 while (condition) ( // body of the loop )

Här,

  • En whileslinga utvärderarcondition
  • Om conditionutvärderas till körs truekoden inuti whileslingan.
  • Den conditionutvärderas igen.
  • Denna process fortsätter tills den conditionär false.
  • När conditionutvärderas till falseavslutas slingan.

För att lära dig mer om conditions, besök C ++ Relational and Logical Operators.

Flödesschema för medan Loop

Flödesschema för C ++ medan loop

Exempel 1: Visa nummer från 1 till 5

 // C++ Program to print numbers from 1 to 5 #include using namespace std; int main() ( int i = 1; // while loop from 1 to 5 while (i <= 5) ( cout << i << " "; ++i; ) return 0; )

Produktion

 1 2 3 4 5

Så här fungerar programmet.

Iteration Variabel jag <= 5 Handling
1: a i = 1 true 1 skrivs ut och iökas till 2.
2: a i = 2 true 2 skrivs ut och iökas till 3.
3: e i = 3 true 3 trycks och iökas till4
4: e i = 4 true 4 skrivs ut och iökas till 5.
5: e i = 5 true 5 skrivs ut och iökas till 6.
6: e i = 6 false Slingan avslutas

Exempel 2: Endast summan av positiva siffror

 // program to find the sum of positive numbers // if the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include using namespace std; int main() ( int number; int sum = 0; // take input from the user cout <> number; while (number>= 0) ( // add all positive numbers sum += number; // take input again if the number is positive cout <> number; ) // display the sum cout << "The sum is " << sum << endl; return 0; )

Produktion

 Ange ett nummer: 6 Ange ett nummer: 12 Ange ett nummer: 7 Ange ett nummer: 0 Ange ett nummer: -2 Summan är 25

I detta program uppmanas användaren att ange ett nummer som lagras i det variabla numret.

För att lagra summan av siffrorna deklarerar vi en variabel summa och initialiseras till värdet av 0.

Den whilefortsätter slingan tills användaren anger ett negativt tal. Under varje iteration läggs det antal som användaren anger till sumvariabeln.

När användaren anger ett negativt tal avslutas slingan. Slutligen visas den totala summan.

C ++ gör … medan Loop

Den do… whileslinga är en variant av den whileslinga med en viktig skillnad: kroppen av do… whileslingan utförs en gång innan conditionkontrolleras.

Dess syntax är:

 do ( // body of loop; ) while (condition);

Här,

  • Slingans kropp körs först. Sedan conditionutvärderas.
  • Om conditionutvärderas till true, dokörs kroppen av slingan inuti uttalandet igen.
  • Den conditionutvärderas än en gång.
  • Om conditionutvärderas till true, dokörs kroppen av slingan inuti uttalandet igen.
  • Denna process fortsätter tills conditionutvärderingen till false. Sedan slutar slingan.

Flödesschema över do … while Loop

Flödesschema för C ++ gör … medan slinga

Exempel 3: Visa nummer från 1 till 5

 // C++ Program to print numbers from 1 to 5 #include using namespace std; int main() ( int i = 1; // do… while loop from 1 to 5 do ( cout << i << " "; ++i; ) while (i <= 5); return 0; )

Produktion

 1 2 3 4 5

Så här fungerar programmet.

Iteration Variabel jag <= 5 Handling
i = 1 inte kontrollerad 1 skrivs ut och iökas till 2
1: a i = 2 true 2 skrivs ut och iökas till 3
2: a i = 3 true 3 skrivs ut och iökas till 4
3: e i = 4 true 4 skrivs ut och iökas till 5
4: e i = 5 true 5 skrivs ut och iökas till 6
5: e i = 6 false Slingan avslutas

Exempel 4: Endast summan av positiva siffror

 // program to find the sum of positive numbers // If the user enters a negative number, the loop ends // the negative number entered is not added to the sum #include using namespace std; int main() ( int number = 0; int sum = 0; do ( sum += number; // take input from the user cout <> number; ) while (number>= 0); // display the sum cout << "The sum is " << sum << endl; return 0; )

Utgång 1

 Ange ett nummer: 6 Ange ett nummer: 12 Ange ett nummer: 7 Ange ett nummer: 0 Ange ett nummer: -2 Summan är 25

Here, the do… while loop continues until the user enters a negative number. When the number is negative, the loop terminates; the negative number is not added to the sum variable.

Output 2

 Enter a number: -6 The sum is 0.

The body of the do… while loop runs only once if the user enters a negative number.

Infinite while loop

If the condition of a loop is always true, the loop runs for infinite times (until the memory is full). For example,

 // infinite while loop while(true) ( // body of the loop )

Here is an example of an infinite do… while loop.

 // infinite do… while loop int count = 1; do ( // body of loop ) while(count == 1);

In the above programs, the condition is always true. Hence, the loop body will run for infinite times.

for vs while loops

A for loop is usually used when the number of iterations is known. For example,

 // This loop is iterated 5 times for (int i = 1; i <=5; ++i) ( // body of the loop )

Here, we know that the for-loop will be executed 5 times.

Men whileoch do… whileslingor brukar användas när antalet iterationer är okänt. Till exempel,

 while (condition) ( // body of the loop )

Kolla in dessa exempel för att lära dig mer:

  • C ++ - program för att visa Fibonacci-serien
  • C ++ - program för att hitta GCD
  • C ++ - program för att hitta LCM

Intressanta artiklar...