0% found this document useful (0 votes)
37 views

Ch4 Arrays Lec2

The document discusses passing arrays as function arguments in C++. It explains that a single element of an array can be passed to a function like a regular variable. However, to pass the entire array, the function parameter must be defined to accept an array and its size. The document provides examples of functions that demonstrate passing single elements, entire arrays, and modifying the original array by changing elements within the function. It also discusses two-dimensional arrays and how they can be used to store and access multiple sets of data.

Uploaded by

Desyilal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Ch4 Arrays Lec2

The document discusses passing arrays as function arguments in C++. It explains that a single element of an array can be passed to a function like a regular variable. However, to pass the entire array, the function parameter must be defined to accept an array and its size. The document provides examples of functions that demonstrate passing single elements, entire arrays, and modifying the original array by changing elements within the function. It also discusses two-dimensional arrays and how they can be used to store and access multiple sets of data.

Uploaded by

Desyilal
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Arrays as Function Arguments

• You may need to write functions that accept


arrays as an argument and process the data in
arrays.

• But before that, when a single element of an


array is passed to a function, it is handled like
any other variable.
Example
// This program demonstrates that an array element can be passed
// to a function like any other variable.
#include <iostream>
using namespace std;
void showValue(int); // Function prototype
int main()
{
const int ARRAY_SIZE = 8;
int collection[ARRAY_SIZE] = {5, 10, 15, 20, 25, 30, 35, 40};
for (int cycle = 0; cycle < ARRAY_SIZE; cycle++)
showValue(collection[cycle]);
cout << endl;
system("pause");
return 0;
}
//**************************************************
// Definition of function showValue *
// This function accepts an integer argument. *
// The value of the argument is displayed. *
//**************************************************
void showValue(int num)
{
cout << num << " ";
}
• If the function were written to accept the entire array as
an argument, the parameter would be set up differently.

void showValues (int nums[], int size)


{
for (int index = 0; index < size; index++)
cout << nums[index] << " ";
cout << endl;
}
Notice also that there is no size declarator inside
the brackets of nums.
// This program demonstrates an entire array being passed to a function.
#include <iostream>
using namespace std;
void showValues(int [], int); // Function prototype
int main()
{
const int ARRAY_SIZE = 8;
int collection[ARRAY_SIZE] = {5, 10, 15, 20, 25, 30, 35, 40};
showValues(collection, ARRAY_SIZE);
return 0;
}
//************************************************************
// Definition of function showValues *
// This function accepts an array of integers and its size *
// as arguments. The contents of the array are displayed. *
//************************************************************
void showValues (int nums[], int size)
{
for (int index = 0; index < size; index++)
cout << nums[index] << " ";
cout << endl;
}
•In the showValues function, the beginning address of the collection
array is copied into the nums parameter variable. The nums variable
is then used to reference the collection array.
•The following figure illustrates the relationship between the
collection array and the nums parameter variable. When nums[0] is
displayed, it is actually the contents of collection[0] that appears on
the screen.
// This program demonstrates different arrays being passed to a function.
#include <iostream>
using namespace std;
// Declare arrayType to be an alias for an array of ints
typedef int arrayType[];
void showValues(arrayType, int); // Function prototype
int main()
{
int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int set2[5] = {2, 4, 6, 8, 10};
showValues(set1, 8);
showValues(set2, 5);
system("pause");
return 0;
}
//************************************************************
// Definition of function showValues *
// This function accepts an array of integers and its size *
// as arguments. The contents of the array are displayed. *
//************************************************************
void showValues (arrayType nums, int size)
{
for (int index = 0; index < size; index++)
cout << nums[index] << " ";
cout << endl;
}
The nums parameter variable in the showValues function can accept the address of any integer array and can
be used to reference that array.
• Array parameters give the function access to the original argument(array).
• Any changes made to the array parametr variable are actuallyperformed on the argument
referenced by the variable.
// Unlike arrays,variables are passed to a function by value
#include <iostream>
using namespace std;
void showValues(int); // Function prototype
int main()
{
int number = 8;
showValues(number);
cout<<number<<endl;
system("pause");
return 0;
}
void showValues (int num)
{
num = num + 1;
cout<<num<<endl;
}
// This program uses a function to double the value of each array element.
#include <iostream>
using namespace std;
typedef int arrayType[];
void doubleArray(arrayType, int);
void showValues(arrayType, int);
int main()
{
const int ARRAY_SIZE = 7;
arrayType set = {1, 2, 3, 4, 5, 6, 7};
cout << "The arrays values are:\n";
showValues(set, ARRAY_SIZE);
doubleArray(set, ARRAY_SIZE);
cout << "\nAfter calling doubleArray, the values are:\n";
showValues(set, ARRAY_SIZE);
cout << endl;
system("pause");
return 0;
}
// Definition of function doubleArray.This function doubles the value of each element in the array
//passed into nums.
void doubleArray(arrayType nums, int size)
{
for (int index = 0; index < size; index++)
nums[index] *= 2;
}
void showValues (arrayType nums, int size)
{
for (int index = 0; index < size; index++)
cout << nums[index] << " ";
cout << endl;
}
Some Useful Array Functions
// This function computes and returns the sum of the values in the double array passed to it
double sumArray(double array[], int size)
{
double total = 0; // Accumulator
for (int count = 0; count < size; count++)
total += array[count];
return total;
}
// This function finds and returns the largest value in the double array passed to it.
double getHighest(double array[], int size)
{
double highest = array[0];
for (int count = 1; count < size; count++)
{
if (array[count] > highest)
highest = array[count];
}
return highest;
}
// This function finds and returns the smallest value in the double array passed to it.
double getLowest(double array[], int size)
{
double lowest = array[0];
for (int count = 1; count < size; count++)
{
if (array[count] < lowest)
lowest = array[count];
}
return lowest;
}
// This program gets a set of sales data from the user and displays the total, average, highest, and lowest amounts.

