Unit 1 Functions

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 43

Function

 A function can be thought of a user-define operator.


 It represents the set of instructions that are expected to work similarly on
various i/p given to it.
 Functions are used to break up large programs into named sections.
 Functions are often used when the same piece of code has to run multiple
times. Function provide modularity to the program.
 Functions make programs reusable and readable.
Eg.
#include<iostream>
using namespace std;
void myprint();
int main()
{
MyPrint();
return 0;
}
void MyPrint()
{
cout<<“Printing from a function.\n”;
}
Example:
main()
{
message();
printf(“\n Hello”);
}
message()
{
cout<<“C++ programming!!”;
}

Here main() is calling the function message() means that the


control passes to the function message(). The activity of main() is
temporarily suspended , it falls asleep while the message() function
wakes up & goes to work.
When the message() function runs out of statement to execute ,
the control returns to main(), which begins to executing its code at the
exact point where it left off.
Thus main() becomes calling function & message() becomes
called function.
 While using function we have to do
1.function prototyping
2.function call
3.function definition.
Function Declaration or
Prototyping
 A declaration of function consist of function return type ,
the name of a function , & the parameter list.
 These three elements are referred to as function declaration
or function prototype.
Syntax

Function Prototype:

return_type function_name (type1 name1, type2 name2,


...
, type n name n);

Rules:

 A function must be declared in the program before it is called,


otherwise a compile time error results.
The parameters
Examples
#include<iostream>
int add(int a, int b)
{
int sum;
sum=a+b;
cout<<sum;
}
int main()
{
add(3);
return 0;
}
The example above will be compiled on many of the
compilers. They just give some warning, because the function add()
needs two parameters as input, not one. The result of this program
cannot be foreseen. It works because many C++ compilers do not check
for parameters matching either in type or count if declaration is not
done. The result is that you will spend a lot of time debugging programs,
because you made a mistake of passing on too many or too few parameters
to a function.
To solve this problem you can make use of function prototypes. If you use
prototypes, Compiler checks the types and count of the parameter list.

example:

#include<iostream>
int Add (int, int); //function prototype for Add
int main()
{
Add(3); /* <- There is the error ! */
return 0;
}
int Add(int a, int b)
{
int sum;
sum=a+b;
cout<<sum;
}

 When you try to compile this program, the compiler will flag an error
on the function call statement.
 So in the future, use function prototypes for every function to save
your lot of time!
Function Definition
 Here we write the actual code of the
function.
 A function can be defined only once in a
program.
Syntax
return_type function_name (type1 name1, type2 name2,
...,type n name n)
{
....statements...
}

Function header The parameters


Parts of function
 Return Type
 Name of function
 Parameter List
 Body of function
1.Return Type
 It indicates type of data returned by the function as a result of
it’s execution.
 A function that uses a return type void, mean that it returns
nothing. If u don’t want to return a result from function , then
use void return type instead of int, float etc.

2.Name of a function
Used to identify the function

3.Parameter List
This indicates the type & sequence of data type that
should be given as i/p to the function.
Body of a function
 Here we write a set of instruction that work
on the i/p data & generate the result.
Some examples
Function Prototype Examples
double squared (double number);
void print_report (int);
int get _menu_choice (void);
Function Definition Examples
double squared (double number) void parameter list means
{ it takes no parameters
return (number * number);
}
void print_report (int report_number)
{ if (report_number == 1)
cout<<“Print Report 1”; return type void means
it returns nothing
else
cout<<“Not printing Report 1”;
}
Function Arguments
A function represents the set of instruction to be
executed on the data that is given to it at the time of calling
it.
There are 2 ways in which this data can be given to
the function.
1) By value and
2) By reference

