If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Functions are reusable blocks of code that perform a specific task. They help in modularizing the code and make it more organized and easier to maintain. A function is defined with a return type (if applicable), a function name, and optional parameters. Let's explore functions and a problem statement:
Functions:
Syntax of a simple function in C++:
cppCopy code
return_type function_name(parameters) { // Function body // Code to perform a specific task // Optionally, return a value }
Example of a function that adds two integers and returns their sum:
cppCopy code
#include <iostream> int add(int a, int b) { int sum = a + b; return sum; } int main() { int num1 = 5, num2 = 10; int result = add(num1, num2); std::cout << "Sum: " << result << std::endl; return 0; }
Problem Statement:
Let's consider a simple problem statement: Write a C++ function to calculate the factorial of a non-negative integer.
Factorial Function: The factorial of a non-negative integer
n
, denoted asn!
, is the product of all positive integers less than or equal ton
.Example: Factorial of 5 (
5!
) is5 * 4 * 3 * 2 * 1 = 120
.cppCopy code
#include <iostream> // Function to calculate the factorial int factorial(int n) { if (n == 0 || n == 1) { return 1; } else { return n * factorial(n - 1); } } int main() { int num = 5; int result = factorial(num); std::cout << "Factorial of " << num << " is: " << result << std::endl; return 0; }
In the above example, we have defined a recursive function
factorial
that calculates the factorial of the input numbern
. The function checks for the base case (n == 0
orn == 1
) and returns 1. Otherwise, it recursively calls itself withn - 1
until it reaches the base case.Feel free to experiment with different inputs for the
factorial
function and see how it calculates the factorial of the given number using recursion.
I bought this course, it worth it!
Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it
Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website
Quick answers to common questions about our courses, quizzes, and learning platform
SCIAKU Team please upload 1st video of TREE please please please, please