Professional Documents
Culture Documents
+
Control
Structure:
Loop
Control Structure: Loop
2. do while statement
3. for statement
Example:
a[0] , a[1] , … , a[n-1]
a
a[0] a[1] a[2] a[3] a[4] element
0 1 2 3 4 index
Elements of array
cout<<a[0] ; //print 3
• Perform mathematical operation on array element
X=a[3] /2 ; // result is x=5
a
Y=a[0]*a[2] ; //result is y=15
3 2 5 10 1
0 1 2 3 4
• Print sum of three element
cout<<a[0]+a[1]+a[2] ; // result is 10
• Can perform operation inside subscript:
a[5-2] same as a[3]
Array initialization
1- initialization at the same time you declare the array :(At compile
time)
int a[5]={10 ,20, 25,30 ,40}; a 0
10 20
1 2 3
25 30
4
40
10 20 25 30 40
int a[ ] ={10 ,20, 25,30 ,40};
Compiler will be determine the size from number of the value we give a0 1 2 3 4
int a[5]={0} ; a0 0 0
1 2 3
0 0 0
4
int a[5]={10 ,20, 25,30 ,40,22 ,33 ,55 , 50} ; Error too many elements
X
Cont
OR
int x[3] ;
x[0] =30 ;
x[1] =3*2 ;
x[2] =x[0] – x[1] ;
x 30 6 24
0 1 2
Cont.
OR
int a[5] ;
for (int i=0 ; i<5 ; i++)
{
cout<<“Enter a [“ << i <<“ ] : “ ;
cin>> a[i] ;
} //end for
Checking bound
output output
garbage value
Cont…
a 0
0 3
1 2
2 7
3 4
8 4
5
2
6
a 0
0
3
1 2
2 7
3 4
8 4
5
2
6
output
Example1
output
Example2
output
a 2
0
4
1
6 8
2 3 4
7
Example3
output
a 2
0
4
1
6 8
2 3 4
7
Example3
output
a 2
0
4
1
6 8
2 3 4
7
Example4
output
a 2
0
4
1
6 8
2 3 4
7
Example5
user
a 0 1 2 3 4
Cont...
Cont…
• Output example5 :
Example6
user
a 0 1 2 3 4
a
Starting point 0 1 2 3 4
a ma
x
?
mi
n
?
0 1 2 3 4
Cont…
Cont…
• Output example6 :
Example 7
a 0
2
1
5 8
2 3
6
4
3
*K=2
a 4 10 18 12 6
0 1 2 3 4
Cont….
• Output example7 :
Example8
a 0
2
1
5
2
8
3
6
4
3
b 0
4
1
3
2
2
3
0
4
10
c 0
2
1
5
2
8
3
6
4
3
Cont…
• Output example8 :
Example9
a 0
7
1
7
2
7
3
7
4
7
b 0 1 2 3 4
Cont…
• Output example9 :
Example10
a 0
2
1
2
2
2
3
2 b 0
1 1
1 2
1
3
1
4
1
c 2
0
2
1 2
2 2
3 4
1 1
5
1
6
1
7
1
8
Con…
Cont…
• Output example10 :
Example11
user
a size
Cont…
• Output example11 :
Linear search
?
10 20 30 50 20 50 X 30
0 1 2 3 4 5
?
10 20 30 50 20 50 X
0 1 2 3 4 5
?
10 20 30 50 20 50
0 1 2 3 4 5
Complete program
Output1:
Output2:
Linear search
Question:
What can we do , if we want to display all the position
of that key , if it occurs more than once
Example12
• Output example12 :
Questions? Comments!