Program : Factorial Using Recursion

#include <stdio.h>
 long int fact(int n);
 int main()
 {
    int n;
    printf("Enter a Positive Integer: ");
    scanf("%d", &n);
    printf("Factorial of %d = %ld", n, fact(n));
    return 0;
 }
 long int fact(int n)
 {
    if (n == 0)
        return 1;   
    else
        return n*fact(n-1);
 }
Enter a positive integer: 6
 Factorial of 6 = 720
Explaination : In this program, we accept a positive integer from the user of whom we are going to find the factorial. The integer number is then passed in the User-defined Function named "fact". The condition is like, if the number gets equal to zero, then the it will return 1 or else it will return number times the fact of (n-1) i.e the function is calls itself. So, again the function "fact" will run for (n-1) and then like this goes on and on until the n values get 0 and it finally returns the value 1 so the functions terminates and returns that value to the main function.

Recursion

Recursion is very useful concept. Recursion, in very simple words, function calling itself. Sometimes, we need to repeat the function many times, for that concept, we have to use Recursion. Let's take an example of Factorial for Recursion. In factorial, we need to go to next number by substracting and perform the same task on it. So, Recursion is used. 

Click Here for Factorial Program using Recursion.

In Recursion, the stack memory is used. We need to break the Recursion condition to make it finite or else, it will run for Infinity times and give will Runtime, as stack memory gets full. So, to make the Recursion condition break, we can use the if else statements. We can write the Breaking condition in if statement and in else condition, the Recursion part is there.

factorial of n (n!) = 1*2*3*4....n

And Breaking Condition for this, can be if(n==0) then return 1; You will get to know about the Recursion in the Factorial Example.

Call by Value and Call by Reference

Call by value and Call by reference is the extended part of Functions. Let's see what's it? For this, you need to understand the concept of Formal Parameters and Actual Parameters. When the function is called, the parameters which we pass are known as actual parameters. And the parameters which get pass from the User-defined function are known as formal parameters. 

To need understand the concept more clearly, let's understand how to functions a little bit deeper. Let's take an example of swapping the values of two variables with the help of User-defined Function. Also we need to include pointer in this example.
#include <stdio.h>
 void swap(int *a, int *b);
 int main()
 {
    int x, y;
    printf("Enter the value of variable 1 = ");
    scanf("%d", &x);
    printf("Enter the value of variable 2 = ");
    scanf("%d", &y);
    printf("Before Swapping\nx = %d\ny = %d\n", x, y);
    swap(&x, &y);
    printf("After Swapping\nx = %d\ny = %d\n", x, y);
    return 0;
 }
 void swap(int *a, int *b)
 {
    int t;
    t  = *b;
    *b = *a;
    *a = t;
 }
Explaination : In this program, we are swapping the values of variables using pointers and using User-defined Function. So, firstly we have declared the swap function. Then in main function, we have scanned 2 variables. And then we have passed the address of the variables x and y and not the values. So, this is called Call By Reference. Call by Value is simple, which we use. In the functions, if have used Call by Value, then we will pass the variables and not the address of the variable. In the User-defined functions, if the pointers variables are passed and simple variables are passed then in memory they have create their own space and after the function returns any value or the functions get terminate the variables get destroy but here, the pointers are passed so, the operations are done on the variable's address' value and not on the variable directly. The above program is working under Call by Reference method.

Structures and Union

Unlike the array, which stores the data in the variables of the same data type, Structures and Union are used for data storage in variables but of different data types. Suppose, you need to take the information of an Employee, the information which you want to collect from them is : Employee Name, DOB (Date of Birth), Salary.
As you can see, Employee Name will be having data type "char", DOB can also have data type "char" and Salary is stored in "integer" data type. For this, we can use structures.

Difference Between Structures & Union?

# Structures & Union are one and the same thing but the only difference is in the memory allocation in both. Structures assign memory to every variable which is declared, and Union only assigns the memory which the last variable in the list is declared to. 

Both Structures and Union have the same data type. Only in structure, you need to use the keyword "struct" and in Union, you need to use the keyword "union".

Let's see the syntax.

struct structureName;
{
 dataType nameOfVariable[size];
 dataType nameOfVariable[size];
 .....
 .....
}noOfObjects;