const int NUM_DAYS = 5; // Number of days


double sales[NUM_DAYS], // Holds the daily sales amounts
total, // Holds the week’s total sales
average, // Holds the average daily sales
highest, // Holds the highest daily sales
lowest; // Holds the lowest daily sales
// Get the sales data
cout << "Enter the sales for this week.\n";
for (int day = 0; day < NUM_DAYS; day++)
{
cout << "Day " << (day + 1) <<": ";
cin >> sales[day];
}
// Get total sales and compute average sales
total = sumArray(sales, NUM_DAYS);
average = total / NUM_DAYS;
// Get highest and lowest sales amounts
highest = getHighest(sales, NUM_DAYS);
lowest = getLowest(sales, NUM_DAYS);
// Display results
cout << fixed << showpoint << setprecision(2) << endl;
cout << "The total sales are $" << setw(9) << total << endl;
cout << "The average sales amount is $" << setw(9) << average << endl;
cout << "The highest sales amount is $" << setw(9) << highest << endl;
cout << "The lowest sales amount is $" << setw(9) << lowest << endl;
system("pause");
return 0;
}//Definition of the functions goes here.
 A program calculate the sum and average of maximum of 20 numbers entered by the user.
#include<iostream>
using namespace std;
const int SIZE=20;
void main()
{
int numbers[SIZE];
float sum=0,average;
cout<<“Enter your data\n";
for(int i=0;i<n;i++) {
cout<<“numbers["<<i<<"]=";
cin>>numbers[i];
sum+=numbers[i]; }
average=sum/n;
cout<<"average is ="<<average;
}
Finding Highest and lowest values
• int count;
int highest;
highest = numbers[0];
for (count = 1; count < SIZE; count++)
{
if (numbers[count] > highest)
highest = numbers[count];
}
• int count;
int lowest;
lowest = numbers[0];
for (count = 1; count < SIZE; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}
Searching for a number
int main()
{ // Declare the members of the array
int numbers[8] = {5, 25, 36, 44, 52, 60, 75, 89};
int find, i, SIZE = 8;
cout << "Enter a number to search: ";
cin >> find;
for (i = 0; (i < SIZE) && (numbers[i] != find); ++i)
continue;
// Find whether the number typed is a member of the array
if (i == SIZE) cout << find << " is not in the list" << endl;
else cout << find << " is the " << i + 1
<< "th element in the list" << endl;
return 0; }
Two-Dimensional Arrays
• It’s necessary to work with multiple sets of data.
• For example, in a grade-averaging program a
teacher might record all of one student’s test
scores in an array of doubles.

