In: Computer Science
Question 1: What is For Loop? Explain with 2 Examples. You can write code in any programming language.
For-Loop is basically programming control flow statement for executing a set of instructions inside it for a specific number of times or until unless a condition is violated .
It has two parts:
Inside the header it has three parts which are applied on a loop variable say i (the variable that runs the loop) :
{
Body of loop with set of instructions
}
Example 1: Let us take an example to print Hello 10 times:
Approach : You can write code Hello 10 times seperately but it would be very repeated code and would not appear code for a programme .
So for your rescue comes the foor loop:
for(int i=0;i<10;i++){
System.out.println("Hello)
}
In above you can see you dont need the loop variable i inside the body but it is used to control the loop.If you replace < with <= symbol the loop will print hello 11 times.
Example 1: Let us take an example to print sum of numbers from 1 to 10:
Approach : You can write code as :
ans 1+2+3_ __ 10; but it will be a bad progrmming practice
So for your rescue comes
the foor loop:
for(int i=1;i<=10;i++){
ans=ans+10;
}
In above you can see you need the loop variable i inside the body If you replace < = with < symbol the loop will compute sum from 1 to 9.
Please find the code attached below in JAVA.
If you have any doubts feel free to ask
public class forLoop{
public static void main(String []args){
//Code for printing Hello 10 times
for(int i=1;i<=10;i++)
{
//Print statement in Java
System.out.println("Hello");
}
int ans=0;
//Code for sum of numbers from 1 to 10
for(int i=1;i<=10;i++)
{
ans=ans+i;
}
System.out.println("The some of numbers from 1 to 10 is "+ans);
}
}