Road Map For Today: - Functions
Road Map For Today: - Functions
• Functions
A Quick Recap
Various constructs to help us write useful programs
• Variables & Input/output statements
• Arithmetic & Assignment statements
• Sequential and conditional statements
• Iteration/looping constructs
• array
• // include statements
• // function prototypes
• // main() function – has the function call
• // function definitions
Internal Functions
C++ programs usually have the following form:
• // include statements
• // function definitions
• // main() function – has the function call
External Functions
C++ Function – Example (Cube)
#include <iostream>
using namespace std;
int Cube (int n);
int main()
{
int yourNumber = 14;
int myNumber = 9;
cout << "My Number =" << myNumber ;
cout << " its cube is" << Cube (myNumber) << endl ;
cout << "Your Number = " << yourNumber ;
cout << " its cube is " << Cube (yourNumber) << endl ;
}
int Cube (int n)
{
return n * n * n ;
}
C++ Function – Example (AddNumbers)
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r = a + b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
}
Lab task1
Write a program which calls a function which prints ten asterisks (*) in
line. (**********).
In this example main function just calls the function named asterisks
which just prints the line of ten asterisks.
Solution
• #include <iostream>
• using namespace std;
• void asterisks ()
•{
• for (int i=0; i<10; i++)
• cout << "*";
•}
• int main ()
•{
• asterisks ();
•}
Lab task2-
• Write a function largerDistance() that takes two
distance values as arguments and returns the
larger one. Write a main() program that takes
two distance values, calls the largerDistance()
function to find out the larger value, and prints
the larger value.