Example-1: Reading static values Create a bash file named loop1.sh with the following script to read the values from a list using for loop. In this example, 5 static values are declared in the lists. This loop will iterate 5 times, and each time, it will receive a value from the li...
Example-1: For loop to read input variable List of predefined strings or array can be read easily by using ‘for’ loop which is shown in the previous tutorial of for loop. How the content of an input variable can be read by using ‘for’ loop is shown in this example. Create a fil...
Example 5 : For loop using File Names in Command Substitution to Specify Arguments Some commands provide file names and directory names as their output. In the following example, the shell substitutes the output of the command, ls /etc/p*(/etc/passwd/etc/profileand so on), as the argument...
To demonstrate a practical example of the for loop, let's create a program that counts to 100 by tens:Example for (i = 0; i <= 100; i += 10) { printf("%d\n", i);} Try it Yourself » In this example, we create a program that only print even numbers between 0 and 10 ...
see something that we did not explain: the expressionbreak;. That expression is used to jump out of the loop, which means that it takes the command right after the loop, without executing the rest of it, but instead doing whatever code is next. Here’s an example of how you can use ...
For example: #!/bin/bash # For loop with seq command for i in $(seq 0 2 10) do echo "Element $i" done The output prints each element generated by theseqcommand. Theseqcommand is a historical command and not a recommended way to generate a sequence. The curly braces built-in method...
If loop contain only one statement then braces are optional; generally it is preferred to use braces from readability point of view. For example : for (j=0;j<5;j++) printf("j”); Loops can be nested too. There can be loop inside another loop. Given below is example for nested loop...
Example 2: for loop // Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); // for loop term...
Example 4 – Loop over array elements Example 5 – C style for loop syntax Example 6 – Break, Continue statement usage Example 7 – True statement usage Conclusion For loop syntax Understanding syntax is very important before you write your firstfor loop. ...
Python for loop example using range() function Here we are usingrange() functionto calculate and display the sum of first 5 natural numbers. # Program to print the sum of first 5 natural numbers# variable to store the sumsum=0# iterating over natural numbers using range()forvalinrange(1...