You are on page 1of 5

Programming Fundamentals

Lab Manual (Lab 08)

Topic: Arrays

Course Instructor:
Lab Instructor:

Session: Fall 2015

School of Systems and Technology


UMT Lahore Pakistan
Objectives
• Understanding the working of arrays.
• To work with arrays””
• To be able to write a C++ program using arrays.

Reading Data from an Array


// arrays example
#include <iostream>
using namespace std;

int array [] = {1,2,3,4,5};


int n, result=0;

int main ()
{
for ( n=0 ; n<5 ; ++n )
{
cout << array[n];
}

return 0;
}

Output
12345

Example 2

Entering Data into an Array


// arrays example
#include <iostream>
using namespace std;

int array [5];


int n, result=0;

int main ()
{
Cout<< ”enter elements of array”;
for ( n=0 ; n<5 ; ++n )
{
Cin>>array[n];
}
Cout<< ”elements of array”;
for ( n=0 ; n<5 ; ++n )
{
Cout<<array[n];
}
return 0;
}

Example 3

// arrays example
#include <iostream>
using namespace std;

int foo [] = {16, 2, 77, 40, 12071};


int n, result=0;

int main ()
{
for ( n=0 ; n<5 ; ++n )
{
result += foo[n];
}
cout << result;
return 0;
}

Output
12206

Example 4
Let us try to write a program to find average marks obtained by a class of 30 students in a test.
main( )
{
int avg, sum = 0 ;
int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
Cout<< "\nEnter marks” ;
cin >> marks[i] ) ; /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
sum = sum + marks[i] ; /* read data from an array*/
avg = sum / 30 ;
cout<<"\nAverage marks = << avg ;
}
Task 1
Write a program which take 10 numbers from user and store them in an array and find the
average, Largest and smallest number in the array.

Task 2
Twenty-five numbers are entered from the keyboard into an array. Write a program to find out how
many of them are positive, how many are negative, how many are even and how many odd.

Task 3
Write a program to copy the contents of one array into another in the reverse order.

Task 4:
Write a program that assign Twenty random numbers to an array and counts all prime numbers
entered by the user. The program finally displays total number of primes in array.

Note: Use rand(), srand() and time() functions to generate the random numbers which you have
already learned in one of your previous labs.

Task 5:
Write a program to convert a decimal value into Hexa-Decimal and store the result in an array. And
print it.

You might also like