1) Passing values
passing values is known as call by value. It is actually
pass a copy of the variable to the function. If the function
modifies the copy , the original remains unaltered.
This creates a copy of i/p data which is local for the
function. The function uses the values from these local copies
& returns the o/p.
Example-
Write a program for doing addition of 3 nos. using function.
int calsum(int, int, int);
 void main()
{
int num1,num2,num3,sum;
cout<<“enter 3 nos.”;
cin>>num1>>num2>>num3;
sum=calsum(num1,num2,num3);
cout<<sum;
}
int calsum(int x,int y,int z)
{
int sum1;
sum1=x+y+z;
return(sum1);
}
Return Statement
 To return a value from a C++
function you must explicitly return
it with a return statement.
 A return statement is placed within
the body of a function.
 This statement terminates the
function that is currently executed.
Local Variables
 Local Variables
int func1 (int y)
{
int a, b = 10;
float rate;
double cost = 12.55;
.......
}

 Those variables declared “within” the function are


considered “local variables”.
 They can only be used inside the function they were
declared in, and not elsewhere.
Call By reference:

 void sum(int *, int *)


 int main()
 {
 int num1,num2;
cout<<“Enter the two numbers”;
 cin>>num1>>num2;
 sum(&num1, &num2);
 }
 void sum(int *x, int *y)
 {
 int sum1;
 sum1=*x+*y;
 cout<<“sum of two numbers is”<<sum1;
 }

 Check Whether Number is Even
or Odd using Functions
Check Whether Number is Even or Odd using
Functions
#include <iostream>
using namespace std;
void iseven(int);
int main ()
{
int num;
cout<<"Enter any number";
cin>>num;
iseven(num);
return 0;
}
void even(int num1 )
{
if ( num1%2==0)
cout<<"\n Even number";
else
cout<<"\n Odd number";
}
Arrays:
 One Dimensional Array
 Multidimensional Array
One Dimensional Array
 Introduction
 Arrays
 Declaring Arrays
 Examples Using Arrays
 Passing Array Elements to
Function
Name of array
(Note that all
elements of this

Arrays array have the


same name, c)

 Array c[0] -45


c[1] 6
 Collection of similar elements
c[2] 0
 Group of consecutive memory locations
c[3] 72

 To refer to an element, specify c[4] 1543


c[5] 89
 Array name
c[6] 0
 Position number c[7] 62

 Format: c[8] -3
c[9] 1
arrayname[ position number ] c[10] 6453
 First element at position 0 c[11] 78

 n element array named c:


c[ 0 ], c[ 1 ]...c[ n – 1 ] Position number
of the element
within array c
Arrays
 Array elements are like normal
variables
c[ 0 ] = 3;
cout<< c[ 0 ];
 Perform operations in subscript. If x
equals 3
c[ 5 - 2 ] == c[ 3 ] == c[ x ]
Declaring Arrays
 When declaring arrays, specify
 Name

 Type of array

 Dimension

 Number of elements/size

arrayType arrayName[ numberOfElements ];


 Examples:

int c[10];
float myArray[3284];
 Declaring multiple arrays of same type
 Format similar to regular variables

 Example:

int b[ 100 ], x[ 27 ];
Examples Using Arrays
 Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
 If not enough initializers, rightmost elements become

0
int n[ 5 ] = { 0 }

All elements 0
 If too many a syntax error is produced

If size omitted, initializers determine it


int n[ ] = { 1, 2, 3, 4, 5 };
 5 initializers, therefore 5 element array
Example:
 int main()
 {
 int x;
 x=5;
 x=10;
 cout<<x;
 return 0;
 }
 Calculate average of given
numbers:
Calculate average of given numbers:
 int main()
 {
 float avg, sum=0;
 int i;
 float num[5];
 cout<<“Enter Marks”;
 for(i=0;i<=4;i++)
 cin>>num[i];
 for(i=0;i<=4;i++)
 sum=sum+num[i];
 avg=sum/5;
 cout<<avg;
 return 0;
 }

