University of Management and Technology
Knowledge Unit of Science and
Technology
Laboratory Manual
[CC1021]: [Programming Fundamentals]
[Semester Fall-2021]
Class: [BSSE,IT]
Lab [9]: [C++ Functions]
Instructor: [Ms. Hifza Munir]
[CC1021]: [Programming Fundamentals] Page 1
University of Management and Technology
Functions
1. C++ Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
2. Create a Function
void myFunction() {
// code to be executed
}
3. Call a Function
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
[CC1021]: [Programming Fundamentals] Page 2
University of Management and Technology
C++ Functions Parameters
Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as variables inside the
function.
Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
Example
void myFunction(string fname) {
cout << fname ;
}
int main() {
myFunction("Sana");
myFunction("Saba");
myFunction("Soha");
return 0;
}
// Sana
// Saba
// Soha
[CC1021]: [Programming Fundamentals] Page 3
University of Management and Technology
Multiple Parameters
You can add as many parameters as you want:
Example
void myFunction(string fname, int age) {
cout << fname << age << " years old. \n";
}
int main() {
myFunction("Sana", 3);
myFunction("Saba", 14);
myFunction("Sara", 30);
return 0;
}
Return Values
The void keyword, used in the examples above, indicates that the function should not return a
value. If you want the function to return a value, you can use a data type (such as int, string, etc.)
instead of void, and use the return keyword inside the function:
Example
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
[CC1021]: [Programming Fundamentals] Page 4
University of Management and Technology
Lab Tasks
1. Write a program in C++ to check a given number is even or odd using the function.
2. Write a program in C++ to find the square of any number using the function.
3. Write a C++ program that prompts the user to enter a number and calls a function
Factorial () to compute its factorial. Write a function Factorial () that has one input
parameter and Displays the factorial of number passed to it.
4. Write a program that inputs a number in main function and passes number to function.
The function displays table of that number.
5. Write a C++ program that will display the calculator menu. The program will input two
numbers and prompt the user to choose the operation choice (from 1 to 5).
1 for Addition
2 for Subtraction
3 for Multiplication
4 for division
5 for Modulus
Based on user choice pass the entered values to the required functions and the function
will return the calculated result value.
[CC1021]: [Programming Fundamentals] Page 5