Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
107 views

One-Dimensional Arrays: TH TH

Arrays allow the storage of multiple values of the same type sequentially in memory. One-dimensional arrays store values in a single column, accessed via an index. Two-dimensional arrays store values in rows and columns, accessed via two indices. Arrays can be initialized with initial values or loaded dynamically. Common operations on arrays include accessing elements, sorting, generating random numbers, and performing calculations element-wise.

Uploaded by

Carla Sibal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views

One-Dimensional Arrays: TH TH

Arrays allow the storage of multiple values of the same type sequentially in memory. One-dimensional arrays store values in a single column, accessed via an index. Two-dimensional arrays store values in rows and columns, accessed via two indices. Arrays can be initialized with initial values or loaded dynamically. Common operations on arrays include accessing elements, sorting, generating random numbers, and performing calculations element-wise.

Uploaded by

Carla Sibal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

ARRAYS

It is a list(or table) of a fixed number of variables of the same type which are stored sequentially in the computer memory. It is used
to store lists of numbers, letters, words, and other data types. Arrays allow you to organize data in either list or tabular form. The variables of
an array have a common name and are distinguished by means of subscripts (indexes/offsets). For example, below is an array containing 4
integer variables:
list[0], list[1], list[2], list[3]
The variables in an array are called its components or elements(list[0],list[1],… The number inside the bracket is the subscript). Each element is
numbered beginning at 0 up to array_size minus-1, where array_size is the number of elements.

One-Dimensional Arrays
Arrays with a single column of entries.

Array Declaration
data_type name[array_size];
Examples: double value[5]; //read as: “value is an array of 5 doubles
char name[20]; //name is an array of 20 characters

Initializing an Array
 List the element’s initial value in braces separated by a comma
Example : int num[5] = {4,2,13,7,8};
Effect: num[0]=4, num[1]=2, num[2]=13, num[3]=7, num[4]=8
 If you do not list enough values the computer will fill the remaining elements with 0
Example: int num[5] = {0};
Effect: num[0]=0, num[1]=0, num[2]=0, num[3]=0, num[4]=0
 If you initialize an array in its declaration, you can omit the size of the array
Example : int num[] = {4,2,13,7,8};
Effect: the size of this array is 5 since there are 5 elements inside the braces

Assigning a Value to an Array


The components of an array may be assigned values just like any other variables.
Examples: num[0] = 2; //2 is assigned to the first element of array num
name[5] = ‘a’; //a is assigned to the 6th element of array name
x[3] = x[2] + 5; //the third element of array x plus 5 is assigned to the 4th element of x

Accessing Data in an Array


Use for loop to process array elements. Use the subscript as the for loop counter

Example: Given the declaration: int num[5];


a. write a program segment that will load num with data
for(i=0; i<5; i++)
cin>>num[i];
b. write a program segment that will display the contents of array num
for(i=0; i<5; i++)
cout<<num[i]<<endl;
c. write a program segment that will multiply each element of num by 10 and display the results
for(i=0; i<5; i++)
cout<<num[i]*10<<endl;
d. write a program segment that will add all the contents of num
for(i=0, sum=0; i<5; i++)
sum+=num[i];
e. write a program segment that will display the first, third and fifth element only
for(i=0; i<5; i+=2)
cout<<num[i]<<endl;
f. write a program segment that will display all the elements that are greater than 10
for(i=0; i<5; i++)
if(num[i]>10)
cout<<num[i];

Sample Problem
Write a program that stores ten numbers in array num. Your program should locate and display both the minimum and maximum
values in the array.
Program:
#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
int num[10], i,min,max;

//load array with data


cout<<"Enter 10 numbers : ";
for(i=0; i<10; i++)
cin>>num[i];

//determine min and max


min=num[0]; //set 1st element to max
max=num[0]; //set ist element to min

for(i=1; i<10; i++)


{
if(num[i]>max)
max=num[i];
if(num[i]<min)
min=num[i];
}
cout<<"max = "<<max
<<"\nmin = "<<min<<endl;
getch();
return 0;
}

Sample Problem
a.Write a declaration to store the string “This is a test” into an array named str. Include the declaration in a program to display the
message using for loop.
b. Modify the for statement to display only the characters t,e,s, and t (“test”)

a.
#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
char str[14]={'T','h','i','s',' ','i','s',' ','a',' ','t','e','s','t'};
int i;
//display contents of str
for(i=0; i<14; i++)
cout<<str[i];

getch();
return 0;
}
b. //display “test” only
for(i=10; i<14; i++)
cout<<str[i];

Sample Problem (Parallel Arrays)


Write a program that will compute the salary of 5 employees. The program should ask the user to enter the rate per hour and the
number of hours worked by the employee. The rate and number of hours worked should be stored in array rate and array hrs, respectively. The
program should display the employee number, the rate, hours worked and salary of each employee.
Sample output
Employee No. Rate Hours Worked Salary
1 200 10 2000
2 100 10 1000
3 150 10 1500
4 300 7 2100
5 200 10 2000

Program
#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
int rate[5],hrs[5];
//get rate and hours worked
cout<<"Enter rate and hours worked of employee \n";
for(int i=0; i<5; i++)
{
cout<<"\nEmployee "<<i+1<<": ";
cout<<"\nRate : ";
cin>>rate[i];
cout<<"Hours Worked : ";
cin>>hrs[i];
}
//heading
cout<<"\tEmployee No. Rate Hours Worked Salary\n";
//display table
for(int i=0; i<5; i++)
cout<<"\n\t "<<i+1<<" "<<rate[i]<<" "<<hrs[i]<<"
"<<rate[i]*hrs[i];

getch();
return 0;
}

Generating Random Numbers


C++ is capable of generating random numbers using srand() and rand() functions. Here is the code that will generate 10 random
numbers to be stored in array num

int num[10],i;
srand(time(NULL));
for(i=0; i<10; i++)
num[i]=1+rand()%20; //store random no. in num[i]

srand(time(NULL))- randomizing to produce different sequence of random numbers for each execution
rand()%20 – produces numbers 0 – 19(called scaling), 20 is the scaling factor, to produce 1 to
20, we add 1. You may change the scaling factor.

Bubble Sort – adjacent elements in the list are exchanged with one another in such a manner that
the list becomes sorted
Pseudocode for bubble sort:
For the first element in the list to one less than the last element(I index)
For the second element in the list to the last element(j index)
If list[j] < list[j-1]
Swap list[j] with list[j-1]
End for
End for
Exercise: convert the above pseudocode to C++ statements.

Two-dimensional Arrays
Sometimes referred to as a table of data, consists of both rows and columns of elements.
Example: array num
Row 0 8 16 9 3
Row 1 7 2 17 1
Row 2 10 20 4 6

Col0 col1 col2 col3

Declaring a Two-Dimensional Array


Data-type name[no.of rows][no of columns];
Examples:
int val[5][4]; integer array with 5 rows and 4 columns
char str[10][20]; character array with 10 rows and 20 columns

An element in a two-dimensional array is identified by its position. Consider the array num
above, 8 is the element on the first row, first column(num[0][0]), 17 is the element on the 2nd
row, 3rd column (num[1][2]), etc.

Initialization of Two-Dimensional Array


Initialization is done in row order. First, the elements of the first row are initialized,
then the elements of the second row are initialized, and so on.
Example: To initialized array num
int num[3][4]={8,16,9,3,7,2,17,1,10,20,4,6};
or you can use braces to separate row elements
int num[3][4]={{8,16,9,3},{7,2,17,1},{10,20,4,6}};

Problem: Using the above declaration for array num


a.Write a single statement that sets the element of num in row 0, column 1 to zero
num[0][1]=0;
b. write a nested for statement that initializes each element of num to 1
for(r=0; r<3; r++)
{
for(c=0; c<4; c++)
num[r][c]=1;
}
c.Write a program segment that will display the contents of array num (tabular form)
for(r=0; r<3; r++) //rows
{
for(c=0; c<4; c++) //columns
cout<<num[r][c]<<"\t";
cout<<endl;
}
d. Write a program segment that will load array num with new values
for(r=0; r<3; r++)
{
for(c=0; c<4; c++)
cin>>num[r][c];
}
e.write a program segment that will add the contents of array num and display the sum and average
int sum=0;
for(r=0; r<3; r++)
{
for(c=0; c<4; c++)
{
cin>>num[r][c];
sum+=num[r][c];
}
}
float ave=sum/12.0;
cout<<"Sum = "<<sum<<endl<<"Average = "<<ave;

f.write a program segment that will display the elements of the first row of num
for(c=0; c<4; c++)
{
cout<<num[0][c]; //1st row only, row number is set to 0

}
g.write a program segment that totals the elements of the 3 rd column of num, it will also compute
the average
sum=0;
for(r=0; r<3; r++)
{
sum+=num[r][2];
}
float ave=sum/3.0;

h.write a program segment that exchanges the contents of columns 0 and 3


for(r=0; r<3; r++)
{
int temp = num[r][0];
num[r][0]=num[r][3];
num[r][3]=temp;
}

Arrays as Function Arguments


The called function is given direct access to the original array. Thus, any changes made
by the called function are made directly to the array itself(this is passing by reference since
the name of the array represents the address of the variable)
Example:
Given the declaration : int num[5], val[3][4];
For these arrays, the ff. function calls can be made:
Find_max(num);
Calc(num,val);
The suitable function header line for the above
void Find_max(int num[5]);
void Calc(int num[5], int val[3][4]);

Sample Problem
Write a program that will load a 2-dimensional array with random numbers. The program
should then display the random numbers generated. Use functions to load the array and display the
array

Program
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<time.h>
using namespace std;

void load(int [4][4]); //function prototypes, name of array is optional


void display(int [4][4]);
int main()
{
int num[4][4];

load(num); //call function load


display(num);

getch();
return 0;
}

void load(int num[4][4])


{
int r,c;
srand(time(NULL));
for(r=0; r<4; r++)
for(c=0; c<4; c++)
num[r][c]=1 +rand()%50;
}

void display(int num[4][4])


{
int r,c;
for(r=0; r<4; r++)
{
for(c=0; c<4; c++)
cout<<num[r][c]<<"\t";
cout<<endl;
}
}

Problems:
1. Write a program that will generate 20 random numbers (range: 1 – 50) and store it in one-
dimensional array; then the program will read a number d and check whether the number d is
present in the array. If it is so, print how many times the number d is repeated in the
array. Use the ff. functions:
a. Load() – load array with random numbers
b. Search() – search array if it contains d and return the number of times d is
repeated
c. Display()-display result
2. Write a program to read 10 numbers and store it in 1-dimensional array; then it will find
the largest and the smallest number. Find also the difference between the 2 numbers. Use
functions
3. Write a program to read 10 numbers and store it in one-dimensional array A; copy the
elements in another array B in reverse order; find the sum of the individual elements of
the array A and B and store the results in another array C(ex. C[0]=A[0]+B[0];
C[1]=A[1]+B[1];….). Display all the 3 arrays. Use functions
4. Write a program to read a 2-dimensional square matrix A and display its transpose.
Transpose of a matrix A is obtained by interchanging all the elements of rows and columns
of original matrix A. Use functions
5. Write a program to read a two dimensional array and find the sum of the elements row wise
and column wise separately, and display the sums of the rows and columns. Use functions.
6. Write a program that loads array A[4][3] with random numbers(range:1-50). Load into array
E all even integers and into array O all odd integers of array A. Print array E with
elements arrange in ascending order, in one line. Print array O on the second line.

You might also like