double student1TestScores[3] = {2.5,5,9};


double student2TestScores[3] = {7,8.5,10};
………
double student30TestScores[3] = {10,9,9};
• A two-dimensional array is like several
identical arrays put together.
• It is useful for storing multiple sets of data.
• It’s best to think of a two dimensional array as
a table having rows and columns of elements,
as shown in Figure .
• To define a two-dimensional array, two size
declarators are required: the first one is for the
number of rows and the second one is for the
number of columns.
• E.g.

• For processing the information in a two-


dimensional array, each element has two
subscripts: one for its row and another for its
column.
In the score array, the elements in row 0 are referenced as
score[0][0]
score[0][1]
score[0][2]
score[0][3]
The elements in row 1 are
score[1][0]
score[1][1]
score[1][2]
score[1][3]
And the elements in row 2 are
score[2][0]
score[2][1]
score[2][2]
score[2][3]
• The subscripted references are used in a
program just like the references to elements in
a one-dimensional array.
• For example, the following statement assigns
the value 92.25 to the element at row 2,
column 1 of the score array:
score[2][1] = 92.25;
• And the following statement displays the
element at row 0, column 2:
cout << score[0][2];
//Programs that cycle through each element of a two-dimensional array usually do so with nested loops.
{

const int NUM_STUDENTS = 3;


const int NUM_TESTS = 4;
double scores[NUM_STUDENTS][NUM_TESTS] ; // 2D array with 3 rows and 4 columns
scores[0][0] = 2.5;
scores[0][1] = 10;
scores[0][2] = 9;
scores[0][3] = 9; 
scores[1][0] = 7.5;
scores[1][1] = 6;
scores[1][2] = 10;
scores[1][3] = 5; 
scores[2][0] = 9;
scores[2][1] = 7;
scores[2][2] = 2.5;
scores[2][3] = 8.5; 
//Nested loops are used to read in test scores for each student & display this on the scree
cout<<"These are the test scores for three students"<<endl;
for (int student = 0; student < NUM_STUDENTS; student++)
{
for (int test = 0; test < NUM_TESTS; test++)
{
cout << "Student " << (student + 1)<< ", Test " << (test + 1) << ": "
<<scores[student][test]<<endl;
 
}
cout << endl; // Print blank line.
}
• As with one-dimensional arrays, two-dimensional arrays can be
initialized when they are created.
E.g. int hours[3][2] = {{8, 5}, {7, 9}, {6, 3}};
The same statement could also be written as
int hours[3][2] = {{8, 5},
{7, 9},
{6, 3}};
In either case, the values are assigned to hours in the following
manner:
hours[0][0] is set to 8
hours[0][1] is set to 5
hours[1][0] is set to 7
hours[1][1] is set to 9
hours[2][0] is set to 6
hours[2][1] is set to 3
• The extra braces that enclose each row’s
initialization list are optional.
• The following two statements are equivalent
int hours[3][2] = {{8, 5}, {7, 9}, {6, 3}};
int hours[3][2] = {8, 5, 7, 9, 6, 3};
• However, the braces give you the ability to
leave out initializers within a row without
omitting the initializers for the rows that
follow it:
• int table[3][2] = {{1}, {3, 4}, {5}};
// This is a rewrite of the previous program using initalization list
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
const int NUM_STUDENTS = 3;
const int NUM_TESTS = 4;

// 2D array with 3 rows and 4 columns


double scores[NUM_STUDENTS][NUM_TESTS] = {{2.5, 10, 9,9},
{7.5, 6, 10, 5},
{9,7, 2.5, 8.5}};
 
// Nested loops are used to read in test scores for each
// student and display this on the screen.
cout<<"These are the test scores for four students"<<endl;
for (int student = 0; student < NUM_STUDENTS; student++)
{
for (int test = 0; test < NUM_TESTS; test++)
{
cout << "Student " << (student + 1)<< ", Test " << (test + 1) << ": "
<<scores[student][test]<<endl;
}
cout << endl; // Print blank line.
}
 
system("pause");
return 0;
}
Summing All the Elements of a Two-Dimensional Array
To sum all the elements of a two-dimensional array, you can use a pair of nested
loops to add the contents of each element to an accumulator.
Summing the Rows of a Two-Dimensional Array