Here, noOfObjects means of many times people, you need to take the information of. Let's learn with the help of example. 

struct student;
{
 char name[20];
 int marks[20];
}student1, student2; OR }student[1];

Explaination : We have created a student structure which is having name as a variable of data char and size of it is 20. Same way, we have variable marks of the data type integer and size of it is 20. After }, you have the number of times, you need to take the data. Here, student[1], so the value will be stored as student0, student1.

How to assign values to structure?

struct student;
{
 char name[20];
 int marks[20];
}student1, student2; OR }student[1];

for(i=0;i<=1;i++)
{
 printf("Name = ");
 scanf("%s", student.name[i]);
 printf("Marks = ");
 scanf("%d", student.marks[i]);
}

How to print the structure? 

You can use the for Loop for it. 

for(i=0;i<=1;i++)
{
 printf("Name = %s", student.name[i]);
 printf("Marks = %d", student.marks[i]);
}

Pointers

So, now let's begin with the Advanced Part of C Programming. The first concept, we are going to learn about is pointers. So what are pointers? A pointer provides access to the variable by using the address of the variable. A pointer variable stores the value of another variable. 

Why to use Pointers?

# Pointers are used when we pass arguments in the functions. They are two methods to call the function, you will learn about them in next tutorial, 1. Call by Value and 2. Call by reference. The Call by reference works with pointers. Because in functions, the arguments we pass are formal arguments. So once the function returns the value or gets close, the variables are destroyed. To prevent it, we use Pointers.
Example : Swapping of two variables using Pointers

How to declare Pointer Variable?

dataType *pointerName;

That's all, and a variable named pointerName will be created, which capable to store the address of another variable.

How to store address of the Variable in Pointer Variable?

To store the address, first declare the variable whose address is to be stored. And then declare pointer variable and assign the address value of the variable to it using "&". Let's see how.

int x = 10;
int *ptr;
ptr = &x;

Explaination : Here, x is a variable in which 10 value is stored. Then pointer variable named ptr is declared. Then the address value of x is stored in variable ptr using "&".

Functions

Functions are basically the block of codes which we have to use multiple times in the program like loops. Functions can reduce the number of lines of codes. Functions are executed when they are called from the main function. 

Functions are of two types :-

</a> In-built Functions 
In-built Functions are printf, scanf, the ones which are predefined in the header file.

</b> User-defined Functions
User-defined Functions are the functions which the users create to reduce the number of lines of codes.

How to Call a function?

Before working in the main function, you need to tell the compiler that we have a Sub-function i.e User-defined function is there below the main function. To call the function,  you need to follow the following syntax.

functionName(dataTypeOfVariable1 nameOfVariable, dataTypeOfVariable2 nameOfVariable, ...);  // This should be before the initialization of main function.

How to declare a function?

returnDataType functionName(dataTypeOfVariable1 nameOfVariable, dataTypeOfVariable2 nameOfVariable, ...)
{
 ......
 // block of codes
 ......
 return(variable);
}

There are 4 types of User-defined Functions :-

</a> Function with No Arguments and no Return Value
In this type of User-defined Function, there is no argument and no return value. We simply need to call the Function from main. Then what about printing the value? It is done in the User-defined Function.
Click Here for the Example Of Function with No Arguments and no Return Value.

</b> Function with No Arguments and a Return Value
Here, in this User-defined Function, still we aren't passing any argument, but return a value from the User-defined Function to the main function.
Click Here for the Example Of Function with No Arguments and a Return Value.

</c> Function with Arguments and no Return Value
With Arguments and no Return Value means the User-defined Function is passed with the Argument and in it, it has the printing statements. 
Click Here for the Example Of Function with Arguments and no Return Value.

</d> Function with Arguments and a Return Value
In this, we have both the Argument along with the Return Value.
Click Here for the Example Of Function with Arguments and a Return Value.

Just to Remind You : dataType functionName(argument, arguments, ...)

One-Dimensional and Two-Dimensional Array

After learning the basics of array, let's see what's One-Dimensional Array and Two-Dimensional Array? One-Dimensional Array is normal array, which is basically linear and only in one-direction. Two-Dimensional Array is array in which can store data in table form or matrices. Two-Dimensional Array has rows and columns i.e we can form tables. 