Calculate average of given numbers:
#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in
range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(i = 0; i < n; i++)
{
cout << ". Enter number: ";
cin >> num[i];
sum =sum + num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
Calculate average of given numbers using
functions:
#include <iostream>
using namespace std;
float avg(float num[10]);
int main()
{
int n, i;
float num[100], average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to
100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(i = 0; i < n; i++)
{
cout << ". Enter number: ";
cin >> num[i];
}
average= avg(num);

cout << "Average = " << average;


return 0;
}
float avg(float num1[100])
{
float sum=0.0, average;
for(i = 0; i < n; i++)
sum=sum + num[i];
average = sum / n;
return(average);
}
Two Dimensional Array:
 Ex. Program for Matrix
Manipulation:
 main()
 {
 int i,j,m1[5][5];

 for(i=0;i<3;i++)
 {
 for(j=0;j<3;j++)
 {
 cin>>m1[i][j];
 }
 }
Structures
 Structures are used to group together different types of
variables under the same name.

example: struct telephone


{
char name[10];
int number;
};
This create a structure "telephone": which is
made up of a string (that is used to hold the name of
the person) and an integer (that is used to hold the
telephone number).
With the declaration of the structure you have
created a new type, called telephone. Before you can
use the type telephone you have to create a variable of
the type telephone. Take a look at the following
example:
#include<iostream>
struct telephone
{
char name[10];
int number;
};
int main()
{
struct telephone index;
return 0;
}
Note: index is now a variable of the type telephone
 To access the members of the structure telephone, you
must use a dot(.) between the structure Variable name
and the member name (variables :name or number.)
Take a look at the next example:

#include<iostream>
struct telephone
{
char name[10];
int number;
};
int main()
{
struct telephone index;
index.name = “xyz"; //if char put in quotations.
index.number = 12345;
cout<< index.name;
cout<<index.number;
return 0;
}
 Write a program to assign the values and retrieve the values using structure.

Take structure book which consist of name,


price & pages
 #include<iostream>
 struct book
 {
 char name[10];
 float price;
 int pages;
 };
 int main()
 {
 struct book b1;
 printf(“Enter name, price & pages of book”);
 cin>>b1.name>>b1.price>>b1.pages;
 cout<< “name”<<“price”<<“pages”<<endl
 cout<<b1.name<<b1.price<<b1.pages;
 return 0;
 }
Type definitions and
structures
 Type definitions make it possible to create your own variable
types.
 Structure can be type defined for simplicity in usage.
 This improves code readability .
 Typedef is a keyword used to redefined the name of data type.
Example
typedef int I;
I x;
creating structure variable with typedef. The name of type definition of
structure is normally written in uppercase.
struct Emp
{
};
typedef struct Emp E;
or
typedef struct Emp
{
}E;
E emp1;
Ex.
#include<iostream>
typedef struct telephone
{
int number;
}TELEPHONE;

int main()
{
TELEPHONE index;
index.number = 12345;
cout<<"Telephone number:”<< index.number;
return 0;
}
Note: The word struct is not needed before TELEPHONE index;
Arrays of Structures:
 What is Array
 What is Structure.
 It makes programming easier.
 Ex. Store record of 50 student’s. It
is must to use array of structures.
 typedef struct student
{
int roll_no;
char name[20];
int marks;
}stud;
stud s[10];
int main()
{
int n,i;
cout<<“Enter total no. of students”;
cin>>n;

cout<<“Enter each student record”;

for(i=0;i<n;i++)
cin>>s[i].roll_no>>s[i].name>>s[i].marks;

cout<<“Each student’s record is ”;

cout<<“ roll_no name marks”;

for(i=0;i<n;i++)
cout<<s[i].roll_no<<s[i].name<<s[i].marks;
return 0;
}
Union
 A union is like a structure contains members
whose individual data types may differ from one
another.
 A union in which all members are stored at the
same address.
 Members of a union can only be accessed one at a
time.
 Just like with structures, the members of unions
can be accessed with the . and -> operators.
Take a look at the example:

union standard
{
int primary;
char pre_pri[10];
};

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy