Iteration - Series Part 1
Iteration - Series Part 1
No 6 Iteration
Loop: repeating the steps till the given condition is true
Structure of loop:
1. Control var: var has initial value and it goes till the end of the loop
2. Body: set of statements to be repeated
3. Test condition: condition till which the loop should execute
4. Step value: it is the increase or decrease of control var to reach the
condition
Types of loop:
class loop7
{
psvm() Sopln(“ sum is”+ sum);
{ Scanner sc=new Scanner(System.in); }//main
Sopln(“Enter start and end value”); }//class
int s=sc.nextInt();
int e=sc.nextInt();
Sopln(“Enter the value of X”);
s= 10 e 17 x=3 12, 15
int x=sc.nextInt();
I i<=e i%x==0 sum+I
int sum=0;
for ( int i=s;i<=e;i++)
{ if( i%x==0)
sum=sum+i;
}//for
1. x= 1+2+3+4+-------n
i position of the term
• Series x= term value
import….
class
{ psvm()..
{ scanner….
Sopln(“Enter the number of terms”);
int n=sc.nextInt();
int sum=0;
int x=1;
for( int i=1;i<=n;i++)
{ sum=sum+x; // sum=sum+i
x++;
} sopln(“Sum is”+sum);}}
2. 1+ ½ +1/3+1/4+……1/n
Sopln(“Enter the number of terms”);
int n=sc.nextInt();
double sum=0.0d;
int x=1;
for( int i=1;i<=n;i++)
{ sum=sum+(1.0/x);
x++;
}
sopln(“Sum is”+sum);}}
3 ) 1-2+3- 4+-------n
i 1 2 3 4
Sopln(“Enter the no of terms”);
int n=sc.nextInt();
Int sum=0;
int x=1;
for( int i=1;i<=n;i++)
{ if (i%2==0)
sum=sum-x;
else
sum=sum+x;
x++;
}
Sopln(sum);
4. 1+
Sopln(“Enter the number of terms”);
int n=sc.nextInt();
Sopln(“Enter the value of a”);
int a=sc.nextInt();
double sum=1.0;
int x=2;
for( int i=2;i<=n;i++)
{ sum=sum+ Math.pow(a,x);
x++;
}
sopln(“Sum is”+sum);}}
4. a/2+a/3+a/4+---------a/(n+1)