Professional Documents
Culture Documents
Arrays and
Functions
ARRAYS IN C++
arrayExample[“<<i<<”]: ” ; prompts
the user to enter .an integer value
The values entered are stored in their
respective positions within the array as shown in figure(i) below:
0
1
2
3
4
5
6
7
8
9
Display of integers as entered by the user
The second for loop outputs the integer values entered by the user. The output is:
0:1
1:2
2:3
3:4
4:5
5:6
6:7
7:8
8:9
9:10
INITIALIZATION OF ARRAYS
An array can be initialized by specifying the
type, name, subscript, assignment operator,
opening brace, elements (separated by
commas), closing brace, and semi-colon.
Example 3
int studentMarks [7] = {75, 60, 80, 68, 78,
82, 71};
This array has seven elements of integer
type.
MULTIDIMENSIONAL ARRAYS
in input and expects the user to hit the return key. This
command keeps the window from closing because the
program is not done yet because it waits for the hitting
of the enter key. Inclusion of that line gives time to the
programmer to see running of the program.
The output
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
1, 2, 3, 4
REVISION EXERCISE
computer screen
Demonstrate how you can initialize a 3 x 2
array
FUNCTIONS IN C++ LANGUAGE
A function is a block of code that performs a service.
Every C++ program has at least one function, namely;
the main function. This is the function that is
automatically called when a C++ program starts.
The Operating System (OS) installed in the computer
invokes the main () function to start a C++ program
whereas other functions are called from the main ()
function or from one another under the control of the
main () function. A C++ program is executed line by line
in the order it appears in the source code, until a function
is called. Then the program branches off to execute the
function. When the function completes the execution, it
returns control to the next line in the calling function.
Functions either return a value or void (i.e. return
nothing). For instance, a function that;
Adds two integers might return the sum, and thus would
declared void.
A well written function performs a specific task only and