Monday, 17 June 2019

THE C PROGRAMMING LANGUAGE

Ok, Friends...Now, I am going to discuss the basics of the C programminglanguage. Before start discussion about the C programming language, first, we will discuss the history of C like who developed it and why and what is the need of the C programming language. C is a general-purpose procedural computer programming language.
       If you want to learn C++, C#, JAVA, JAVASCRIPT, Python and any other programming language it is necessary you must have knowledge about the basics of the C language. Let’s start...


the C programming language






















Features of the C programming language

1. A C is a case-sensitive programming language and it follows the scope rule. 
2. This language is easy to learn and understand.
3. There is a lot of arithmetic and logical operator in the C programming language, such as +,++,-, =, &, ! etc.
4. It has a fixed number of keywords.
5. Programmer can create its own data type in the C programming language using the keyword struct, union, enum etc.
6. Supports preprocessor that executes before the compilation.
7. It also supports pointers.
8. You can avoid function return values if you don't want to use it.

Why use C language?

There are various reasons to select the C programming language for development language. I have some reason that describes why C is a popular language and why most of the people use it.

1. C is a general-purpose language and easy to learn, whatever you learn in the C programming language, you can be used in the future programming language.
2. This language is a good choice for the designing of an operating system such as Microsoft's windows, Mobile phone's operating system.
3. C is used in the creation of language compiler and interpreter.
4. A lot of legacy programs are written in the C programming language.
5. This language is also a portable language.
6. C language is also used in the database (Oracle database, MySQL).
7. This language is also used in the designing of embedded systems.
8. It is widely used in IoT (Internet of Things) applications. 

History of the C programming language

The first programming language 'ALGOL' is introduced in the year 1960. This language is widely used in European Countries.  A new programming language i.e. Basic Combined Programming Language (BCPL) is developed in 1967 which is specially designed for writing system software. This language was developed by Martin Richards.

After three years, in 1970, a new programming language 'B' is designed by Ken Thompson at AT&T and Bell Laboratories. In 1972, Dennis Ritchie developed a new programming language called 'C' at Bell laboratories. This language consist features of 'ALGOL', 'BCPL' and 'B' programming language.


the C programming language



















UNIX operating system is written in 'C' language. At the initial stage, 'C' is used only for designing the operating system, but as it becomes popular this language is used commercially and many compilers are designed for cross-platform systems. Nowadays, various operating system and hardware platform are designed using 'C' language. As it started evolving many different versions of the language were released.

In 1989, the American National Standard Institute (ANSI) declared a commercial standard for 'C' programming language. In 1990, 'C' language is approved by the International Standard Organization (ISO). This language is also known as 'ANSI C'

Structure of C program

From the structure, it means that any program can be written only in this structure. Therefore, writing a C program in any other composition will make the compilation error. The structure of the C program is as follows:

the C programming language




















Write a Program to display "WELCOME TO THE HELLO WORLD!". 

There are many in-built library functions to do input/output tasks in C programming. The two most used functions for input/output are printf() and scanf(). The scanf() function reads the input data while printf() sends the formatted output to the standard output (the screen).

 #include <stdio.h>
int main( )
{
printf ("WELCOME TO THE HELLO WORLD");
return 0;
 }

Output
WELCOME  TO THE HELLO WORLD

Explanation
#include <stdio.h> : In the C program, all the lines starting with # are processed by the preprocessor, which is a program implemented by the compiler. In a very basic word, the preprocessor takes a C program. The program produced does not have any line starting from #,  all such lines are processed by the preprocessor. In the above example, the preprocessor copies the preprocessed code of stdio.h on our file. .h files are called header files in C. Declaration of functions are usually in these header files. We require stdio.h for the printf() function used in the program.

int main( ): This is a starting point from where the execution of C program begins. main() can be written to take parameter also. The int wrote before main indicates return type of main(). The value returned by main indicates the status of program termination. Main() can be written as mention below:

1. main(): blank parentheses indicates that the main( ) can have an argument.
2. void main(): void means function does not return any value.
3. int main(): int means function returns an integer value. so, it is necessary to mention return 0 at the end of the program.
4. main (void): It also indicates that there is no argument in the main function and return type is also void
5. int main (void): no argument with the integer return type.
6. void main (void): no argument with no return type.

printf ("WELCOME TO THE HELLO WORLD");: printf is a standard library which is used to print output at the screen. The semicolon at the end of this line indicates the termination of the line.

return 0;: The return statement returns the zero value to main(). The value 0 means successful termination of the program.


Monday, 10 June 2019

Recursion in C

A process in which function called itself directly or indirectly is called recursion in C and that function is called recursive function. A recursive function can solve many problems like Fibonacci series, the factorial of a number and Towers of Hanoi (TOH) etc.

Let's understand it with the help of an example

int function1 (int n)
{
function1 ( );
//code;
}


function1() is a recursive function that calls itself. If the termination condition is not inserted in the recursive function function1() then stack overflow will occur. So, it is necessary to put a condition to avoid an infinite loop (avoid stack overflow).

int function1 (int n)
{
if (condition)
function1 ( );
//code;
}


recursion in C



























Direct recursion in C

When a function called itself is known as direct recursion in C.
void add( )
{
//code
add ();
//code
}

Indirect recursion in C

When a function called another recursive function and the called function calling the call function is known as indirect recursion in C.
For example, add() function is known as an indirect recursive function because it calls sub() function and sub() function call add() function.

void add( )
{
//code
sub( );
//code
}
void sub( )
{
//code
add( );
}

Learn with video how to write a program using recursion


How does recursion work?

If we are making a recursive function, then we should keep in mind that each call of the recursive function creates a new automatic set of variables.
Let's try to understand it with a  program, In the below program, the recursive function has been created to calculate factorial of a number. What is factorial? Factorial is a product of all positive number from 1 to n.

Factorial of a number can be,
n! = n*(n-1)!
For example, (4!) = 4 * (4-1)! = 4* (3!)
= 4*3*(3-1)!
= 4*3*(2!)
=4*3*2*(2-1)!
=4*3*2*(1)!
= 4*3*2*1
=24

Note 0! and 1! will be 1.

Program to find out factorial of a given number.


recursion in c




























#include <stdio.h>
int factorial(int num); //Declaration of factorial function
int main( )
{
    int num = 5, output=0;
    if (num <0)
    {
        printf ("Factorial of a negative number is not possible");
    }
    else
    {
        output = factorial(num);
    printf ("Factorial is %d\n", output);
    }
    return 0;
}

int factorial(int num)
{
    if (num==0)
    {
        return 1;
    }
    else
    {
        return (num*factorial (num-1));
    }
}

Output
Factorial is 120.

Working of the above program

Desired number (num)= 5
factorial (5)=5*factorial (4)
factorial (4)= 4*factorial (3)
factorial (3)=3*factorial (2)
factorial (2)=2*factorial (1)
factorial (1)=1*factorial (0)

When num=0 then the recursion process stops and control returns to factorial(1). Now reverse process occurs and function will return a value to the previous function calls.
recursion in c



























So, the output will be, factorial (5) = 5*4*3*2*1 = 120

Advantage and disadvantage of recursion in C

Recursion process has a lot of advantage and disadvantage. Some are mentioning here,

Advantage

1. Recursion process helps us to makes the program simpler.
2. With the help of recursion, a lot of mathematical problems can be solved like calculate factorial of a number, generate Fibonacci series.
3. Recursive functions are convenient for recursively defined data structure like trees.

Disadvantage

1. Recursion in C reduces the speed of a program because each time it creates a stack frame for the function call.
2. Recursion needs a lot of memory space.












Monday, 3 June 2019

What is Pointers in C & how it works?

