Example 1: C# for Loop using System; namespace Loop { class ForLoop { public static void Main(string[] args) { for (int i=1; i<=5; i++) { Console.WriteLine("C# For Loop: Iteration {0}", i); } } } } When we run the program, the output will be: C# For Loop: Iteratio...
C while Loop: Example 1 Input two integers and find their average using while loop. #include<stdio.h>intmain(){inta,b,avg,count;count=1;while(count<=3){printf("Enter values of a and b:");scanf("%d%d",&a,&b);avg=(a+b)/2;printf("Average =%d",avg);}return0;} ...
Example 3: Declare Collection inside the Loop #include<iostream>usingnamespacestd;intmain(){// define the collection in the loop itselffor(intn : {1,2,3,4,5}) {cout<< n <<" "; }return0; } Run Code Output 1 2 3 4 5 Here, we have declared the collection within the loop itsel...
Let’s look at the “for loop” from the example: We first start by setting the variable i to 0. This is where we start to count. Then we say that the for loop must run if the counter i is smaller then ten. Last we say that every cycle i must be increased by one (i++). ...
A loop is used for executing a block of statements repeatedly until a particular condition is satisfied. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its valu
REM # | EXAMPLE: For loop to copy all the files in the current directory to the C:\User\ folder For %F in (*) do copy %F C:\User\ REM # | S...
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 <=20 ) { printf ("%d " , i ); i++;
Example-6: Create infinite for loop Create a bash named loop6.bash with the following script to know the way to declare infinite for loop. Here, the loop will iterate for infinite times and print the counter value until the user presses Ctrl+C. #!/bin/bash # Initialize counter variable ...
for(inti=0;;){longi=1;// valid C, invalid C++// ...} Keywords for Example Run this code #include <iostream>#include <vector>intmain(){std::cout<<"1) typical loop with a single statement as the body:\n";for(inti=0;i<10;++i)std::cout<<i<<' ';std::cout<<"\n\n""2)...
In this example, we’ll use a C++ for loop to calculate the factorial of a given number step by step.Code Example:#include <iostream> using namespace std; int main() { int n, factorial = 1; cout << "Enter a number: "; cin >> n; for (int i = 1; i <= n; i++) { ...