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

2011 C++ Chapter 05

The document discusses arrays and functions in C++. It defines arrays as collections of data that hold the same type of data in each storage location. Arrays are declared with the type, name, and number of elements in brackets. Elements are accessed using offsets, starting from 0. Multidimensional arrays have multiple subscripts. Functions are blocks of code that perform tasks and can be called from different parts of a program. Functions are declared with the return type, name, and parameters, and defined with the body. Calling a function transfers control to execute the function's statements and then returns.

Uploaded by

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

2011 C++ Chapter 05

The document discusses arrays and functions in C++. It defines arrays as collections of data that hold the same type of data in each storage location. Arrays are declared with the type, name, and number of elements in brackets. Elements are accessed using offsets, starting from 0. Multidimensional arrays have multiple subscripts. Functions are blocks of code that perform tasks and can be called from different parts of a program. Functions are declared with the return type, name, and parameters, and defined with the body. Calling a function transfers control to execute the function's statements and then returns.

Uploaded by

tsegab bekele
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Fundamentals of Programming I Introduction to Arrays and Functions

Chapter five
Introduction to Arrays and Functions
 Introduction to arrays
 Introduction to functions
 Declaring and defining function
 Function Prototype
 Calling function
Introduction to arrays
In previous chapters, you declared a single int, char, or another object. You often want to declare a collection of
objects, such as 20 integers.
What Is an Array?
An array is a collection of data storage locations, each of which holds the same type of data. Each storage
location is called an element of the array.
You declare an array by writing the type, followed by the array name and the subscript. The subscript is the
number of elements in the array, surrounded by square brackets. For example,
int age [25];
declares an array of 25 integers, named age. When the compiler sees this declaration, it sets aside enough
memory to hold all 25 elements. Because each integer requires 2 bytes, this declaration sets aside 50 contiguous
bytes of memory.
Array Elements
You access each of the array elements by referring to an offset from the array name. Array elements are counted
from zero. Therefore, the first array element is arrayName[0]. In the age example, age[0] is the first array
element, age[1] the second, and so forth.
More generally, SomeArray[n] has n elements that are numbered SomeArray[0] through SomeArray[n-1].

Using an integer array.

1
Fundamentals of Programming I Introduction to Arrays and Functions

//Array
#include <iostream>
using namespace std;
int main()
{
int myArray[5];
int i;
for ( i=0; i<5; i++) // 0-4
{
cout<< "Value for myArray[" <<i<< "]: ";
cin>>myArray[i];
}
for (i = 0; i<5; i++)
cout<<i<< ": " <<myArray[i] << "\n";
return 0;
}
Output:
Value for myArray[0]: 3
Value for myArray[1]: 6
Value for myArray[2]: 9
Value for myArray[3]: 12
Value for myArray[4]: 15
0: 3
1: 6
2: 9
3: 12
4: 15
Line 6 declares an array called myArray, which holds five integer variables. Line 8 establishes a loop that
counts from 0 through 4, which is the proper set of offsets for a five-element array. The user is prompted for a
value, and that value is saved at the correct offset into the array.

2
Fundamentals of Programming I Introduction to Arrays and Functions

The first value is saved at myArray[0], the second at myArray[1], and so forth. The second for loop prints each
value to the screen.
________________________________________
NOTE: Arrays count from 0, not from 1. This is the cause of many bugs in programs written by C++ novices.
Whenever you use an array, remember that an array with 10 elements counts from ArrayName[0] to
ArrayName[9]. There is no ArrayName[10].
________________________________________
Initializing Arrays
You can initialize a simple array of built-in types, such as integers and characters, when you first declare the
array. After the array name, you put an equal sign (=) and a list of comma-separated values enclosed in braces.
For example,
int Integer Array [5] = { 10, 20, 30, 40, 50 };
declares IntegerArray to be an array of five integers. It assigns IntegerArray[0] the value 10, IntegerArray[1]
the value 20, and so forth. If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write
int Integer Array[] = { 10, 20, 30, 40, 50 };
you will create exactly the same array as you did in the previous example.
You cannot initialize more elements than you've declared for the array. Therefore,
int IntegerArray[5] = { 10, 20, 30, 40, 50, 60};
generates a compiler error because you've declared a five-member array and initialized six values. It is legal,
however, to write
int IntegerArray[5] = { 10, 20};
If you don't initialize an array member, its value will be set to 0.
Declaring Arrays
Arrays can have any legal variable name, but they cannot have the same name as another variable or array within
their scope. Therefore, you cannot have an array named myCats[5] and a variable named myCats at the same
time.
Accessing Arrays
To access members of the array, use the subscript operator.
Example

3
Fundamentals of Programming I Introduction to Arrays and Functions

int theNinethInteger = MyIntegerArray[8];


Multidimensional Arrays
It is possible to have arrays of more than one dimension. Each dimension is represented as a subscript in the
array. Therefore, a two-dimensional array has two subscripts; a three-dimensional array has three subscripts; and
so on. Arrays can have any number of dimensions, although it is likely that most of the arrays you create will be
of one or two dimensions.
A good example of a two-dimensional array is a chess board. One dimension represents the eight rows; the other
dimension represents the eight columns.
SQUARE Board [8][8];
Initializing Multidimensional Arrays
You can initialize multidimensional arrays. You assign the list of values to array elements in order, with the last
array subscript changing while each of the former holds steady. Therefore, if you have an array
int theArray[5][3]
You initialize this array by writing
int theArray[5][3] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }
For the sake of clarity, you could group the initializations with braces. For example,
int theArray[5][3] = { {1,2,3},
{4,5,6},
{7,8,9},
{10,11,12},
{13,14,15} };
The compiler ignores the inner braces, which make it easier to understand how the numbers are distributed. Each
value must be separated by a comma, without regard to the braces. The entire initialization set must be within
braces, and it must end with a semicolon.

4
Fundamentals of Programming I Introduction to Arrays and Functions

Function
Function is group of program statements that can act on data and return a value. Every C++ program has at least
one function, main ( ) and all the most trivial programs can define additional functions.
When your program starts, main ( )is called automatically. main ( )might call other functions, some of which
might call still others. The reason why we use functions is to aid modularization of a program. A function
reduces program size.
Any function has its own name, and when that name is encountered, the execution of the program branches to
the body of that function. When the function returns, execution resumes on the next line of the calling function.
The function body is placed in one place in memory. But it could be invoked in several places in the program.

Function Declaration / Prototype Declaration


As you can’t use variables before declarations (telling the compiler what the variable is), you can’t use function
before telling the compiler what this function is. The common approach to declare functions is at the beginning
of the program. A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function.

Example
void getnumber( ); this is a function declaration. Void shows that the function doesn’t have a return type.
Function declaration is terminated with semicolon. If the function has arguments, then they should be indicated
in the declaration.
Function Definition
A function definition consists of two parts: interface and body. The interface of a function (also called its
prototype) specifies how it may be used. It consists of three entities.
The general form of a C++ function definition is as follows:
return_typefunction_name ( parameter list )
{
body of the function
}
 The function name. This is simply a unique identifier.
 The function parameters (also called its signature). This is a set of zero or more typed identifiers used
for passing values to and from the function.

5
Fundamentals of Programming I Introduction to Arrays and Functions

 The function return type. This specifies the type of value the function returns.
A function which returns nothing should have the return type void. The body of a function contains the
computational steps (statements) that comprise the function.
Example// function returning the max between two numbers
int max(int num1, int num2) function header (interface)
{
// local variable declaration
int result;

if (num1 > num2) function body


result = num1;
else
result = num2;

return result;
}
The function body is placed in one place in memory. But it could be invoked in several places in the program.
Calling functions
Calling functions is invoking it to execute. The function call involves the function name, followed by
parentheses. The function call is similar to its declaration except that the return type is not mentioned. The call is
terminated by semi colon. Executing the call statement causes the function to execute, i.e. control is transferred
to the function, and the statements in the function definition are executed and then control returns to the
statement following the function call.

The following program demonstrates what we have discussed so far.


#include <iostream>
using namespace std;

// function declaration

6
Fundamentals of Programming I Introduction to Arrays and Functions

int max (int num1, int num2);

int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);

cout<< "Max value is : " << ret <<endl;

return 0;
}

// function returning the max between two numbers


int max(int num1, int num2)
{
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

A simple function
The example below shows the definition of a simple function which raises an integer to the power of another,
positive integer.

int Power (int base, unsigned int exponent)

{
int result = 1; 7
for (int i = 0;i< exponent ; + + i)
result *= base;
return result;
Fundamentals of Programming I Introduction to Arrays and Functions

The function interface starts with the return type of the function (int in this case). The function name appears
next followed by its parameter list. Power has two parameters (base and exponent) which are of type int and
unsigned int, respectively. Note that the syntax for parameters is similar to the syntax for defining variables: type
identifier followed by the parameter name. However, it is not possible to follow a type identifier with multiple
commas separated parameters like:

int Power (int base , exponent) // Wrong !


the for loop raises base to the power of exponent and stores the outcome in result. Finally, the function returns
result as the return value of the function. Below, example 2 illustrates how this function is called. The effect of
this call is that first the argument values 2 and 8 are respectively, assigned to the parameters base and exponent,
and then the function body is evaluated.
Example 2:

#include<iostream>
using namespace std;
void main
{ cout<<”2 ^ 8 = “<<Power (2, 8) <<endl;

When run, this program will produce the following output:


2^8 = 256
In general, a function should be declared before it is used.

Example 3:

#include<iostream>
using namespace std;
int Power (int base, unsigned int exponent); // Function declaration
void main
{
cout<< “2^8 = “<<Power (2, 8) <<endl;
}
int Power (int base, unsigned int exponent) 8
{
int result = 1;
for (int i = 0; i< exponent; + + i)
Fundamentals of Programming I Introduction to Arrays and Functions

Parameters and Arguments


While calling a function, there are two ways that arguments can be passed to a function:
Passing by value and by reference. A value parameter receives a copy of the value of the argument passed to it.
As a result, if the function makes any changes to the parameter, this will not affect the argument. For example, in
the following simple program:
#include<iostream>
#include<conio.h>
using namespace std;
void Foo (int num);
int main ()
{int x =10;
Foo (x);
cout<<” x = “<<x<<’\n’;
getch( );
return 0;
}
void Foo (int num)
{ num = 0;
cout<<”Num “<<num<<”\n”;
}
The single parameter of Foo is a value parameter. As far as this function is concerned, num behaves just like a
local variable inside the function. When the function is called and x passed to it, num receives a copy of the value

9
Fundamentals of Programming I Introduction to Arrays and Functions

of x. As a result, although num is set to 0 by the function, this does not affect x. the program produces the
following output.
Num = 0
x = 10
A reference parameter, on the other hand, receives the argument passed to it and works on it directly. Any
change made by the function to a reference parameter is in effect directly applied to the argument. Within the
context of function calls, the two styles of passing arguments are, respectively, called pass-by-value and pass-
by-reference. It is perfectly valid for a function to use pass-by-value for some of its parameters and pass-by-
reference for others. The former is used much more often in practice.
Example: We can rewrite the above example so that the value x is passed by reference
#include<iostream>
#include<conio.h>
using namespace std;
void Foo (int &num);
int main ()
{int x =10;
Foo (x);
cout<<” x= “<<x<<’\n’;
getch( );
return 0;
}
void Foo (int &num)
{ num = 0;
cout<<”Num “<<num<<”\n”;
}
The output is:
Num = 0
x=0
Another example
#include<iostream>

10
Fundamentals of Programming I Introduction to Arrays and Functions

#include<conio.h>
using namespace std;
void getdata (int &dividend, int &divisor);
void divide (int dividend, int divisor, int &quotient, int &reminder);
void print (int quotient, int reminder);
void main ( )
{
int a, b, c, d;
getdata (a, b);
divide (a, b, c, d);
print (c, d);
getch( );
}
void getdata (int &dividend, int &divisor)
{
cout<<”Enter two numbers:”;
cin>>dividend>>divisor;
}
voids divide (int dividend, int divisor, int &quotient, int &remainder)
{
quotient = dividend / divisor;
remainder = dividend % divisor;
}
void print (int quot, int remd)
{
cout<<”Quotient is = “<<quot<<endl;
cout<<”Remainder is = “<<remd<<endl;
}
Scope operator

11
Fundamentals of Programming I Introduction to Arrays and Functions

Because a local scope overrides the global scope, having a local variable with the same name as a global variable
makes the latter inaccessible to the local scope. For example, in
int x; // global variable
void main ( )
{
int x; // local variable
}
The global x is inaccessible inside main, because it is overridden by the local x parameter. This problem is
overcome using the unary scope operator:which takes a global entity as argument.
#include<iostream>
using namespace std;
int x = 12;
void main ( )
{
int x = 5;
if (x >= ::x)
cout<<”The local x is grater and its value is = “<<x<<endl;
}
else if (x = = ::x)
cout<<”Both are equal, the local x = “<<x<<” the global x is =”<<::x<<endl;
else
cout<<”The global x is greater and its value is = “<<::x<<endl;
}
Default Values for Parameters
When you define a function, you can specify a default value for each of the last parameters. This value will be
used if the corresponding argument is left blank when calling to the function.
This is done by using the assignment operator and assigning values for the arguments in the function definition.
If a value for that parameter is not passed when the function is called, the default given value is used, but if a
value is specified, this default value is ignored and the passed value is used instead. Consider the following
example:

12
Fundamentals of Programming I Introduction to Arrays and Functions

#include <iostream>
using namespace std;
int sum(int a, int b=20)
{
int result;
result = a + b;
return (result);
}
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;
// calling a function to add the values.
result = sum(a, b);
cout<< "Total value is :" << result <<endl;
// calling a function again as follows.
result = sum(a);
cout<< "Total value is :" << result <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total value is :300
Total value is :120
Overloaded functions
Two different functions can have the same name if the prototype of their arguments is different. That means that
you can give the same name to more than one function if they have either a different number of arguments or
different types in their arguments.
/* Example of function overloading */

13
Fundamentals of Programming I Introduction to Arrays and Functions

int test() { }
int test(int a){ }
int test(double a){ }
int test(int a, double b){ }
All 4 functions mentioned above are overloaded function. It should be noticed that, the return type of all 4
functions is same,i.e, int. Overloaded function may or may not have different return type but it should have
different argument(either type of argument or numbers of argument passed).
Example
#include<iostream>
using namespace std;
int divide (int a, int b = 2);
int divide (int z, int r, int y);
float divide (float a, float b);
int main ( )
{
int x = 20, y = 2;
float n = 5.0, m = 2.0;
cout<<divide (x, y);
cout<<divide (n, m);
cout<<endl;
cout<<divide (x, y, x);
cout<<endl;
return 0;
}
int divide (int a, int b)
{
return a / b;
}
int divide (int a, int b, int c)
{

14
Fundamentals of Programming I Introduction to Arrays and Functions

int w = a / b;
return w / c;
}
float divide (float x, float y)
{
return x / y;
}
In this case we have defined two functions with the same name, but one of them accept two arguments of type
int and the other accepts them of type float the compiler knows which one to call in each case by examining the
type when the function is called. If it is called with two ints as an argument it calls to the function that has two
int arguments in the prototype if is called with two floats it will call to the one which has two floats its
prototype.
For simplicity I have included the same code with both functions, but this is not compulsory. You can make two
functions with the same name but with completely different behavior.
Note: Return type of a function has no effect in overloading. That means, if the prototype of two functions is
differ by return type only, we can’t say that they are overloaded.
Recursion
A function which calls itself is said to be recursive. Recursion is a general programming technique applicable to
problems which can be defined in terms of themselves. Take the factorial problem, for instance, which is defined
as:
 Factorial of 0 is 1.
 Factorial of a positive number n is n times the factorial of n – 1.
The second line clearly indicates that factorial is defined in terms of itself and hence can be expressed as a
recursive function:
int Factorial (unsigned int n)
{
return n = 0? 1: Factorial (n—1);
}
For n set to 3, the table below provides a trace of the calls to Factorial.
Call N n==0 n * Factorial(n – 1 ) Returns

15
Fundamentals of Programming I Introduction to Arrays and Functions

First 3 0 3 * Factorial(2 ) 6
Second 2 0 2 * Factorial(1 ) 2
Third 1 0 1 * Factorial(0 ) 1
Fourth 0 1 1

A recursive function must have at least one termination condition which can be satisfied. Otherwise, the
function will call itself indefinitely until the run time stack overflows. The Factorial function, for example, has a
termination condition n = = 0 which, when satisfied, causes the recursive calls to fold back. (Note that for a
negative n this condition will never be satisfied and Factorial will fail).
As a general rule, all recursive functions can be rewritten using iteration. In situations where the number of stack
frames involved may be quite large, the iterative version preferred. In other cases, the elegance and simplicity of
the recursive version may give it the edge. For factorial, for example, a very large argument will lead to as many
stack frames. An iterative version is therefore preferred in this case:
#include<iostream>
using namespace std;
int Factorial (unsigned int n);
int main ( )
{
int n;
cout<<”Enter a positive number”;
cin>>n;
cout<<”!”<<n<<” = :”<< Factorial (n);
return 0;
}
int Factorial (unsigned int n)
{
if (n = = 0)
return 1;
else
return (n * (Factorial (n – 1)));}

16

You might also like