A pointer is a variable in the C programming language which holds the address of another variable of the same data type. For example, an integer variable contains an integer value, however, an integer pointer holds the address of integer variable. Pointers in C have derived data types. Whenever a variable is declared or initialized in the C programming language, memory is allocated to that variable which stores the value of that variable. We can easily see the address of that variable by using the symbol '&'.


With the help of unary operator & (ampersand), we can access the address of the variable.

#include <stdio.h>
int main ( )
{
int a = 12;
printf ("Value of a=%d\n", a);
printf ("Address of a=%x\n", &a);
return 0;
}

Output
Value of a =12
Address of a = 28ff1c (This output is different for different runs because the variable is stored at a different memory location in different runs.)



Whenever we declared a variable in the C programming language then memory is allocated to that variable. Each memory location has its own address, as we saw in the above program. Assume the variable 'i' is stored at memory location 5698 with the value '12'.

int i = 12;

Pointers in C











A pointer variable holds the address of another variable of the same data type and the value of the pointer variable gets stored in the memory location.



Declaration and Initialization of Pointers in C

Just like variables, pointers are also declared before using in the program. Pointer's name can be anything but they should obey the rules of C.

Syntax to declare pointer variables
data type  *pointer_name;

For example
int *w;
float *x;
char *y;

In int *w, w is an integer data type pointer variable. Similarly, x and y are floating and character data type pointer variable. With the help of asterisk (*) operator, we can access the value of the pointer. Because no value is assigned to these variables, so it contains a garbage value and therefore they point to a memory location as shown in the figure, 

int *z

Pointers in C









Initialization of pointer variables

There are two ways to initialize pointer variables. You can get the memory location of the variable with the help of the reference operator (&) or you can directly assign one pointer variable to other pointer variables.

int   q             // Variable declaration

Pointers in C








Variable 'q' is stored at memory location 2000 which consists a garbage value.

int   *p           // Pointer variable declaration


Pointers in C









Pointer variable 'p' is stored at memory location 3000 with garbage value.

p = &q;           // Initialization of pointer variable



Pointers in C









After initialization, the pointer variable 'p' holds the address of the variable q which is 2000.

int *p = q//Initialize pointer using another pointer

How to access a variable through the pointer variable?

Once an address of a variable is assigned to a pointer, the question arises that how to access the value of the variable using the pointer? This is done by using a unary operator (*) asterisk. This is also known as indirection operator or dereferencing operator.

#include <stdio.h>
int main ( )
{
    // Declaring variable and pointer variable
    int a, *q;

    // Initialize variable a
    a = 12;

    // Initialize pointer variable q
    q = &a;

    printf ("%d\n", *q);          //This will print the value of a
    printf ("%d\n", *&a);     // This will print the value of a
    printf ("%d\n", &a);     // This will print the address of a
    printf ("%d\n", p);       // This will print the address of a
    printf ("%d\n", &p);   // This will print the address of p


    return 0;

}

Size of Pointers in C

In the above section, we discussed what is a pointer in C?  We will now discuss the size of the pointer and why the size of the pointer changes from one compiler to another compiler. The manner in which the size of the integer varies from one compiler to another compiler in C programming, the size of the pointer changes from one compiler to another compiler.


Size of pointers in C






Above figure shows that size of integer and size of the pointer varies from compiler to compiler. If the compiler is 16-bit, it occupies 2 bytes, if it's a 32-bit compiler, it occupies 4 bytes integer and pointer both are same. The reason why the pointer's size depends on the size of the compiler. 16-bit compiler contains 2^16 memory location.

Total location in the 16-bit compiler would be 2^16 = 65,536.

int a = 134;

The value of the integer 134 will be allocated in memory location between 0 to 65,536.

Size of pointers in C











int *ptr;


size of pointers in C











Because the pointer ptr is also the type of integer, the memory location will be allocated between 0 to 65,536.

ptr =&a;

Now, the pointer variable 'ptr' holds the address of the integer variable 'a'.

Size of pointers in C








C program to calculate the size of pointers.

