0% found this document useful (0 votes)
6 views

Functions in C++

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

Functions in C++

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

keyboard_arrow_down 1.

Modular Programming
Definition:
Modular programming is a software design technique that emphasizes dividing a program into independent, reusable modules. Each module is
responsible for a specific task.

Benefits:
Improves readability and maintainability.
Encourages code reuse.
Simplifies debugging and testing.

Example Problem:
Problem: Write a program to compute the factorial of a number using modular programming.
Solution:

# include <iostream>
using namespace std;

// Function prototypes
int getNumber();
int factorial(int);

int main() {
int number = getNumber(); // Call function to get input
cout << "Factorial: " << factorial(number) << endl; // Call factorial function
return 0;
}

// Function definitions
int getNumber() {
int num;
cout << "Enter a positive number: ";
cin >> num;
return num;
}

int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

2. Defining and Calling Functions


Definition:
A function is a block of code designed to perform a specific task. Functions are used to avoid code duplication and make programs modular.

Example:
Problem: Create a function to calculate the sum of two integers and call it in the main function.
Solution:

# include <iostream>
using namespace std;

int add(int a, int b); // Function prototype

int main() {
int num1 = 5, num2 = 10;
cout << "Sum: " << add(num1, num2) << endl; // Call the function
return 0;
}

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


return a + b;
}

3. Function Prototypes
Definition:
A function prototype is a declaration that tells the compiler the function's name, return type, and parameters before the function is defined.

Syntax:

returnType functionName(parameterType1, parameterType2, ...);

Example:
Problem: Use a function prototype to calculate the area of a circle.
Solution:

# include <iostream>
using namespace std;

double areaOfCircle(double radius); // Function prototype

int main() {
double radius = 7.5;
cout << "Area of Circle: " << areaOfCircle(radius) << endl;
return 0;
}

double areaOfCircle(double radius) {


const double PI = 3.14159;
return PI * radius * radius;
}

4. Sending Data into a Function

Definition:
Data is sent into a function via parameters, which allow the function to process specific values.

Example:
Problem: Pass a name to a function and display a greeting message.
Solution:

# include <iostream>
using namespace std;

void greet(string name) { // Function with parameter


cout << "Hello, " << name << "!" << endl;
}

int main() {
string username = "Alice";
greet(username); // Call function with an argument
return 0;
}

5. Passing Data by Value


Definition:
In pass by value, a copy of the actual parameter is passed to the function. Changes made in the function do not affect the original value.
Example:
Problem: Illustrate pass-by-value with a square function.
Solution:

# include <iostream>
using namespace std;

void square(int num) { // Pass-by-value


num = num * num;
cout << "Inside function: " << num << endl;
}

int main() {
int number = 5;
square(number); // Call function
cout << "Outside function: " << number << endl; // Original value unchanged
return 0;
}

6. Using Functions in a Menu-Driven Program


Example:
Problem: Create a menu-driven program for basic arithmetic operations.
Solution:

# include <iostream>
using namespace std;

void add() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Sum: " << a + b << endl;
}

void subtract() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "Difference: " << a - b << endl;
}

int main() {
int choice;
do {
cout << "\nMenu:\n1. Add\n2. Subtract\n3. Exit\nChoose an option: ";
cin >> choice;

switch (choice) {
case 1: add(); break;
case 2: subtract(); break;
case 3: cout << "Exiting program.\n"; break;
default: cout << "Invalid choice!\n";
}
} while (choice != 3);
return 0;
}

7. The return Statement


Definition:
The return statement is used to send a value back to the calling function or terminate a function.

Example:
int multiply(int a, int b) {
return a * b;
}

8. Returning a Boolean Value


Functions can return true or false.

Example:
Problem: Check if a number is positive.
Solution:

bool isPositive(int num) {


return num > 0;
}

9. Local and Global Variables


Local Variables:
Declared inside a function and not accessible outside it.

Global Variables:
Declared outside all functions and accessible throughout the program.

Example:

# include <iostream>
using namespace std;

int globalVar = 100; // Global variable

void display() {
int localVar = 50; // Local variable
cout << "Global: " << globalVar << ", Local: " << localVar << endl;
}

int main() {
display();
return 0;
}

10. Static Local Variables


Static local variables retain their value between function calls.

Example:

void count() {
static int counter = 0; // Retains value across function calls
counter++;
cout << "Counter: " << counter << endl;
}

11. Default Arguments


Default values for parameters are specified in the function prototype.

Example:

# include <iostream>
using namespace std;

void modify(int &num) {


num *= 2;
}

int main() {
int number = 10;
modify(number);
cout << "Modified value: " << number << endl;
return 0;
}

12. Using Reference Variables as Parameters


References allow functions to modify arguments directly.

Example:

# include <iostream>
using namespace std;

void modify(int &num) {


num *= 2;
}

int main() {
int number = 10;
modify(number);
cout << "Modified value: " << number << endl;
return 0;
}

13. Overloading Functions

Example:

# include <iostream>
using namespace std;

int add(int a, int b) {


return a + b;
}

double add(double a, double b) {


return a + b;
}

int main() {
cout << add(5, 10) << endl;
cout << add(5.5, 10.2) << endl;
return 0;
}

14. The exit() Function


Example:

# include <iostream>
# include <cstdlib>
using namespace std;

int main() {
cout << "This program will exit now.\n";
exit(0);
cout << "This won't be displayed.\n";
}

keyboard_arrow_down Practice Questions


1. Write a program that uses a function to calculate the factorial of a given number. The function should take an integer as input and return
the factorial. Use this function in the main function to calculate the factorial of 5 and display the result.

2. Create a function that checks whether a given number is a prime number. The function should return true if the number is prime and
false otherwise. Use this function in the main function to check whether the numbers 7 and 15 are prime.

3. Develop a program with two functions: one to calculate the area of a rectangle and another to calculate its perimeter. Both functions
should take the length and width of the rectangle as arguments. Use these functions in the main function to find the area and perimeter of
a rectangle with a length of 8 and width of 4.

4. Implement a function that generates the first n terms of the Fibonacci sequence. The function should take an integer n as input and
return the numbers in the sequence. Use this function in the main function to generate and display the first 7 terms of the Fibonacci
sequence.

5. Write a function that determines if a given string is a palindrome. The function should ignore case and spaces. Use this function in the
main function to check whether the strings "Madam" and "Hello" are palindromes.

6. Create a function that swaps the values of two variables using pass-by-reference. Demonstrate the functionality in the main function by
swapping two integers, 10 and 20, and displaying the results before and after swapping.

7. Write a program with two functions: one to convert a temperature from Celsius to Fahrenheit and another to convert Fahrenheit to Celsius.
Each function should take the temperature as input and return the converted value. Use these functions in the main function to convert
100°C to Fahrenheit and 212°F to Celsius.

8. Implement a function that calculates the GCD of two integers using the Euclidean algorithm. The function should take two integers as
input and return the GCD. Use this function in the main function to calculate the GCD of 56 and 98.

9. Develop a program with a function to calculate the power of a number. The function should take two arguments: the base and the
exponent. Return the calculated result using recursion. Use this function in the main function to calculate 34 and display the result.

10. Write a function that calculates the simple interest for a given principal, rate of interest, and time. The function should take three
arguments and return the calculated interest. Use this function in the main function to calculate the interest for a principal of 10,000, rate
of 5%, and time of 2 years.

Start coding or generate with AI.

You might also like