NOTE : All the codes which we learnt in the basics of Array tutorial is for One-Dimensional Array.

How to declare Two-Dimensional Array?

datatype arrayName[rowSize][columnSize];
Example : int table[3][5];

Here, we need to mention two sizes, one for the rows and one for the columns. In the example, we have 3 rows and 5 columns in each row.

How to store data in Two-Dimensional Array?

You have to run two loop to store data in 2-D array, as everytime you need to increment the array index. So, let's learn how to store data in 2-D array.

for(i=0;i<=sizeOfRows;i++)
{
 for(j=0;j<=sizeOfColumns;j++)
 {
  scanf("%d", &arrayName[i][j]);
 }
}

NOTE : In old compilers, you need to declare the size of the array i.e. keep the size as constant and it can't be variable but in new compilers you can keep the size of an array as variable.

How to print the stored value from the array?

for(i=0;i<=sizeOfRows;i++)
{
 for(j=0;j<=sizeOfColumns;j++)
 {
  printf("%d", arrayName[i][j]);
 }
 printf("\n");
}

To print the stored value from the array, follow the above syntax, if the array is of Integer data type. This will print the 2-D array in rows and columns form.

Array

Array is collection of variables having the same data type. Suppose, you need to read marks of 10 students and print them. For this problem, you can declare 10 different variables and can solve the marks of the students in that. But if you are using Array to solve this problem, you can do it very easily then previous solution. Here, we have to declare an array which have the ability to store the marks of students which is having the same data type i.e. integer. 

How to declare an array?

datatype arrayName[size];
Example : int marks[5];

To declare an array, you need to follow the above syntax. You can create an array of different data types such as int, char, etc.

Array of data type "char" is Strings. 

How to store data in an array?

You have to run a loop to store data in array, as everytime you need to increment the array index. So, let's learn how to store data in an array.

for(i=0;i<=sizeofarray;i++)
{
 scanf("%d", &arrayName[i]);
}

NOTE : In old compilers, you need to declare the size of the array i.e. keep the size as constant and it can't be variable but in new compilers you can keep the size of an array as variable.

How to print the stored value from the array?

printf("%d", arrayName[0]);

To print the stored value from the array, follow the above syntax, if the array is of Integer data type. This will print the first element of the array. 

NOTE : Array indexing starts from '0' and not from '1'.

Strings

String is group of characters. String is one of type of array with null character (Array will be discussed in next tutorial). Null Character ('\0') declares the end of the string. Let's different things of Strings.

How to declare a string?

char str[]="Hello"; OR char str[5]="Hello";

The above code shows us how to declare a string which is stored in variable str of data type char. Char is used for declaring characters and also declare group of characters i.e. Strings. The string is "Hello" which has 5 characters i.e 'H', 'e', 'l', 'l' and 'o' but actually it also has one null character at the end of the string i.e '\0'. Here, 5 of str[5] is the size of the array to be define. 

NOTE : In old compilers, you need to declare the size of the array i.e. keep the size as constant and it can't be variable but in new compilers you can keep the size of an array as variable.

How to read a string?

There are three ways by which you can read the string. First, you can use the scanf function to scan the string with %s and you can also use gets() function to do the same. The third is used very rarely is not of much use. The third way to scan is using getchar(), getch() or getche() functions.

Below are the syntax examples of scanf and gets(). As told the third one is very rarely used, so not providing with the syntax of it. 

scanf("%s", str);
gets(str);

Operations on strings

You can use the built-in functions to do the below mentioned operations. For that, you need to include one header named strings.h. You can add this header files like we add stdio.h header file.

#include <strings.h>

You can do the following operations on the string:-

</a> Can compare two strings
1. strcmp() function : Compares whole with ASCII
Syntax : strcmp(str1, str2);

2. strncmp() function : Compares first n bytes of the string.
Syntax : strcmp(str1, str2, n);

</b> Can find the length of the string
Syntax : n = strlen(str);

</c> Can concat two strings (i.e joining two strings)
1. strcat() function : Join both the strings
Syntax : strcat(str1, str2);

