You are on page 1of 5

4/26/2016

Computer Science I
Lab 9

02/05/2016 - Shakhawan H. Mahmood Salahaddin University

Example 1
Practice on Loops (Using break)
Write a C++ program to print numbers 1-10, the program should
exit the loop when the number equals 6 or 7.
int main()
{
int i;
for(i=1; i <= 10; i++){
if(i==6 || i==7){
break;
}
cout<<i<<endl;
}
return 0;
}
02/05/2016 - Shakhawan H. Mahmood Salahaddin University

4/26/2016

Example 2
Practice on Loops (Using continue)
Write a C++ program to print numbers 1-10, the program should
exit the loop when the number equals 6 and continue from 7.
int main()
{
int i;
for(i=1; i <= 10; i++){
if(i==6){
continue;
}
cout<<i<<endl;
}
return 0;
}
02/05/2016 - Shakhawan H. Mahmood Salahaddin University

Example 3
Practice on One Dimensional Arrays (Vectors)
Write a C++ program that reads and prints xn vector.
const int n = 5;
int x[n];
Output:
int main(){
cout<<"Enter 5 integers: ";
for(int i=0; i<n; i++){
cin>>x[i];
}
for(int i=0; i<n; i++){
cout<<"The number in position "<< i << " is "<<x[i]<<endl;
}
return 0;
}
26/04/2015 - Shakhawan H. Mahmood Salahaddin University

4/26/2016

Example 4
Practice on One Dimensional Arrays (Vectors)
Write a C++ program that reads xn vector, then finds and
prints the largest number out of vector x.
..
..
Output:
int largestNo = 0;
largestNo = x[0];
for(int i=1; i<n; i++){
if(x[i]>largestNo){
largestNo = x[i];
}
}cout<<"The largest number is : "<<largestNo<<endl;
return 0;
}
26/04/2015 - Shakhawan H. Mahmood Salahaddin University

Example 5
Practice on One Dimensional Arrays (Vectors)
Write a C++ program that reads xn vector, then rearrange
the vector from largest to smallest (Descending Order).
const int n = 5;
int x[n], temp = 0;
int main(){
cout<<"Enter 5 integers: "<<endl;
for(int i=0; i<n; i++){
cin>>x[i];
cout<<endl;
}
for(int i=0; i<n; i++){
for(int j=i+1;j<n; j++){
if(x[i]<x[j]){
temp = x[j];

x[j] = x[i];
x[i] = temp;
}
}
}
cout<<"The array in descending order is: "<<endl;
for(int i=0; i<n; i++){
cout<<x[i]<<endl;
}
return 0;
}

26/04/2015 - Shakhawan H. Mahmood Salahaddin University

4/26/2016

Example 5
Practice on One Dimensional Arrays (Vectors)
Write a C++ program that reads xn vector, then rearrange
the vector from largest to smallest (Descending Order).
Output:

26/04/2015 - Shakhawan H. Mahmood Salahaddin University

Exercises
Practice on One dimensional arrays (vectors)
1) Write a C++ program that reads xn vector and prints it in

reverse order.
2) Write a C++ program that reads xn vector, then finds and prints
the largest number and its index out of vector x.

25/04/2016 - Shakhawan H. Mahmood Salahaddin University

4/26/2016

References
Nassir, H.S.2009. C++ programming with 469 solved problems.
Deitel, H.M. 2005. C++ How to program.
John R. H. 2000. Programming with C++.

02/05/2016 - Shakhawan H. Mahmood Salahaddin University

Questions?

02/05/2016 - Shakhawan H. Mahmood Salahaddin University

10

You might also like