#include <stdio.h>
#include <conio.h>
int main ( ) 
{
int a = 32;
char ch = 'd';
int *b;
char *cp;
b = &a;
cp = &ch;
printf ("size of pointer b is %d and cp is %d\n", sizeof(b), sizeof(cp));
return 0;
}

You all might be thinking that its output will be 1 byte for character pointer 'cp' and 4 bytes for the integer pointer 'b'. But this is not true, both the character pointer and the integer pointer will have the size of 4 bytes. Why do so, let's talk about it.

Size of pointers in C









Whenever you declare a normal variable, size varies from one data type to another type because the type of data you are storing is different.
But, when we are declaring character pointer, integer pointer and float pointer holding the address of variable 'ch', 'a' and 'd'.

char *c = &ch;


i.e. character pointer 'c' holds the address (2034) of 'ch'.

int *= &a;

and integer pointer 'b' holds the address (5896) of the variable 'a'.

double *w = &d;

Pointer variable 'w' holds the address (9325) of the variable 'd'.

Using pointer variables always we are storing the same type of data. All pointer variables hold the address of a normal variable, it is not holding the data, so, what it is holding? It is holding the address 2034, 5896 and 9325. Pointer variable always holds the address, so, it always occupies 2 bytes memory. Pointer size is always fixed because it is holding address instead of data.







































Monday, 27 May 2019

C Functions

The need for C functions

When we write programs, sometimes it happens that we have to type any code repeatedly, so to avoid this situation, we create C functions. Creating function reduces the consumption of memory space and we can use that code in the program when needed. 

With the help of the function, we divide a large program into smaller parts, which also facilitates debugging the program. 

What are C functions?

C functions are a group of many codes/instructions and statements that work together to execute a task. 

Categorization of C functions


C functions













1. Library function or pre-defined function
2. User-defined function

1. Library function

The library function is a pre-defined function in C library. Library function includes header files like stdio.h, conio.h, string.h, graphics.h, dos.h, math.h etc. All header files we can include in our program using "#include <filename.h>" and these header files include C functions.


C functions
Library functions in C


2. User-defined function

These functions are made by themselves. You can also modify these functions. We will further understand how to create user-defined functions, but before that how do we create functions.

Function declaration

A function declaration is a process in which it tells the compiler about the function name, it's return type and parameter list. It is also called function prototyping. 
Syntax
return type         name_of_function (parameter list);

Return type- return type tells the compiler the value you want to return is of which data type (int, float, double, char).
Function name- Function name is an identifier which is decided by the programmer.
Parameter list- This list declares the data type and arguments at the time of calling the function.

If we write declarations before the main function, then this prototype is called a global prototype and this declaration is available for all the functions written in the program.

When we write the declaration in the function definition then the prototype is called the local prototype.

Function definition

A function definition is a group of statements which are written in the function body.
Syntax
return type     name_of_function (parameter_list)
{
Function body;
}

Calling function

When we call a function, the control goes to the function body.
Syntax
Function_name (argument_list);

A c program which demonstrates the function.
#include <stdio.h>

// Declaration of addition function
int add_function(int a, int b);
int main ()
{
    int c;
//Calling of addition function
    c = add_function(10,20);
    printf ("c=%d", c);
    return 0;
}

//Function definition
int add_function(int a, int b)
{
    int addition;
    addition = a+b;
    return addition;
}

Output
c=30

Arguments or parameters passing to C functions

The parameters or arguments passed to a function are called actual parameters. For example, in the main function 10,20 are actual parameters (in the above program). The arguments or parameters received by a function is called formal parameters. For example, in the above program, int a and int b  are formal parameters. There are two methods to pass parameters to a function,

1. Call by value or Pass by value

In this method, values of actual parameters/arguments are copied to formal parameters. These two parameters are stored at a different memory location. That's the reason when you make some changes in the function, the changes do not appear in the actual parameters.

#include <stdio.h>
//Declaration of maximum function
int maximum(int a, int b);
int main ()
{
    int a = 11, b=21,c;
//Calling maximum function
    c = maximum(a,b);
    printf ("c=%d\n",c);
    return 0;
}