2. strncat() function : Join first n bytes of the strings
Syntax : strncat(str1, str2, n);

</d> Can reverse a string
Syntax : strrev(str1)

</e> Can extract a substring from a string
Syntax : result = strstr(str1,str2)

</f> Can copy one string from another
Syntax : strcpy(str1,str2)

do ... while Loop

do ... while Loop is exit controlled loop. In this loop, the codes inside the do will be executed first and then the condition in while is checked. Here's the syntax of do ... while Loop.

declaration and initialization of the variable
do
{
 //  Codes inside do 
 increment / decrement
}
while ( conditon );

Same as while Loop, we need to declare and initialize the variable before the Loop. Here, the do part will be executed first and then the condition which is in while part is checked. If the condition is satisified then the compiler will again go to the do and execute it. 

NOTE : In do ... while Loop, once the do is executed before checking the condition.

Example for do ... while Loop can be as of while Loop i.e Printing hello 5 times.
#include <stdio.h>
 int main()
 {
    int i=1;
    do
    {
        printf("Hello\n");
        i++;
    }
    while(i<=4);
    return 0;
 }
Explaination of the program :
Here, we have first declared and initialized the variable i to 1. We are printing Hello and incrementing the value of i inside the do part of the Loop and the condition in while is i <= 4 ( i less than or equal to 4, because once the compiler will print the Hello as the do part will execute first. \n means breaking of line. Once the condition gets break, the compiler will skip the do ...  while Loop and execute the next line of code. 

while Loop


    while Loop is also entry controlled loop. The difference between for Loop and while Loop is that we need to declare and initialize the variable outside the Loop and we need to increment or decrement the value inside the Loop. Let's have a look at while Loop's syntax.
    
    declaration and initialization of variable;
    while ( condition )
    {
     // Codes inside while Loop
     increment/decrement
    }
    
    Here, in while Loop, we need to declare the variable and also initialize it before the Loop. We need to specific the condition and the Loop works until the condition is satisfied. Inside the Loop only, we need to increment or decrement the variable. So, the while Loop works like this : condition is checked, if true, then the block of code inside loop will execute and inside the block of code, the increment or decrement is done. If the conditon is break, the compiler comes to next line of code after the Loop.
    
    Let's now understand while Loop with an example. Example is of printing hello 5 times.
    
    #include <stdio.h>
     int main()
     {
        int i=1;
        while(i<=5)
        {
            printf("Hello\n");
            i++;
        }
        return 0;
     }
    
    
    
    Explaination of the program :
    As we are using while Loop in this program, we need to declare and initialize the variable first, as we did, declaring and initializing to 1. Now the condition for while Loop is i <= 5 ( i less than or equal to 5 ). If the condition satisfies, then the compiler will execute the block of code inside the while Loop i.e will print Hello and then increment the value of i. \n means breaking of line. The Compiler will again move to condition and check if satisfies then again it will execute the block of code and increment will be done and the same step will be repeated until the condition gets break. Once break, the compiler will jump to next line of code after while Loop.

    for Loop

    for Loop is entry controlled loop. So, what's the syntax of for Loop?
    for ( initialization ; condition ; increment/decrement )
    {
     // Codes inside for Loop
    }
    Initialization is initializing the variable from where it will begin the loop. Let's take, suppose, x is the variable and we are in starting the loop from zero, so need to write x = 0. Second is the condition, we need to specific the condition. Until the condition is true, the loop will be executed, once the condition is break, then loop will get break and next line of code will be executed. The increment/decrement is performanced after the codes inside the loop are executed and then after increment/decrement, the condition is checked.
    Let's see an example of Printing 1 to 10 with the help of for Loop.
    #include <stdio.h>
     int main()
     {
        int i;
        for(i=1;i<=10;i++)
        {
            printf("%d", i);
        }
        return 0;
     }
    
    Explaination of the program:
    We have declared a variable i. Now in for Loop, the i variable is initialized from 1, and then condition is given i<=10 ( i less than or equal to 10 ) and then increment the value of i by 1. Inside for Loop, printing function is there, which prints i. And the programs get exit once the condition is break.

    Loops

    So, what are Loops? Basically, Loops are used for repeating the same codes multiple times, i.e. executing same codes multiples. Let's learn it with the help of an example. Suppose you need to print Hello 15 times on the screen. The Simple way is to write printf function 15 times with the "Hello". So it will print Hello 15 times. But what if you want to print Hello 1000 or infinite times, then at that time, Loops are used.
    
    There are 2 types of Loops :-
    
    </1> Entry Controlled Loop
    
    Entry Controlled Loop means first the condition is checked, if satisfies then it executes the block of codes.
    
    # for Loop
    # while Loop
    
    </2> Exit Controlled Loop
    
    Exit Controlled Loop means the block of code inside the loop is executed first and then the condition is checked.
    
    # do ... while Loop

    Data Types

    Let's have a look at Data Types in C Language. Data types are common in every programming language. There are five basic data types which we use in our programs for beginners. As we get in Advance, we can try the other data types too.
    
    1. int (Integers) : a whole number
    Ex. 0, -7, 8
    Size : 2 bytes or 4 bytes
    
    2. float (Floating point value) : numbers with fractional part.
    Ex. 2.34, 5.19
    Size : 4 bytes
    
    3. double : Double precision floating value
    Size : 8 bytes
    
    4. char (Character) : a single character
    Ex. A, a
    Size : 1 byte
    
    5. void : valueless
    
    int, float, char are fundamental data types and arrays, pointers, structures and enums are derived data types. We can also have signed and unsigned data types. Let's not get in that detail right now. 
    
    This is the basic knowledge required for the beginners.

    Hello World

    After learning the structure of C program, let's code a program and make it print "Hello World!".
     #include <stdio.h>
     int main()
     {
        printf("Hello World!");
        return 0;
     }
    
    Explaination Of the Program : First we need to declare the header file. (Header file will be covered in the upcoming post). After declaration of header file, we need to declare the main function. Compiler starts execution of any program from main function. Inside the main function contains the printf function whose main function is defined in stdio.h header file. After writing the whole program, we need to add return 0; to stop the execution of the program.

    Structure Of C

    Let's start the tutorial with Structure Of C Program. It is necessary to follow the structure or else the compiler will give an error. Structure of C Program contains declaration of header files, declaration of author's details, declaration of global variables, declarating define, the main function and the sub-functions.
    
    
    

    Header files

    This is the first thing which we declare in the program. There are many header files but right now, starting as a beginner, there are only few headers which are useful to us right now. Though, at the end of the post, I'll provide the list of header files. Headers files are files which contain built-in functions, some functions are pre-defined in the header files.
    
    Let's take for an example, <stdio.h> header files, known as Standard I/O header file, is having the pre-defined function of printing and scanning the statement. So to use the printf and scanf function, we need to declare the header file at the beginning of the program. Let us learn, how to declare the header file.
    
    #include <headerfile.h>
    
    This is the syntax for declaring the header file..h indicates that it is a header file. 
    
    The following are the header files which we will be using in this tutorial. 
    
    1. <stdio.h> : Contains printf, scanf and other using functions.
    2. <conio.h> : It is required when we don't have terminal to execute the file.
    3. <math.h> : Contains all the mathematical formulas as functions.
    4. <ctype.h> : Contains several functions for testing purpose.
    5. <string.h> : Contains function performed on strings.
    
    Other than these, there are many other header files which can be included in the program.

    Introduction to C

    C is a low-level programming language. Dennis Ritchie developed the programming language C in the year 1972. More updation over the previous version of C are made and new stable release are made. The last stable release was of C 11 and it was released in December, 2011. Computers can only understands binary codes i.e combinations of 0's and 1's. To code in Binary Language, can increase the chances of errors; it is very difficult to memorize all the functions and commands in binary and also the programs will be full of bugs if no proper attention is paid to every statement while programming it. To decrease the amount of errors and make a error-free program, programming language like C programming is made. 
    
    Programming Language C, is having the functions and commands which can be understand by the humans. After writing the source code of the program, the program is complied. Compiler is given the task of compiling the program. Complier converts the source code written in C into machine language i.e combination of 0's and 1's. After compiling is done, the Compiler generates a new file which is written in binary, and the computer can understand it. Computer runs that binary file and the program executed.