Functions and Arrays in C++
Functions and Arrays in C++
A function is block of code which is used to perform a particular task, for example
let’s say you are writing a large C++ program and in that program you want to do a
particular task several number of times, like displaying value from 1 to 10, in order to
do that you have to write few lines of code and you need to repeat these lines every
time you display values. Another way of doing this is that you write these lines inside
a function and call that function every time you want to display values. This would
make your code simple, readable and reusable.
Syntax of Function
#include <iostream>
#include<conio >
using namespace std; /* This function adds two integer values * and returns the result
*/
int sum(int num1, int num2)
{ int num3 = num1+num2;
return num3;
}
int main()
{ //Calling the function
clrscr();
cout<<sum(1,99);
return 0;
}
Output:
100
The same program can be written like this: Well, I am writing this program to let
you understand an important term regarding functions, which is function declaration.
Lets see the program first and then at the end of it we will discuss function
declaration, definition and calling of function.
#include <iostream>
using namespace std;
//Function declaration
int sum(int,int);
//Main function
int main()
{
clrscr();
//Calling the function
cout<<sum(1,99);
return 0;
}
/* Function is defined after the main method
*/
int sum(int num1, int num2)
{
int num3 = num1+num2;
return num3;
}
Function Declaration: You have seen that I have written the same program in two
ways, in the first program I didn’t have any function declaration and in the second
program I have function declaration at the beginning of the program. The thing is that
when you define the function before the main() function in your program then you
don’t need to do function declaration but if you are writing your function after the
main() function like we did in the second program then you need to declare the
function first, else you will get compilation error.
syntax of function declaration:
return_type function_name(parameter_list);
Note: While providing parameter_list you can avoid the parameter names, just like I
did in the above example. I have given int sum(int,int); instead of int sum(int
num1,int num2);.
Function definition: Writing the full body /code of function is known as defining a
function.
syntax of function definition:
return_type function_name(parameter_list)
{
//Statements inside function
}
Calling function: We can call the function like this:
function_name(parameters);
Now that we understood the working of function, lets see the types of function in
C++
Types of function
We have two types of function in C++:
1) Built-in functions/library functions
2) User-defined functions
1) Built-in functions
Built-in functions are also known as library functions. We need not to declare and
define these functions as they are already written in the C++ libraries such as
iostream, cmath etc. We can directly call them when we need.
Example: C++ built-in function example
Here we are using built-in function pow(x,y) which is x to the power y. This function
is declared in math header file so we have included the file in our program using
#include directive.
#include <iostream>
#include <math>
using namespace std;
int main()
{
/* Calling the built-in function
* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}
Output:
32
2) User-defined functions
We have already seen user-defined functions, the example we have given at the
beginning of this tutorial is an example of user-defined function. The functions that
we declare and write in our programs are user-defined functions. Lets see another
example of user-defined functions.
User-defined functions
#include <iostream>
#include <cmath>
using namespace std;
//Declaring the function sum
int sum(int,int);
int main(){
int x, y;
cout<<"enter first number: ";
cin>> x; 22
A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is main(), and all the most trivial programs can
define additional functions.
You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division usually is such that
each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body/code of the function.
The C++ standard library provides numerous built-in functions that your program
can call. For example, function strcat() to concatenate two strings,
function memcpy() to copy one memory location to another location and many more
functions.
A function is known with various names like a method or a sub-routine or a
procedure etc.
Defining a Function
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) { body of the function }
A C++ function definition consists of a function header and a function body. Here
are all the parts of a function −
• Return Type − A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
• Function Name − This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked,
you pass a value to the parameter. This value is referred to as actual
parameter or argument. The parameter list refers to the type, order, and
number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
• Function Body − The function body contains a collection of statements that
define what the function does.
Example
Following is the source code for a function called max(). This function takes two
parameters num1 and num2 and return the biggest of both −
// 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; }
Function Declarations
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required,
so following is also valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and
you call that function in another file. In such case, you should declare the function at
the top of the file calling the function.
Calling a Function
While creating a C++ function, you give a definition of what the function has to do.
To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called
function. A called function performs defined task and when it’s return statement is
executed or when its function-ending closing brace is reached, it returns program
control back to the main program.
To call a function, you simply need to pass the required parameters along with
function name, and if function returns a value, then you can store returned value. For
example −
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
//global function declaration
int main ()
{ // local variable declaration:
int a = 100; int b = 200; int ret;
// calling a function to get max value.
ret = max(&a, &b); -actual parameters/arguments
cout << "Max value is : " << ret << endl; return 0;
}
// function returning the max between two numbers
int max(int num1, int num2) –formal arguments/parameters
{ // local variable declaration
int result;
if (num1 > num2)
result = num1;
else result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code.
While running final executable, it would produce the following result −
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of
the arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a
function −
1 Call by Value
This method copies the actual value of an argument into the formal parameter of the function. In this
case, changes made to the parameter inside the function have no effect on the argument.
2 Call by Pointer
This method copies the address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. This means that changes made to the
parameter affect the argument.
3 Call by Reference
This method copies the reference of an argument into the formal parameter. Inside the function, the
reference is used to access the actual argument used in the call. This means that changes made to the
parameter affect the argument.
By default, C++ uses call by value to pass arguments. In general, this means that
code within a function cannot alter the arguments used to call the function and above
mentioned example while calling max() function used the same method.
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 −
#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
These are the variables or expressions These are the variables or expressions
referenced in the parameter list of a referenced in the parameter list of a
subprogram call. subprogram specification.
Actual Parameters are the parameters Formal Parameters are the parameters
which are in calling subprogram. which are in called subprogram.
Actual Parameters Formal Parameters
There is no need to specify datatype in The datatype of the receiving value must
actual parameter. be defined.
void main()
{int f=1,i=1,x;
cout<<”enter a number\n”;
cin>>x; 5
for(i=1;i<=x; i++)
{f=f*i;}
cout<<”factorial of “ <<x<<”=”<<f;
}
factorial of 5=120
C++ Recursion
A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
What is Recursion?
The process in which a function calls itself directly or indirectly is
called recursion and the corresponding function is called as recursive
function.
int main()
{
... .. ...
recurse();
... .. ...
}
The figure below shows how recursion works by calling itself over and over again.
#include <iostream>
using namespace std;
int main()
{
int n, result;
cout << "Enter a non-negative number: ";
cin >> n; 4
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n)
{
if (n > 1) {
return n * factorial(n - 1); 4*factorial(3)
3*factorial(2)
} else
{ 2*factorial(1)
return 1; 1*factorial(0)
4*3*2*1
}
}
Output
Enter a non-negative number: 4
Factorial of 4 = 24
Fibonacii series
Third term= first term +second term
Third term(1)=0+1
0 1 1 2 3 5 8 13 21 34
balance[4] = 50.0;
size of an array starts from 0 uptill n-1 terms
int n[5];
n[0]= 1st element
n[1]=2nd element
n[2]=3rd element
n[3]=4th element
n[4]=5th element
n[5]=?
The above statement assigns element number 5th in the array a value of 50.0. Array
with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of
their first element which is also called base index. Following is the pictorial
representaion of the same array we discussed above −
#include <iomanip>
using std::setw;
int main () {
return 0;
}
This program makes use of setw() function to format the output. When the above
code is compiled and executed, it produces the following result −
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Arrays in C++
Arrays are important to C++ and should need lots of more detail. There are following
few important concepts, which should be clear to a C++ programmer −
Sr.No Concept & Description
1 Multi-dimensional arrays
C++ supports multidimensional arrays. The simplest form of the multidimensional array is the tw
2 Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the array name, w
3 Passing arrays to functions
You can pass to the function a pointer to an array by specifying the array's name without an inde
4 Return array from functions
C++ allows a function to return an array.
void main()
{
int n[5],i;
for(i=0;i<5;i++)
{ cout<<” enter the elements of array n\n”; enter the elements of array n
12
cin>>n[i]; 14
11
2
19
}
for(i=0;i<5;i++)
{ cout<<” the elements of array n are”<<n[i]<<”\n”;
}
C++ Arrays
In this article, you will learn to work with arrays. You will learn to
declare, initialize and, access array elements in C++ programming.
To solve this problem in C++, you can create an integer array having
100 elements.
An array is a collection of data that holds fixed number of values of
same type. For example:
int age[100];
Here, the age array can hold maximum of 100 elements of integer
type.
The size and type of arrays cannot be changed after its declaration.
What is an ARRAY?
Arrays in C/C++
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
int main()
{
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";
return 0;
}
Output
Enter 5 numbers: 3
4
5
4
2
Sum = 18
int main()
{
int test[3][2] = {{2, -5},{4, 0},{9, 1}};
return 0;
}
Output
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1
int main()
{
int temperature[CITY][WEEK];
cout << "Enter all temperature for a week of first city and then
second city. \n";
return 0;
}
Output
Enter all temperature for a week of first city and then second city.
City 1, Day 1 : 32
City 1, Day 2 : 33
City 1, Day 3 : 32
City 1, Day 4 : 34
City 1, Day 5 : 35
City 1, Day 6 : 36
City 1, Day 7 : 38
City 2, Day 1 : 23
City 2, Day 2 : 24
City 2, Day 3 : 26
City 2, Day 4 : 22
City 2, Day 5 : 29
City 2, Day 6 : 27
City 2, Day 7 : 23
Displaying Values:
City 1, Day 1 = 32
City 1, Day 2 = 33
City 1, Day 3 = 32
City 1, Day 4 = 34
City 1, Day 5 = 35
City 1, Day 6 = 36
City 1, Day 7 = 38
City 2, Day 1 = 23
City 2, Day 2 = 24
City 2, Day 3 = 26
City 2, Day 4 = 22
City 2, Day 5 = 29
City 2, Day 6 = 27
City 2, Day 7 = 23
int main()
{
// This array can store upto 12 elements (2x3x2)
int test[2][3][2];
return 0;
}
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream.h>
int main()
{ int r, c, a[100][100], b[100][100], sum[100][100], i, j;
cout << "Enter number of rows (between 1 and 100): ";
cin >> r;
cout << "Enter number of columns (between 1 and 100): ";
cin >> c;
cout << endl << "Enter elements of 1st matrix: " << endl;
// Storing elements of first matrix entered by user.
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j]; }
//Displaying the elements of first matrix
cout<<” Display the elements of Matrix a”;
for(i = 0; i < r; i++)
{ for(j = 0; j < c; j++)
{ cout<<a[i][j] <<”\t”;
}
cout<<”\n”;
}
// Storing elements of second matrix entered by user.
cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> b[i][j]; }
//Displaying the elements of second matrix
cout<<” Display the elements of Matrix b”;
for(i = 0; i < r; i++)
{ for(j = 0; j < c; j++)
{ cout<<b[i][j] <<”\t”;
}
cout<<”\n”;
}
// Adding Two matrices
cout << endl << "Sum of two matrix is: " << endl;
// Displaying the resultant sum matrix.
for(i = 0; i < r; ++i)
{ for(j = 0; j < c; ++j)
{ cout << sum[i][j] << " \t "; }
cout << “\n”;
}
return 0;
}
Output
int main()
{
int i, n;
float arr[100];
cout << "Enter total number of elements(1 to 100): ";
cin >> n;
cout << endl;
return 0;
}
Output
Enter total number of elements: 8
Then, the program computes the transpose of the matrix and displays
it on the screen.
#include <iostream>
int main()
{ int a[10][10], trans[10][10], r, c, i, j;
cout << "Enter rows and columns of matrix: ";
cin >> r >> c; // Storing element of matrix entered by user in
array a[][].
cout << endl << "Enter elements of matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ cout << "Enter elements a" << i + 1 << j + 1 << ": ";
cin >> a[i][j]; } // Displaying the matrix a[ ][ ]
cout << endl << "Entered Matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ cout << " " << a[i][j];
if(j == c - 1)
cout << endl << endl; } // Finding transpose of matrix
a[][] and storing it in array trans[][].
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{ trans[j][i]=a[i][j]; }
// Displaying the transpose,i.e, Displaying array trans[][].
cout << endl << "Transpose of Matrix: " << endl;
for(i = 0; i < c; ++i)
for(j = 0; j < r; ++j)
{ cout << " " << trans[i][j];
if(j == r - 1)
cout << endl << endl; }
return 0; }
Output
#include <iostream.h>
int main()
{ string str[10], temp;
cout << "Enter 10 words: " << endl;
for(int i = 0; i < 10; ++i)
{ getline(cin, str[i]); }
Output
Enter 10 words:
C
C++
Java
Python
Perl
R
Matlab
Ruby
JavaScript
PHP
In lexicographical order: C
C++
Java
JavaScript
Matlab
PHP
Perl
Python
R
Ruby
#include<iostream>
#include<string.h>
int main()
{
char str[5][20], t[20];
int i, j;
cout<<"\n Enter Any Five Names : \n\n";
for(i=0; i<5; i++)
{
cout<<" ";
cin>>str[i];
}
for(i=1; i<5; i++)
{
for(j=1; j<5; j++)
{
if(strcmp(str[j-1], str[j])>0)
{
strcpy(t, str[j-1]);
strcpy(str[j-1], str[j]);
strcpy(str[j], t);
}
}
}
cout<<"\n Names Sorted in Alphabetical Order : \n\n";
for(i=0; i<5; i++)
{
cout<<" ";
cout<<str[i]<<"\n";
}
return 0;
}
Output: