Knowledge Unit of Science and Technology: Laboratory Manual (CC1021) : (Programming Fundamentals) (Semester Fall-2021)
Knowledge Unit of Science and Technology: Laboratory Manual (CC1021) : (Programming Fundamentals) (Semester Fall-2021)
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;
}
C++ Functions Parameters
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
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;
}
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.