0% found this document useful (0 votes)
59 views47 pages

Functions On C++-1

This document discusses various C++ functions including library functions, user-defined functions, function prototypes, passing arguments to functions, different types of user-defined functions, function overloading, storage classes, recursion, passing values by reference and value, arrays, multidimensional arrays, strings, structures, pointers to structures, and enumerations. Library functions are predefined functions that can be directly invoked, while user-defined functions must be declared and defined by the programmer. Functions allow code to be organized and reused through calls.

Uploaded by

Samwel Otieno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views47 pages

Functions On C++-1

This document discusses various C++ functions including library functions, user-defined functions, function prototypes, passing arguments to functions, different types of user-defined functions, function overloading, storage classes, recursion, passing values by reference and value, arrays, multidimensional arrays, strings, structures, pointers to structures, and enumerations. Library functions are predefined functions that can be directly invoked, while user-defined functions must be declared and defined by the programmer. Functions allow code to be organized and reused through calls.

Uploaded by

Samwel Otieno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Table of content:

Table of content:.........................................................................................................................................1
C++ functions...............................................................................................................................................1
Library Function...........................................................................................................................................1
User-defined Function.................................................................................................................................2
Function prototype(declaration).................................................................................................................4
Function Call................................................................................................................................................4
Passing Arguments to Function...................................................................................................................5
C++ User-defined Function Types.....................................................................................................6
1) Function with no argument and no return value................................................................7
2) Function with no arguments but return value.....................................................................7
3) Function with argument but no return value.......................................................................8
4) Function with arguments and return value..........................................................................9
Function overloading.............................................................................................................................9
Example 1: Function Overloading............................................................................................10
Example 2: Function Overloading............................................................................................11
C++ Storage Class.......................................................................................................................................12
Static Local variable...................................................................................................................................14
C++ Recursion......................................................................................................................................15
Example 1: C++ Recursion............................................................................................................15
Passing values in C++...........................................................................................................................18
1. Call by reference (pass values by reference)...............................................................................18
Example 1: Return by Reference.................................................................................................18
Important Things to Care While Returning by Reference.................................................19
call by reference..............................................................................................................................20
Using const.......................................................................................................................................20
Call by value....................................................................................................................................20
Simple functions................................................................................................................................21
Call by value....................................................................................................................................21
C++ Arrays.............................................................................................................................................21
Defining Arrays.................................................................................................................................21
Array Elements.................................................................................................................................22
Array Initialization.................................................................................................................................22
Example 1: C++ Array.....................................................................................................................23
C++ Multidimensional Arrays............................................................................................................24
Multidimensional Array Initialization...........................................................................................24
Initialization of three dimensional array.................................................................................25
Example 1: Two Dimensional Array........................................................................................25
Example 2: Two Dimensional Array............................................................................................26
Example 3: Three Dimensional Array.....................................................................................27
Passing Array to a Function in C++ Programming......................................................................................29
Passing Multidimensional Array to a Function.........................................................................31
Example 2: Passing Multidimensional Array to a Function..................................................31
C++ Program to display the elements of two dimensional array by passing it to a
function..............................................................................................................................................31
C++ Strings............................................................................................................................................32
C-strings.............................................................................................................................................32
Example 1: C++ String....................................................................................................................33
Example 2: C++ String....................................................................................................................34
Passing String to a Function.........................................................................................................34
C++ Structures......................................................................................................................................35
How to define a structure in C++ programming?.....................................................................35
How to define a structure variable?............................................................................................36
How to access members of a structure?...................................................................................36
Example 1: C++ Structure..............................................................................................................36
C++ Structure and Function..............................................................................................................37
Passing structure to function in C++...........................................................................................37
Example 1: C++ Structure and Function................................................................................38
Returning structure from function in C++..................................................................................39
C++ Pointers to Structure..................................................................................................................40
Example 1: Pointers to Structure.................................................................................................40
C++ Enumeration.................................................................................................................................42
Example 1: C++ Enumeration.......................................................................................................42
Example 2: C++ Enumeration.......................................................................................................43
C++ functions
In programming, function refers to a segment that groups codes to perform a specific task. Depending
on whether a function is predefined or created by programmer; there are two types of function:

1. Library Function

2. User-defined Function

Library Function
Library functions are the built-in function in C++ programming. Programmer can use library function by
invoking function directly; they don't need to write it themselves.

Example 1: Library Function

# include <iostream>

#include <cmath>

using namespace std;

int main() {

double number, squareRoot;

cout<<"Enter a number: ";

cin>>number;

/* sqrt() is a library function to calculate square root */

squareRoot = sqrt(number);

cout<<"Square root of "<<number<<" = "<<squareRoot;

return 0;

}
Output

