Functions & some Problem Statement

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 22:- Functions & some Problem Statement

 

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 as n!, is the product of all positive integers less than or equal to n.

Example: Factorial of 5 (5!) is 5 * 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 number n. The function checks for the base case (n == 0 or n == 1) and returns 1. Otherwise, it recursively calls itself with n - 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.

4. Basics Of Programming- II

2 Comments

@mk.info.work
mk.info.work Feb 17, 2024 at 10:20 PM

SCIAKU Team please upload 1st video of TREE please please please, please

@na3744
na3744 Feb 23, 2024 at 2:52 AM

I bought this course, it worth it!

@mk.info.work
mk.info.work Nov 15, 2023 at 10:25 PM

Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it

@sciaku1
sciaku1 Jan 11, 2024 at 3:23 PM

Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support