• For example, suppose a two-dimensional array is


used to hold a set of test scores for a group of
students.
• Each row in the array is a set of scores for one
student.
• To sum the scores for each student, you again use
a pair of nested loops.
• The inner loop is used to add all the scores in a
row, that is, all the scores for one student. The
outer loop is executed once for each student.
Summing the Columns of a Two-Dimensional Array

• from the previous example, suppose you wish


to calculate the class average for each of the
tests. To do this, you must calculate the
average of each column in the array.
char name[20];
N.B 1.we need not initialize all the available space (20)
2.the string will terminate by the null character ‘\0’
Initialization
char my_string[]={‘H’,’e’,’l’,’l’,’o’,’\0’’};
or char my_string[]=”Hello”
once initialized we can not use the following:
my_string[]=”hello”;
my_string=”Hello”;
my_string[]={‘H’,’e’,’l’,’l’,’o’,’\0’’};
but we can say
my_string [0]=’H’;
my_string[3]=’k’;
cout<< my_string[2];
cout<<my_string;
cin>> my_string;
With cin space will not be read.
Hence use the following
cin.getline(char buffer[],int )
 
Address to store input Max length
Eg. // cin with strings
#include <string>
int main () {
char mystr[100];
cout << "What's your name? ";
cin.getline(mystr,100);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
cin.getline(mystr,100); cout << "I like " <<
mystr << " too!\n"; return 0; }
String Manipulations:
Functions to manipulate strings:
Requires string header file in standard c++ and string.h in pre-standard c++.
 
i)strlen (char buffer[] ) =>retuns the length without the null character ‘\0’;
int main () {
char name[50] = "Abebe Kebede";
int len1, len2;
len1 = strlen(name); // 12
len2 = strlen("Hello World"); // 11
cout<<len1<<" "<<len2;
return 0; }
String concatenation
ii)strcat(str1, str2) =>to concatenate or merge two strings
NB. 1.The first string str1 hold the concatenated string
2.the size of the first string must be large enough to hold both
strings.
int main()
{char str1[13] = "Hello ";
char str2[] = "World!"
cout<<"Before: "<<str1<<endl;
cout<<"Before: "<<str1<<endl;
strcat(str1, str2);
cout<<"After: "<<str1<<endl;
cout<<"After: "<<str2<<endl;}
String compare
iii)strcmp(str1,str2) => for lexical/alphabetica
comparison rule:
• 0 if the two strings are equal
• negative if the first string comes before the
second in alphabetical order
• positive if the first string comes after the
second in alphabetical order
String copy
iv) strcpy(str1,str2): is used to copy one string to another.
This is because arrays can't be copied using
the assignment operator (=).
Example:
char str1[20];
char str2[] = "Second String";
strcpy(str1, str2);
cout<<"str1: "<<str1<<endl;
strcpy(str2, "Another String");
cout<<"str2: "<<str2<<endl;
String/Numeric Conversion
i)atoi= string to int i)itoa int to string
ii)atof=string to float ii)ftoi float to string
iii)atoll=string to long iii)ltoa long to string
Eg.
int num = atoi("4123"); //num = 4123
long lnum = atol ("12345678");
float fnum = atof ("2.34");
itoa (not standard): converts an integer to a string. It
accepts three arguments
argument1 - the integer to be converted
argument2 - the string to hold the converted result
argument3 - the base (8, 10, or 16)
char strnum[4];
itoa(102, strnum, 10);

You might also like