Enter a number: 26

Square root of 26 = 5.09902

In example above, sqrt() library function is invoked to calculate the square root of a number. Notice
code #include <cmath> in the above program. Here, cmath is a header file. The function definition
of sqrt()(body of that function) is written in that file. You can use all functions defined in cmath when
you include the content of file cmath in this program using #include <cmath> .

Every valid C++ program has at least one function, that is, main() function.

User-defined Function
C++ allows programmer to define their own function. A user-defined function groups code to perform a
specific task and that group of code is given a name(identifier). When that function is invoked from any
part of program, it all executes the codes defined in the body of function.

How user-defined function works in C Programming?

Consider the figure above. When a program begins running, the system calls the main() function, that is,
the system starts executing codes from main() function. When control of program reaches
to function_name() inside main(), the control of program moves to void function_name(), all codes
inside void function_name() is executed and control of program moves to code right
after function_name() inside main() as shown in figure above.

Example 1: Function
C++ program to add two integers. Make a function add() to add integers and display sum in main()
function.

# include <iostream>

using namespace std;

int add(int, int); //Function prototype(declaration)

int main() {

int num1, num2, sum;

cout<<"Enters two numbers to add: ";

cin>>num1>>num2;

sum = add(num1,num2); //Function call

cout<<"Sum = "<<sum;

return 0;

int add(int a,int b) { //Function declarator

int add;

add = a+b;

return add; //Return statement

Output

Enters two integers: 8

-4

Sum = 4
Function prototype(declaration)
If an user-defined function is defined after main() function, compiler will show error. It is because
compiler is unaware of user-defined function, types of argument passed to function and return type.

In C++, function prototype is a declaration of function without function body to give compiler
information about user-defined function. Function prototype in above example:

int add(int, int);

You can see that, there is no body of function in prototype. Also there are only return type of arguments
but no arguments. You can also declare function prototype as below but it's not necessary to write
arguments.

int add(int a, int b);

Note: It is not necessary to define prototype if user-defined function exists before main() function.

Function Call
To execute the codes of function body, the user-defined function needs to be invoked(called). In the
above program, add(num1,num2); inside main() function calls the user-defined function. In the above
program, user-defined function returns an integer which is stored in variable add.

Function Definition

The function itself is referred as function definition. Function definition in the above program:

/* Function definition */

int add(int a,int b) { // Function declarator

int add;

add = a+b;

return add; // Return statement

When the function is called, control is transferred to first statement of function body. Then, other
statements in function body are executed sequentially. When all codes inside function definition is
executed, control of program moves to the calling program.
Passing Arguments to Function
In programming, argument (parameter) refers to data this is passed to function(function definition)
while calling function.

In above example, two variables, num1 and num2 are passed to function during function call. These
arguments are known as actual arguments. The value of num1 and num2 are initialized to
variables a and b respectively. These arguments a and b are called formal arguments. This is
demonstrated in figure below:

Notes on passing arguments

 The numbers of actual arguments and formals argument should be same. (Exception: Function
Overloading)

 The type of first actual argument should match the type of first formal argument. Similarly, type
of second actual argument should match the type of second formal argument and so on.

 You may call function without passing any argument. The number(s) of argument passed to a
function depends on how programmer want to solve the problem.

 In above program, both arguments are of int type. But it's not necessary to have both
arguments of same type.

Return Statement
A function can return single value to the calling program using return statement. In the above program,
the value of add is returned from user-defined function to the calling program using statement below:

return add;

The figure below demonstrates the working of return statement.

In the above program, the value of add inside user-defined function is returned to the calling function.
The value is then stored to a variable sum. Notice that, the variable returned, that is, add is of
type int and also sum is of int type. Also notice that, the return type of a function is defined in function
declarator int add(int a,int b). The int before add(int a,int b) means that function should return a value
of type int. If no value is returned to the calling function then, void should be used

C++ User-defined Function Types

For better understanding of arguments and return in functions, user-defined functions can
be categorised as:

 Function with no argument and no return value


 Function with no argument but return value
 Function with argument but no return value
 Function with argument and return value

Consider a situation in which you have to check prime number. This problem is solved below by making
user-defined function in 4 different ways as mentioned above.
1) Function with no argument and no return
value
# include <iostream>
using namespace std;

void prime();

int main() {
prime(); // No argument is passed to prime().
return 0;
}

// Return type of function is void because value is not returned.


void prime() {

int num, i, flag = 0;


cout<<"Enter a positive integer enter to check: "<<endl;
cin>>num;
for(i = 2; i <= num/2; ++i){
if(num%i == 0) {
flag=1;
break;
}
}
if (flag == 1) {
cout<<num<<" is not a prime number.";
}
else {
cout<<num<<" is a prime number.";
}
}

2)Function with no arguments but return value


#include <iostream>
using namespace std;

int prime();

int main() {
int num, i, flag = 0;
num = prime(); /* No argument is passed to prime() */
for (i = 2; i <= num/2; ++i) {
if (num%i == 0) {
flag = 1;
break;
}
}
if (flag == 1) {
cout<<num<<" is not a prime number.";
}
else {
cout<<num<<" is a prime number.";
}
return 0;
}

// Return type of function is int


int prime() {
int n;
printf("Enter a positive integer to check: ");
cin>>n;
return n;
}

3)Function with argument but no return value


