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...
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 it:
To demonstrate a practical example of the for loop, let's create a program that counts to 100 by tens:ExampleGet your own Java Server for (int i = 0; i <= 100; i += 10) { System.out.println(i); } Try it Yourself » In this example, we create a program that only print ...
Example 1: Loop Through Vector in R (Basics)In this Example, I’ll illustrate how to use for-loops to loop over a vector.In the following R code, we are specifying within the head of the for-loop that we want to run through a vector containing ten elements from the first element (...
Example-2: Reading Array Variable You can use for loop to iterate the values of an array. Create a new bash file namedloop2.shwith the following script. In this example, the loop retrieves the values from an array variable namedColorList, and it will print the output only if thePinkval...
Nested For Loop in C Nesting of loop is also possible. Lets take an example to understand this: #include<stdio.h>intmain(){for(inti=0;i<2;i++){for(intj=0;j<4;j++){printf("%d, %d\n",i,j);}}return0;} Output: 0,00,10,20,31,01,11,21,3 ...
Increment- A directive which increments the iterator. In our case, we increment it by 1 on every loop. example 2 To iterate over an array and print out all of its members, we usually use theforstatement. Here's an example: varmyArray=["A","B","C"];for(vari=0;i<myArray.length...
2. Java For-loop Example In the following program, we are iterating over an array ofintvalues. The array contains 5 elements so the loop will iterate 5 times, once for each value in the array. int[]array=newint[]{0,1,2,3,4};for(inti=0;i<array.length;i++){System.out.format(...
Python for each loop example: Here, we are going to implement a program that will demonstrate examples/use of for each loop.ByPankaj SinghLast updated : April 13, 2023 Why For Each Loop is Used? The for each loop is mainly used to traverse the elements of container type of data type ...
There are 3 types of loops in C:- while loop in C do – while loop in C for loop in C 1. while Loop in C- While loop executes the code until the condition is false. Syntax: while(condition){ //code } Example: #include<stdio.h> void main() { int i = 20; while( i <=...