Зміст курсу
C Basics
C Basics
While, Do-While
Imagine a scenario where you need to repeatedly execute certain tasks, like reading data from a sensor, attempting password entries, or counting words in a sentence. In these situations, loops come into play.
Loops enable you to run specific blocks of code multiple times, be it tens, hundreds, or even thousands of times. Grasping the concept of loops is vital in programming. This course delves into the foundational loops: the while
loop, do-while
loop, and for
loop.
While Loop
This loop continues running as long as a specific condition is met. Once the condition isn't satisfied, the loop stops.
A basic use of a loop is to display the count of its repetitions:
Main
#include <stdio.h> int main() { int iterations = 1; // interesting string while (iterations <= 10 ) { printf("%d\n", iterations); iterations++; // iterations = iterations + 1; } return 0; }
To halt this loop, a terminating condition is essential. A straightforward approach is using a counter to track the number of times the loop runs.
Note
An iteration refers to a single cycle within a loop. So, if the loop runs the code block 10 times, it has completed 10 iterations.
The line iterations++;
is crucial as it increments the counter (int iterations
) with each pass. The counter then sets the conditions to terminate the loop.
Note
It's imperative to establish conditions to exit the loop. Failing to do so will result in an endless loop.
Let's craft a program to showcase the elements of an integer array:
Main
#include <stdio.h> int main() { int array[] = {3, 6, 2, 134, 45, 2, 564, 8, 3, 531}; int i = 0; // index of array while (i < 10 ) { printf("Index of element: %d\tValue of element: %d\n", i, array[i]); i++; // i = i + 1 } return 0; }
Focus on the expression array[i]
.
Here, the variable i
denotes the index of the array[]
elements.
Note
An iteration refers to the count of loop cycles.
With every cycle, the variable i
increases by 1. This means that during each cycle, the expression array[i]
accesses the subsequent array element:
do-while
The key distinction between the do-while
and while
loops is that the former guarantees at least one execution, even if its condition is initially false.
Example:
Main
#include <stdio.h> int main() { int i = 0; do { printf("Condition `i == 1` is false, because i = 0, but loop is working...\n"); } while (i == 1); printf("Loop is over\n"); return 0; }
This type of loop is handy for crafting basic user interfaces. For instance, when prompting for a password, the program will repeatedly ask until the user inputs the correct one:
Main
#include <stdio.h> int main() { int userInput[] = { 111, 222, 333, 444 }; // arrays of passwords int i = 0; // index of element do { printf("You entered password: %d | incorrect\n", userInput[i]); i++; } while (userInput[i] != 444); printf("You entered password: %d | correct\n", userInput[i]); return 0; }
Дякуємо за ваш відгук!