#include <iostream>
using namespace std;

void prime(int n);

int main() {
int num;
cout<<"Enter a positive integer to check: ";
cin>>num;

prime(num); // Argument num is passed to function.


return 0;
}

// There is no return value to calling function. Hence, return type of function is void. */
void prime(int n) {
int i, flag = 0;
for (i = 2; i <= n/2; ++i) {
if (n%i == 0) {
flag = 1;
break;
}
}
if (flag == 1) {
cout<<n<<" is not a prime number.";
}
else {
cout<<n<<" is a prime number.";
}
}
4)Function with arguments and return value.
#include <iostream>
using namespace std;

int prime(int n);

int main() {
int num, flag = 0;
cout<<"Enter positive enter to check: ";
cin>>num;
flag = prime(num); /* Argument num is passed to check() function. */
if(flag == 1)
cout<<num<<" is not a prime number.";
else
cout<<num<<" is a prime number.";
return 0;
}

/* This function returns integer value. */


int prime(int n){
int i;
for(i = 2; i <= n/2; ++i){
if(n%i == 0)
return 1;
}
return 0;
}
All four programs above gives the same output and all are technically correct program. There is no hard
and fast rule on which method should be chosen. The particular method is chosen depending upon the
situation and how a programmer want to solve that problem.

Function overloading
In C++ programming, two functions can have same identifier(name) if either number of arguments or
type of arguments passed to functions are different. These types of functions having similar name are
called overloaded functions.

/* Example of function overloading */

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). Two functions
shown below are not overloaded functions because they only have same number of arguments and
arguments in both functions are of type int.

/* Both functions has same number of argument and same type of


argument*/

/* Hence, functions mentioned below are not overloaded functions.


*/

/* Compiler shows error in this case. */

int test(int a){ }

double test(int b){ }

Example 1: Function Overloading


/*Calling overloaded function test() with different argument/s.*/

#include <iostream>
using namespace std;
void test(int);
void test(float);
void test(int, float);
int main() {
int a = 5;
float b = 5.5;

test(a);
test(b);
test(a, b);

return 0;
}

void test(int var) {


cout<<"Integer number: "<<var<<endl;
}

void test(float var){


cout<<"Float number: "<<var<<endl;
}
void test(int var1, float var2) {
cout<<"Integer number: "<<var1;
cout<<" And float number:"<<var2;
}

Output

Integer number: 5

Float number: 5.5

Integer number: 5 And float number: 5.5

In above example, function test() is called with integer argument at first. Then, function test() is called
with floating point argument and finally it is called using two arguments of type int and float. Although
the return type of all these functions is same, that is, void, it's not mandatory to have same return type
for all overloaded functions. This can be demonstrated by example below.

Example 2: Function Overloading


/* C++ Program to return absolute value of variable types
integer and float using function overloading */

#include <iostream>
using namespace std;

int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;

cout<<"Absolute value of "<<a<<" = "<<absolute(a)<<endl;


cout<<"Absolute value of "<<b<<" = "<<absolute(b);
return 0;
}

int absolute(int var) {


if (var < 0)
var = -var;
return var;
}

float absolute(float var){


if (var < 0.0)
var = -var;
return var;
}

Output

Absolute value of -5 = 5

Absolute value of 5.5 = 5.5

In above example, two functions absolute() are overloaded. Both take single argument but one takes
integer type argument and other takes floating point type argument. Function absolute() calculates the
absolute value of argument passed and returns it.

C++ Storage Class


Every variable in C++ has a type which specifies the type of data that can be stored in a variable. For
example: int, float, char etc. Also variables and objects in C++ have another feature called storage class.
Storage class specifiers control two different properties: storage duration (determines how long a
variable can exist) and scope (determines which part of the program can access it). The variables can be
divided into 4 ways depending upon the storage duration and scope of variables.

 Local variable
 Global variable
 Static local variable

Local Variable

A variable defined inside a function (defined inside function body between braces) is a local variable.
Local variables are created when the function containing local variable is called and destroyed when that
function returns. Local variables can only be accessed from inside a function in which it exists. Consider
this example:

#include <iostream>
using namespace std;

void test();

int main() {
int var = 5; // local variable to main()
test();
var1 = 9; // illegal: var1 not visible inside main()
}
void test() {
int var1; // local variable to test()
var1 = 6;
cout<<var; // illegal: var not visible inside test()
}
The variable var cannot be used inside test() and var1 cannot be used inside main() function.

Keyword auto could also be used for defining local variables (it was optional but not necessary) before
as: auto int var; but, after C++11 auto has different meaning and should not be used for defining local
variables as variables defined inside a function is a local variable by default.

Global Variable
If a variable is defined outside any function, then that variable is called a global variable. Any part of
program after global variable declaration can access global variable. If a global variable is defined at the
beginning of the listing, global variable is visible to all functions. Consider this example:

/* In this example, global variable can be accessed by all functions because


it is defined at the top of the listing.*/

#include <iostream>
using namespace std;
int c = 12;

void test();

int main() {
++c;
cout<<c<<endl; //Output: 13
test();
return 0;
}

void test() {
++c;
cout<<c; //Output: 14
}
In the above program, c is a global variable. This variable is visible to both functions in the above
program.

The memory for global variable is set when program starts and exist until program ends.

Static Local variable

Keyword  static  is used for specifying static variable. For example:
... .. ...

int main() {

static float a;

... .. ...

A static local variable exist only inside a function in which it is declared(similar to local variable) but the
lifetime of static variable starts when the function containing static variable is called and ends when the
program ends. The main difference between local variable and static variable is that, the value of static
variable persist until the program ends. Consider this example:

#include <iostream>
using namespace std;

void test() {
static int var = 0; // var is a static variable;
++var;
cout<<var<<endl;
}
int main() {

test();
test();
return 0;
}

Output

In the above program, test() function is invoked 3 times. During first call, variable var is declared as static
variable and initialized to 0. Then 1 is added to var which is displayed in the screen. When the function
test() returns, variable var still exist because it is a static variable. During second function call, no new
variable var is created. Only var is increased by 1 and then displayed to the screen.

Output of above program if  var  was not specified as static variable
1

C++ Recursion
In many programming languages including C++, it is possible to call a function from a same function. This
function is known as recursive function and this programming technique is known as recursion. 

To understand recursion, you should have knowledge of two important aspects:

In recursion, a function calls itself but you shouldn't assume these two functions are same function.
They are different functions although they have same name.

Local variables: Local variables are variables defined inside a function and has scope only inside that
function. In recursion, a function call itself but these two functions are different functions (You can
imagine these functions are function1 and function 2. The local variables inside function1 and function2
are also different and can only be accessed within that function.

Consider this example to find factorial of a number using recursion.

Example 1: C++ Recursion


#include <iostream>
using namespace std;

int factorial(int);

int main() {
int n;
cout<<"Enter a number to find factorial: ";
cin>>n;
cout<<"Factorial of "<<n<<" = "<<factorial(n);
return 0;
}

int factorial(int n) {
if (n>1) {
return n*factorial(n-1);
}
else {
return 1;
}
}
Output

Enter a number to find factorial: 4

Factorial of 4 = 24

Explanation: How recursion works?

Suppose user enters 4 which is passed to function factorial(). Here are the steps involved:
 In first factorial() function, test expression inside if statement is true. The statement return
num*factorial(num-1); is executed, which calls second factorial() function and argument passed
is num-1 which is 3.
 In second factorial() function, test expression inside if statement is true. The statement return
num*factorial(num-1); is executed, which calls third factorial() function and argument passed
is num-1 which is 2.
 In third factorial() function, test expression inside if statement is true. The statement return
num*factorial(num-1); is executed, which calls fourth factorial() function and argument passed
is num-1 which is 1.
 The fourth factorial() function, test expression inside if statement is false. The statement return
1; is executed, which returns 1 to third factorial() function.
 The thrid factorial() function returns 2 to second factorial() function.
 The second factorial() function returns 6 to first factorial() function.
 Finally, first factorial() function returns 24 to the main() function and is displayed.

C++ Return by Reference

Passing values in C++


There are many ways to get values in and out of functions, some of which only pertain to member
functions

The following are two main ways in which functions receive their values

1. Call by reference -
2. Call by value-

1. Call by reference (pass values by reference)


In call by reference, original value is changed or modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments shares the
same address space. Hence, any value changed inside the function, is reflected inside as well as
outside the function.

Consider this example:

Example 1: Return by Reference


#include <iostream>
using namespace std;
int n;
int& test();

int main() {
test() = 5;
cout<<n;
return 0;
}

int& test() {
return n;
}

Output

Explanation

In program above, the return type of function   test()   is  int& . Hence this function returns by
reference. The return statement is   return n;   but unlike return by value. This statement doesn't
return value of n , instead it returns variable n  itself.

Then the variable n  is assigned to the left side of code  test() = 5;   and value of n  is displayed.

Important Things to Care While Returning by Reference.


int& test() {

int n = 2;

return n;

 Ordinary function returns value but this function doesn't. Hence, you can't return constant from this
function.

 int& test() {
 return 2;

 You can't return a local variable from this function.

Example 2
call by reference

int triple(int& number) { // note the ampersand

number=number*3;

return number;

int main() {

i=7;

int j = triple(i)

Here number is a sort of alias for main's i. After the call to triple, main's i will be 21, and so will j.
Using const
The const keyword can be used in several ways to prevent values being changed. For example, were
the previous example's triple changed to the following, the code wouldn't compile, because number can't
be changed.

int triple(const int& number) {

number=number*3;

return number;

}
NB:. By careful use of const you can make your code safer, ensuring that variables that shouldn't
change are protected from accidental modification.

Call by value

In call by value, original value can not be changed or modified. In call by value, when you

passed value to the function it is locally stored by the function parameter in stack memory

location. If you change the value of function parameter, it is changed for the current function only

but it not change the value of variable inside the caller function such as main().

Alternative explanation for Call by value


When passing data by value, the data is copied to a local variable/object in the function. Changes to
this data are not reflected in the data of the calling function

Simple functions
Here's a simple function which given an integer returns 3 times that integer

Call by value

int triple(int number) {

number=number*3;

return number;

int main() {

i=7;

int j = triple(i)

i is "passed by value", meaning that number is initially given the value that i has, but after that there's
no connection between the variables. At the end i will be 7 and j will be 21.
Difference between call by value and call by reference.

call by value call by reference

This method copy original value into This method copy address of arguments into
1
function as a arguments. function as a arguments.

Changes made to the parameter inside Changes made to the parameter affect the
2 the function have no effect on the argument. Because address is used to access the
argument. actual argument.

Actual and formal arguments will be Actual and formal arguments will be created in
3
created in different memory location same memory location

Note: By default, C++ uses call by value to pass arguments

C++ Arrays
In programming, one of the frequently arising problem is to handle similar types of data. Consider this
situation: You have to store marks of more than one student depending upon the input from user. These
types of problem can be handled C++ programming(almost all programming language have arrays) using
arrays.

An array is a sequence of variable that can store value of one particular data type. For example: 15 int
type value, 105 float type value etc.

Defining Arrays
type array_name[size];

Consider this code.

int test[85];

The above code creates an array which can hold 85 elements of   int   type.

Array Elements
The maximum number of elements an array can hold depends upon the size of an array. Consider this
code below:

int age[5];

This array can hold 5 integer elements.

Notice that the first element of an array is   age[0]   not  age[1] . This array has 5 elements and notice
fifth is  age[4]   not age[5] . C++ programmer should always keep this is mind as it may differ from other
programming languages.

Array Initialization

Array can be initialized at the time of declaration. For example:

float test[5] = {12, 3, 4, -3, 9};

It is not necessary to write the size of an array during array declaration.

float test[] = {12, 3, 4, -3, 9};

I prefer writing size of array during array declaration because it quickly gives the information on size of
an array while help me in debugging code.

Example 1: C++ Array


C++ Program to store 5 numbers entered by user in an array and display first and last number only.

#include <iostream>
using namespace std;

int main() {
int n[5];
cout<<"Enter 5 numbers: ";
/* Storing 5 number entered by user in an array using for loop. */
for (int i = 0; i < 5; ++i) {
cin>>n[i];
}

cout<<"First number: "<<n[0]<<endl; // first element of an array is n[0]


cout<<"Last number: "<<n[4]; // last element of an array is n[SIZE_OF_ARRAY - 1]
return 0;
}

Output

Enter 5 numbers: 4

-3

First number: 4

Last number: 0
C++ Multidimensional Arrays
In arrays , you learned about one dimensional array, that is, single variables specifies array. C++ allows
programmer to create array of an array known as multidimensional arrays. Consider this example:

int x[3][4];

Here, x  is a two dimensional array. This array can hold 12 elements. You can think this array as table
with 3 row and each row has 4 column.

Three dimensional also array works in similar way. For example:

float x [2][4][3];

This array x  can hold 24 elements. You can think this example as: Each 2 elements can hold 4 elements,
which makes 8 elements and each 8 elements can hold 3 elements. Hence, total number of elements
this array can hold is 24.

Multidimensional Array Initialization


You can initialize a multidimensional array in more than one way. Consider this example to initialize two
dimensional array.

int test[2][3] = {2, 4, -5, 9, 0, 9};

Better way to initialize this array with same array elements as above.
int test[2][3] = { {2, 4, 5}, {9, 0 0}};

Initialization of three dimensional array


int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23,

2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};

Better way to initialise this array with same elements as above.

int test[2][3][4] = {

{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },

{ {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }

};

Example 1: Two Dimensional Array


C++ Program to display all elements of an initialised two dimensional array.
#include <iostream>
using namespace std;

int main() {
int test[3][2] = {
{2, -5},
{4, 0},
{9, 1}
};
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 2; ++j) {
cout<< "test["<< i << "][" << ;j << "] = " << test[i][j]<<endl;
}
}
return 0;
}

test[0][0] = 2

test[0][1] = -5

test[1][0] = 4

test[1][1] = 0

test[0][2] = 9
test[1][2] = 1

Example 2: Two Dimensional Array


C++ Program to store temperature of two different cities for a week and display it.

#include <iostream>
using namespace std;
const int CITY = 2;
const int WEEK = 7;

int main() {
int temperature[CITY][WEEK];
cout<<"Enter all temperature for a week of first city and then second city. \n" ;
for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
cout<<"City "<<i+1<<", Day "<<j+1<<" : ";
cin>>temperature[i][j];
}
}
cout<<"\n\nDisplaying Values:\n";
for (int i = 0; i < CITY; ++i) {
for(int j = 0; j < WEEK; ++j) {
cout<<"City "<<i+1<<", Day "<<j+1<<" = "<< temperature[i][j]<<endl;
}
}
return 0;
}

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
Example 3: Three Dimensional Array
C++ Program to Store value entered by user in three dimensional array and display it.
#include <iostream>
using namespace std;

int main() {
int test[2][3][2]; // this array can store 12 elements
cout<<"Enter 12 values: \n";
for(int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for(int k = 0; k < 2; ++k ) {
cin>>test[i][j][k];
}
}
}
cout<<"\nDisplaying Value stored:"<<endl;
/* Displaying the values with proper index. */
for(int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for(int k = 0; k < 2; ++k ) {
cout<< "test["<<i<<"]["<<j<<"]["<<k<<"] = "<< test[i][j][k]<<endl;
}
}
}

return 0;
}
Output

Enter 12 values:

9
10

11

12

Displaying Value stored:

test[0][0][0] = 1

test[0][0][1] = 2

test[0][1][0] = 3

test[0][1][1] = 4

test[0][2][0] = 5

test[0][2][1] = 6

test[1][0][0] = 7

test[1][0][1] = 8

test[1][1][0] = 9

test[1][1][1] = 10

test[1][2][0] = 11

test[1][2][1] = 12

As the number of dimension increases, the complexity also increases tremendously


although the concept is quite similar.

Passing Array to a Function in C++ Programming


Arrays can be passed to a function as an argument. Consider this example to pass one-dimensional array
to a function:

Example 1: Passing One-dimensional Array to a


Function
C++ Program to display marks of 5 students by passing one-dimensional array to a
function.

#include <iostream>
using namespace std;
void display(int marks[5]);

int main() {
int marks[5] = {88, 76, 90, 61, 69};
display(marks);
return 0;
}

void display(int m[5]) {


cout<<"Displaying marks: "<<endl;
for (int i = 0; i <5; ++i) {
cout<<"Student "<<i+1<<": "<<m[i]<<endl;
}
}

Output

Displaying marks:

Student 1: 88

Student 2: 76

Student 3: 90

Student 4: 61

Student 5: 69

When an array is passed as an argument to a function, only the name of an array is used as
argument.

display(marks);
Also notice the difference while passing array as an argument rather than variable.

void display(int m[5]);

The argument used marks in the above code represents the memory address of first element of
array marks[5]. And the formal argument int m[5] in function declaration decays to int* m;. That's
why, although the function is manipulated in the user-defined function with different array name m[5],
the original array is manipulated. The C++ programming language handles passing array to a function in
this way to save memory and time.

Note: You need to have understanding of pointers to understand passing array to a function. Learn
more: Call by reference

Passing Multidimensional Array to a Function


Multidimensional array can be passed in similar way as one-dimensional array. Consider this example to
pass two dimensional array to a function:

Example 2: Passing Multidimensional Array to a


Function

C++ Program to display the elements of two dimensional array by passing it to a


function.

#include <iostream>
using namespace std;
void display(int n[3][2]);

int main() {
int num[3][2] = {
{3, 4},
{9, 5},
{7, 1}

};
display(num);
return 0;
}
void display(int n[3][2]) {

cout<<"Displaying Values: "<<endl;


for(int i = 0; i < 3; ++ i) {
for(int j = 0; j < 2; ++j) {
cout<<n[i][j]<<" ";
}
}
}

Output

Displaying Values:

3 4 9 5 7 1

Multidimensional array with dimension more than 2 can be passed in similar way as two dimensional
array.

C++ Strings

There are two types of strings commonly use in C++ programming language:

 Strings that are objects of string class (The Standard C++ Library string class)
 C-strings (C-style Strings)

C-strings
In C programming, only one type of string is available and this is also supported in C++ programming.
Hence it's called C-strings. C-strings are the arrays of type   char   terminated with null character, that is,  \
0   (ASCII value   of null character is 0). Consider this example:

char str[] = "C++";

In the above code,  str   is a string and it holds 4 character. Although, " C++ " has 3 character, the null
character  \0  is added to the end of the string automatically.
 

Other ways of defining the string:

char str[4] = "C++";

char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};

Like arrays, it is not necessary to use all the space allocated for the string. For example:

char str[100] = "C++";

Example 1: C++ String


C++ program to display a string entered by user.

#include <iostream>
using namespace std;

int main() {
char str[100];
cout<<"Enter a string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
cout<<"\nEnter another string: ";
cin>>str;
cout<<"You entered: "<<str<<endl;
return 0;
}

Output
Enter a string: C++

You entered: C++

Enter another string: Programming is fun.

You entered: Programming

Notice that, in second example only "programming" is displayed instead of "Programming is fun". It is
because The extraction operator >> considers a space has a terminating character.

Example 2: C++ String


C++ program to read and display an entire line entered by user.

#include <iostream>
using namespace std;

int main() {
char str[100];
cout<<"Enter a string: ";
cin.get(str, 100);
cout<<"You entered: "<<str<<endl;
return 0;
}

Output

Enter a string: Programming is fun.

You entered: Programming is fun.

To read the text containing blank space,  cin.get   function can be used. This function takes two
arguments. First argument is the name of the string(address of first element of string) and second
argument is the maximum size of the array.

Passing String to a Function


Strings are passed to a function in a similar way  arrays are passed to a function .
#include <iostream>
using namespace std;
void display(char s[]);

int main() {
char str[100];
cout<<"Enter a string: ";
cin.get(str, 100);
display(str);
return 0;
}

void display(char s[]) {


cout<<"You entered: "<<s;
}

Output

Enter a string: Programming is fun.

You entered: Programming is fun.

C++ Structures
Structure is the collection of variables of different types under a single name for better visualisation of
problem. Arrays is also collection of data but arrays can hold data of only one type whereas structure
can hold data of one or more types.

How to define a structure in C++ programming?


The struct keyword defines a structure type followed by an identifier(name of the structure). Then
inside the curly braces, you can declare one or more members (declare variables inside curly braces) of
that structure. For example:

struct person {

char name[50];

int age;

float salary;

};

Here a structure person is defined which has three members: name, age and salary.


When a structure is created, no memory is allocated. The structure definition is only the blueprint for
the creating of variables. You can imagine it as a datatype. When you define an integer as below:

int foo;

The int specifies that, variable foo can hold integer element only. Similarly, structure definition only
specifies that, what property a structure variable holds when it is defined.

How to define a structure variable?


Once you declare a structure person as above. You can define a structure variable as:

person bill;

Here, a structure variable bill is defined which is of type structure person. When structure variable is
defined, then only the required memory is allocated by the compiler. Considering you have either 32-bit
or 64-bit system, the memory of float is 4 bytes, memory of int is 4 bytes and memory of char is 1
byte. Hence, 58 bytes of memory is allocated for structure variable bill.

How to access members of a structure?


The members of structure variable is accessed using dot operator. Suppose, you want to access age of
structure variable bill and assign it 50 to it. You can perform this task by using following code below:

bill.age = 50;

Example 1: C++ Structure


C++ Program to assign data to members of a structure variable and display it.

#include <iostream>
using namespace std;

struct person {
char name[50];
int age;
float salary;
};

int main() {
person p1;

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

return 0;
}

Output

Enter Full name: Magdalena Dankova

Enter age: 27

Enter salary: 1024.4

Displaying Information.

Name: Magdalena Dankova

Age: 27

Salary: 1024.4

Here a structure person is declared which has three members. Inside main() function, a structure


variable p1 is defined. Then, the user is asked to enter information and data entered by user is
displayed.

C++ Structure and Function


Structure variables can be passed to a function and returned from a function in similar way as normal
arguments:
Passing structure to function in C++
A structure variable can be passed to a function in similar way as normal argument. Consider this
example:

Example 1: C++ Structure and Function


#include <iostream>
using namespace std;

struct person {
char name[50];
int age;
float salary;
};

void displayData(person); // Function declaration

int main() {

person p;

cout << "Enter Full name: ";


cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;

displayData(p); // Function call with structure variable as arugment

return 0;
}

void displayData(person p1) {

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

Output

Enter Full name: Bill Jobs

Enter age: 55
Enter salary: 34233.4

Displaying Information.

Name: Bill Jobs

Age: 55

Salary: 34233.4

In this program, user is asked to enter the data for the members of a structure variable
inside  main()   function. Then that structure variable to passed to a function using code.

displayData(p);

The return type of  displayData()   is  void   and one argument of type structure  person  is passed.
The function prototype also should match the function definition. Then the members of structure   p1   is
displayed from this function.

Returning structure from function in C++


#include <iostream>
using namespace std;

struct person {
char name[50];
int age;
float salary;
};

person getData(person);
void displayData(person);

int main() {

person p;

p = getData(p);
displayData(p);

return 0;
}

person getData(person p1) {

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
return p1;

void displayData(person p1) {

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

The output of this program is same as program above.

In this program, the structure variable  p  of type structure person  is defined under  main()   function.
The structure variable p  is passed to  getData()   function which takes input from user and that value is
stored in member function of structure variable  p1  which is then returned to main function.

p = getData(p);

Note:  The value of all members of a structure variable can be assigned to another structure using
assignment operator  =  if both structure variables are of same type. You don't need to manually assign
each members.

Then the structure variable p  is passed to  displayData()   function, which displays the information.

C++ Pointers to Structure


A pointer variable can be created not only for native types like ( int, float, double etc.) but they can
also be created for user defined types like structure. For example:

#include <iostream>
using namespace std;

struct temp {
int i;
float f;
};

int main() {
temp *ptr;
return 0;
}
This program creates a pointer ptr of type structure temp.
Example 1: Pointers to Structure
#include <iostream>
using namespace std;

struct Distance {
int feet;
float inch;
};

int main() {
Distance *ptr, d;

ptr = &d;

cout << "Enter feet: ";


cin >> (*ptr).feet;
cout << "Enter inch: ";
cin >> (*ptr).inch;

cout << "Displaying information." << endl;


cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";

return 0;
}

Output

Enter feet: 4

Enter inch: 3.5

Displaying information.

Distance = 4 feet 3.5 inches

In this program, a pointer variable ptr and normal variable d of type structure Distance is defined.


The address of variable d is stored to pointer variable, that is, ptr is pointing to variable d. Then the
member function of variable d is accessed using pointer.

Note: Since pointer ptr is pointing to variable d in this


program,  (*ptr).inch  and  d.inch  is exact same cell. Similarly,  (*ptr).feet  and  d.feet  is
exact same cell.

The syntax to access member function using pointer is ugly and there is alternative
notation -> which is more common.
ptr->feet is same as (*ptr).feet

ptr->inch is same as (*ptr).inch

C++ Enumeration

An enumeration is a user-defined type whose value is restricted to one of several explicitly


named constants(enumerators). Enumeration are defined using keyword:  enum.

enum seasons { spring, summer, autumn, winter };

This code is a enum declaration. After declaration, you can define variable of type seasons. And this
variable of type seasons can only have one of those 4 values. For example:

C++ program to define enumeration type and assign value to variable of that type.

#include <iostream>
using namespace std;

enum seasons { spring, summer, autumn, winter };

int main() {

seasons s;
s = autumn; // Correct
s = rainy; // Error
return 0;
}
In this program, an enum type seasons is declared with 4 enumerators
(spring, summer, autumn, winter). Then, inside main() function, a variable s of type seasons is
defined. This variable s can only store any one of four values (spring, summer, autumn, winter).

By default, the value of first enumerator is 0, second is 1 and so in. In this program, spring is equal to
0, summer is equal to 1 and autumn is 2 and winter is 3.

One very important thing to remember is that, spring, summer etc are not variables. They are treated
as integers by compiler. Hence, once enumerators are defined, their value can't be changed in program.

Example 1: C++ Enumeration


#include <iostream>
using namespace std;
enum seasons { spring, summer, autumn, winter };

int main() {

seasons s;

s = spring;
cout >> "spring = " >> s >> endl;

s = summer;
cout >> "summer = " >> s >> endl;

s = autumn;
cout >> "autumn = " >> s >> endl;

s = winter;
cout >> "winter = " >> s >> endl;

return 0;
}

Output

spring = 0

summer = 1

autumn = 2

winter = 3

You can change the default value during enumeration declaration (after declaration, you cannot change
it) and give them another value. Consider this example:

Example 2: C++ Enumeration


#include <iostream>
using namespace std;

enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main() {

seasons s;

s = summer;
cout << "summer = " << s << endl;

return 0;
}

Output

summer = 4

In this program, the enumerations are given the different integer value than default value.

You might also like