2️⃣

6.2 While-Loops

 

While Loop

Another type of loop used in programming is the while loop. The while loop is used when the programmer does not know the exact number of times the code needs to be iterated. For example, you might only want to run some code while a certain condition is true. You would implement this using a while loop. Let’s take a look at an example:
 
int i = 0; while (i < 9) //while loop header { printf(“Hello World!\nEnter a number: ”); scanf(“%d”, &i); }
 
In the above example, we have a variable of type int that has a value of 0. The conditional in the while loop checks to see if the value of i is less than 9. Since 0 is less than 9, the code in the while loop is executed. Within the while loop, there is a print statement and an input statement. The input statement prompts the user to enter a number and the computer stores the user’s number into the variable i.
 
This is where the functionality of a while loop comes into play: the computer has no idea what number the user is going to enter and whether it is going to fall in the range of the conditional or not. If the user enters a number outside the range, when the code checks the conditional in the while loop, the code inside will not run because the conditional will result in 0, or false. While loops are used in this way when the value of the number in the conditional is not previously known.
 
 

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.