//Maximum function definition
int maximum(int a, int b)
{
    int temp;
    if (a>b)
    {
        temp=a;
    }
    else
    {
        temp=b;
    }
    return temp;
}


Explanation
In this function, we declare the value of the variable 'a' and variable 'b' in the main function, these values stored in the stack memory. If we want to redeclare these values in the local function (maximum), no changes in the values of the local function. values of the variable in the main function will not change. 

Output
c = 21

2. Call by reference or pass by reference

In this method, actual parameters are passed to formal parameters. But, they shared the same memory location. So, any change in function reflects in the actual parameters.

#include <stdio.h>
// Declaration of the function of swapping two numbers
int swap (int *a, int *b);
int main()
{
    int x = 19, y=56;
// Calling function swap
    swap(&x,&y);
    printf ("x=%d\n y=%d\n", x,y);
    return 0;
}

//Function Definition of swap
int swap(int *a, int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}


Explanation
In call by reference, the address of variables is assigned to the function as a parameter. We can change the value of the variables in the local function (swap).  Same memory is used for variables declared in the main function or if you want to redeclare variable in the local function.

Output
x = 56
y = 19


C functions arguments and return values

In C programming, C functions are called with arguments or without arguments. These functions may or may not return values to the calling functions.

C functions

Various aspects of function calling

1. C Functions with no argument and no return value

When there is no argument in the function, it will not receive any data from the calling function. In the same way, if it does not return any value then the called function does not receive any data.

Syntax
Declaration of function: void name_of_function();
Calling function: name_of_function();
Definition of function
void name_of_function()
{
//Group of statements;
}

//Addition program for C functions with no arguments and no return values.
#include <stdio.h>
void addition(); //Declaration of function
void main()
{
    addition(); //Calling function
}

//Function definition
void addition( )
{
    int a =10, b=20,c;
    c=a+b;
    printf("Addition of two numbers is %d",c);
}

Output
Addition of two numbers is 30.

2. C Functions with arguments but no return value

When there are arguments in a function, it receives data from calling function but does not return any value to the called function.
Syntax
Declaration of function: void name_of_function(int);
Calling function: name_of_function (a);
Definition of function
void name_of_function(int a)
{
//Group of statements;
}

//Addition program for C functions with arguments and no return value.
#include <stdio.h>
void addition(int a, int b); //Declaration of function
void main()
{
    addition(10,20); //Calling function
}
//Definition of the addition function
void addition(int a,int b)
{
    int c;
    c=a+b;
    printf("Addition of two numbers is %d",c);
}

Output
Addition of two numbers is 30.

3. C Functions with no arguments but returns a value


When there are no arguments in a function, it does not receive any data from calling function but in some special cases, it returns value to the called function.
Syntax
Declaration of function: int name_of_function();
Calling function: name_of_function();
Definition of function
int name_of_function()
{
//Group of statements;
}

// Addition program for C functions with no arguments but have a return value.
#include <stdio.h>
int addition(); //Declaration of function
void main()
{
    int c;
    c=addition(); //Calling addition function
    printf("Addition of two numbers is %d",c);
}
//Definition of the addition function
int addition()
{
    int a =10, b=20;
    return (a+b);
}

Output
Addition of two numbers is 30

4. C Functions with arguments but returns a value

When there are arguments in a function, it receives data from calling function and also return a value to the called function. 
Syntax
Declaration of function: int name_of_function(int);
Calling function: name_of_function(a);
Definition of function
int name_of_function(int)
{
//Group of statements;
}

//Addition program for C functions with arguments and return a value.

#include <stdio.h>
int addition(int a, int b); //Declaration of addition of function
int main()
{
    int c;
    c=addition(10,20); //Calling addition function
    printf("Addition of two numbers is %d",c);
    return 0;
}
//Definition of the addition function
int addition(int a, int b)
{
    return (a+b);

}