C Program To Find Factorial of a Number using Function

Write a function to calculate the factorial value of any integer entered through the keyboard.

Related Read:
C Program To Find Factorial of a Number

Factorial of a number is the product of all the numbers preceding it. For example, Factorial of 6 is 720 (1 x 2 x 3 x 4 x 5 x 6 = 720).

In general, n objects can be arranged in n(n – 1)(n – 2) … (3)(2)(1) ways. This product is represented by the symbol n!, which is called n factorial. By convention, 0! = 1.

Video Tutorial: C Program To Find Factorial of a Number using Function


[youtube https://www.youtube.com/watch?v=OcXCoX51Xx4]

YouTube Link: https://www.youtube.com/watch?v=OcXCoX51Xx4 [Watch the Video In Full Screen.]


Source Code: C Program To Find Factorial of a Number using Function

#include<stdio.h>

void factorial(int);

int main()
{
    int num;

    printf("Enter a positive number to find Factorial\n");
    scanf("%d", &num);

    factorial(num);

    return 0;
}

void factorial(int num)
{
    int count, fact = 1;

    if(num == 0)
    {
        printf("Factorial of 0 is 1 (!0 = 1)\n");
    }
    else
    {
        for(count = 1; count <= num; count++)
        {
            fact = fact * count;
        }

        printf("\nFactorial of %d is %d (!%d = %d)\n", num, fact, num, fact);
    }
}

Output 1:
Enter a positive number to find Factorial
5

Factorial of 5 is 120 (!5 = 120)

Output 2:
Enter a positive number to find Factorial
4

Factorial of 4 is 24 (!4 = 24)

Output 3:
Enter a positive number to find Factorial
6

Factorial of 6 is 720 (!6 = 720)

Output 4:
Enter a positive number to find Factorial
7

Factorial of 7 is 5040 (!7 = 5040)

Output 5:
Enter a positive number to find Factorial
8

Factorial of 8 is 40320 (!8 = 40320)

Logic To Find Factorial of a Number

Complete for loop logic to find Factorial of a number is present at C Program To Find Factorial of a Number. Watch the video without fail to understand the logic.

Note: Function factorial doesn’t return anything so its return type is void. It accepts 1 integer type argument.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Generate Fibonacci Series using Function

Lets write a C program to generate Fibonacci Series using function / method.

Related Read:
Fibonacci Series using While loop: C Program
C Program To Generate Fibonacci Series using For Loop

What Is Fibonacci Series ?
Fibonacci Series is a series of numbers where the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Its recurrence relation is given by Fn = Fn-1 + Fn-2.

Below are a series of Fibonacci numbers(10 numbers):
0
1
1
2
3
5
8
13
21
34

How Its Formed:
0 <– First Number (n1)
1 <– Second Number (n2)
1 <– = 1 + 0 (previous two numbers)
2 <– = 1 + 1 (previous two numbers)
3 <– = 2 + 1 (previous two numbers)
5 <– = 3 + 2 (previous two numbers)
8 <– = 5 + 3 (previous two numbers)
13 <– = 8 + 5 (previous two numbers)
21 <– = 13 + 8 (previous two numbers)
34 <– = 21 + 13 (previous two numbers)

Video Tutorial: C Program To Generate Fibonacci Series using Function


[youtube https://www.youtube.com/watch?v=R3MPbqvYooA]

YouTube Link: https://www.youtube.com/watch?v=R3MPbqvYooA [Watch the Video In Full Screen.]


Source Code: C Program To Generate Fibonacci Series using Function

#include<stdio.h>

void fibonacci(int);

int main()
{
    int limit;

    printf("Enter the number of terms to be printed\n");
    scanf("%d", &limit);

    fibonacci(limit);

    return 0;
}

void fibonacci(int num)
{
    int n1 = 0, n2 = 1, n3, count;

    printf("\nFibonacci Series ..\n");
    printf("1. %d\n2. %d\n", n1, n2);

    for(count = 3; count <= num; count++)
    {
        n3 = n1 + n2;
        printf("%d. %d\n", count, n3);

        n1 = n2;
        n2 = n3;
    }
}

Output 1:
Enter the number of terms to be printed
5

Fibonacci Series ..
1. 0
2. 1
3. 1
4. 2
5. 3

Output 2:
Enter the number of terms to be printed
14

Fibonacci Series ..
1. 0
2. 1
3. 1
4. 2
5. 3
6. 5
7. 8
8. 13
9. 21
10. 34
11. 55
12. 89
13. 144
14. 233

Logic To Generate Fibonacci Series using Function

We ask the user to enter the limit i.e., how many terms in the Fibonacci series to be printed. We pass this user entered limit to function fibonacci.

Inside fibonacci function
We initialize n1 to 0 and n2 to 1 and display it to the console. We do this because we know that in any Fibonacci series the first two numbers are 0 and 1.

Now we add n1 and n2 and assign it to n3, and display the value of n3 – which is the next number in the Fibonacci series. We use for loop to keep printing the Fibonacci series until the limit entered by the user.

Note: Function fibonacci takes 1 integer type argument and doesn’t return anything, so its return type is void.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find Armstrong Numbers Between 1 and 500 using Function

Lets write a C program to find Armstrong number or Narcissistic number from 1 to 500 using function.

Problem Statement
Write a C program to print out all Armstrong numbers or Narcissistic number between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. Hint: Use function / method.

An Armstrong number or Narcissistic number is an n-digit base b number such that the sum of its (base b) digits raised to the power n is the number itself.

Example 1:
If number = 153
It has 3 digits: 1, 5 and 3. So n = 3.
result = 13 + 53 + 33 = 1 + 125 + 27 = 153.
So the original number 153 is equal to the result. So it’s an Armstrong Number.

Example 2:
If number = 1634
It has 4 digits: 1, 6, 3 and 4. So n = 4.
result = 14 + 64 + 34 + 44 = 1 + 1296 + 81 + 256 = 1634.
So the original number 1634 is equal to the result. So it’s an Armstrong Number.

Related Read:
C Program to print Armstrong Numbers between 1 and 500

Video Tutorial: C Program To Find Armstrong Numbers From 1 To 500 using Function


[youtube https://www.youtube.com/watch?v=V0Ws8aS4GwI]

YouTube Link: https://www.youtube.com/watch?v=V0Ws8aS4GwI [Watch the Video In Full Screen.]


To count the digits in a number

    int n = 0, temp;

    temp = num;

    while(temp)
    {
        temp = temp / 10;
        n++;
    }

To Iterate through the digits in the number

    while(num)
    {
        rem = num % 10;
        sum = sum + pow(rem, n);
        num = num / 10;
    }

To know above code logic, please visit and watch the video tutorial present at C Program to Check Armstrong Number.

Full Source Code: C Program To Find Armstrong Numbers Between 1 and 500 using Function

#include<stdio.h>
#include<math.h>

float armstrong(int);

int main()
{
    int count;

    for(count = 1; count <= 500; count++)
    {
        if(count == armstrong(count))
        {
            printf("%d is a Armstrong number\n", count);
        }
    }

    return 0;
}

float armstrong(int num)
{
    int rem, n = 0, temp;
    float sum = 0.0;

    temp = num;

    while(temp)
    {
        temp = temp / 10;
        n++;
    }

    while(num)
    {
        rem = num % 10;
        sum = sum + pow(rem, n);
        num = num / 10;
    }

    return(sum);
}

Output:
1 is a Armstrong number
2 is a Armstrong number
3 is a Armstrong number
4 is a Armstrong number
5 is a Armstrong number
6 is a Armstrong number
7 is a Armstrong number
8 is a Armstrong number
9 is a Armstrong number
153 is a Armstrong number
370 is a Armstrong number
371 is a Armstrong number
407 is a Armstrong number

#include<stdio.h>
#include<math.h>

float armstrong(int);

int main()
{
    int count;

    for(count = 1; count <= 500; count++)
    {
        if(count == armstrong(count))
        {
            printf("%d is a Armstrong number\n", count);
        }
    }

    return 0;
}

float armstrong(int num)
{
    int rem;
    float sum = 0.0;

    while(num)
    {
        rem = num % 10;
        sum = sum + (rem * rem * rem);
        num = num / 10;
    }

    return(sum);
}

Output:
1 is a Armstrong number
153 is a Armstrong number
370 is a Armstrong number
371 is a Armstrong number
407 is a Armstrong number

Logic To Find Armstrong Numbers Between 1 and 500 using Function

Using for loop(inside main method) we pass value(from 1 to 500) to armstrong function one by one. The value is present in variable count.

Function armstrong checks the number of digits present in the number(we call it as n) and then separates individual digits of the number and multiplies all the individual digits n times and adds them all and finally returns the sum.

If the armstrong function returned number and the value present in count are same then the value present in count is an Armstrong number, else we pass on to check the next number selected by for loop.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Function / Methods In C Programming Language

In today’s video tutorial lets learn the basics of function or methods in C programming language.

Function / Method: is a group of statements that together perform certain task.

Note: Every C program should have 1 main function. No 2 functions / methods should be named as main.

Video Tutorial: Function / Methods In C Programming Language


[youtube https://www.youtube.com/watch?v=X7auVd3QpTM]

YouTube Link: https://www.youtube.com/watch?v=X7auVd3QpTM [Watch the Video In Full Screen.]

Advantages of Function/Methods

1. It provides modularity to the program structure.
2. You can reuse your code. You can write function definition once and call the function any number of times in your program.
3. Easy to read, understand, edit and debug your code.

Types of Functions/Methods

1. Built in functions/methods.
2. User defined functions/methods.

1. Built in functions/methods: So far we’ve used a lot of builtin methods like pow(), sin(), cos(), tan(), sqrt() etc which are all present in library / header file math.h

If you open math.h header file and check the code, it’ll have function prototype and function definition for pow(), sin(), cos(), tan(), sqrt() etc.

Functions like printf(), scanf() and other input output functions/methods are present in stdio.h library file.

Similarly, if we want to write user defined function, we must specify the function prototype and function definition ourselves.

2. User defined functions/methods: We can define and use our own functions. We can have 4 types of user defined functions/methods.
a. No return type, no arguments.
b. No return type, with arguments.
c. With return type, no arguments.
d. With return type, with arguments.

Stay subscribed to our YouTube channel and blog for video tutorials explaining all types of user defined functions.

General Syntax of user defined Funtion/Method

1. Function prototype.
return_type funtion_name(argument_data_type_list);

2. Function definition.
return_type funtion_name(argument_data_type_list)
{
//instructions
}

3. Function Call.
funtion_name(argument_data_type_list);

Source Code: Function / Methods In C Programming Language: With Return Type and With Arguments

#include<stdio.h>

int add(int, int); // function prototype

int main()
{
    int a = 10, b = 20, c;

    c = add(a, b); // function call

    printf("Addition of %d and %d is %d\n", a, b, c);

    return 0;
}

//function definition
int add(int i, int j)
{
    return(i+j);
}

Output
Addition of 10 and 20 is 30

Source Code: Function / Methods In C Programming Language: No Return Type and No Arguments

#include<stdio.h>

void companies(); // function prototype

int main()
{
    companies(); // function call

    return 0;
}

//function definition
void companies()
{
    printf("1. IBM\n");
    printf("2. Apple\n");
    printf("3. Google\n");
    printf("4. Oracle\n");
    printf("5. Ripple\n");
}

Output
1. IBM
2. Apple
3. Google
4. Oracle
5. Ripple

Source Code: Function / Methods In C Programming Language: No Return Type and With Arguments

#include<stdio.h>

void multiply(int, int); // function prototype

int main()
{
    int a = 9, b = 12;

    multiply(a, b); // function call

    return 0;
}

//function definition
void multiply(int x, int y)
{
    printf("%d x %d = %d\n", x, y, (x*y));
}

Output
9 x 12 = 108

Source Code: Function / Methods In C Programming Language: With Return Type and No Arguments

#include<stdio.h>

int subtract(); // function prototype

int main()
{
    printf("Subtraction Result = %d\n", subtract() ); // function call

    return 0;
}

//function definition
int subtract()
{
    int a = 50, b = 25, c;

    c = a - b;

    return(c);
}

Output
Subtraction Result = 25

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Update with SET Operator: MongoDB

Lets use $set operator along with update() method, to update the documents.

test database, names collection

1
2
3
> db.names.find()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "name" : "Alia" }
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }

update-with-set-operator-mongodb

Related Read: Update Method: MongoDB

Lets update the first document using only update method.

1
2
3
4
5
6
7
8
9
10
> db.names.update({"name": "Alia"}, {"name": "Alia", "age": 25});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{
        "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"),
        "name" : "Alia",
        "age" : 25
}

Everything is ok in this case. But what if you forget to mention the name field in the second argument of update() method.

1
2
3
4
5
6
> db.names.update({"name": "Alia"}, {"age": 25});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"), "name" : "Bebo" }
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }

In this case, the name field gets erased. As we did not specify name field in the second parameter of update() method.

Using $set operator

1
2
3
4
5
6
7
8
9
10
> db.names.update({"name": "Bebo"}, {$set: {"age": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 25
}

Here we make use of document with name as Bebo. Using $set operator we only specify the fields we want to add or update. Need not specify other existing fields in order to retain them.

Update with SET Operator: MongoDB


[youtube https://www.youtube.com/watch?v=nsDnZcstUV4]

YouTube Link: https://www.youtube.com/watch?v=nsDnZcstUV4 [Watch the Video In Full Screen.]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
> db.names.update({"name": "Bebo"}, {$set: {"age": 25, "salary": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 25,
        "salary" : 25
}
 
 
> db.names.update({"name": "Bebo"}, {$set: {"age": 26, "salary": 25}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 26,
        "salary" : 25
}
 
 
> db.names.update({"name": "Bebo"}, {$set: {"salary": 30}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
 
> db.names.find().pretty()
{ "_id" : ObjectId("53be5d4604cc1cb0a7bfc3c0"), "age" : 25 }
{
        "_id" : ObjectId("53be5d5204cc1cb0a7bfc3c1"),
        "name" : "Bebo",
        "age" : 26,
        "salary" : 30
}

We can update existing field or add a field to the existing document using $set operator and need not to worry about the other fields in the document.