Loops: Repeating Tasks
loops are used to perform repetitive tasks efficiently. so let’s look at the for loop and while loop. i intend to show some of the sorting algorithms that i’ve used and learnt over time. i might write something some day with examples of what to do.
For Loop Example
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Count: %d\n", i);
}
return 0;
}
While Loop Example
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("Count: %d\n", i);
i++;
}
return 0;
}
well, in the case of the for
Loop, this loop runs 5 times, printing the value of i
each time and incrementing it by 1
. however, in the case of the while
loop which is similar to the for
loop, but the condition is checked at the start of each iteration, and the variable i
is updated manually.
we can say that loops help avoid redundant code and make tasks like iterating over arrays or handling repetitive operations much easier.
Arrays: Storing Multiple Values
speaking of arrays, they allow you to store multiple values of the same data type. so let’s look at how to declare and use arrays in C.
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
in the case of int numbers[] = {10, 20, 30, 40, 50};
declares an array of integers and initializes it with 5 values. The for
loop prints each element of the array using the index i
.
on the flip side, arrays are super handy when you need to work with lists of items. They allow you to store, access, and manipulate multiple values without needing separate variables for each.