Monday, 24 June 2019

IF STATEMENT IN C

If statement in C is a decision-making statement (in real life, we need to take some decision, these decisions decide what should we do next, the same condition for programming which determines what block of code will execute). When the condition in if statement is true, then the block of code will execute and condition in if statement is false, then the block of code will not execute.


Syntax
 if (condition)
{
//Block of code

Flow Chart of if Statement in C

if statement in C
































If curly braces ({ ) is not provided after if statement, then only the first statement will execute, and the rest of the statement will not execute.


See Also: Do While Loop in C

Program 1: Write a program to find out the largest number from the given numbers are 14 & 13 using if statement in C.

 Here, we tried to explain how to find out the largest number step by step:
Algorithm
Step1:  Start the program.
Step2:  Enter input data a =14, b=13.
Step3: Write if statement with the condition (a>b).
Step4:  When the condition (a>b) is true, then the block of code will execute. When the condition (a>b) is false, then go to Step5.
Step5: Print the output.
Step6: Finish the program.


See Also: Learn Dynamic Memory Allocation in C

Flow Chart of the Largest Number Program

if statement in C



























Program
#include <stdio.h>
int main()
{
    int a =14, b 13;
    if (> b)
    {
        printf ("largest number is=%d\n", a);
    }
    return 0;
}

Output
Using if statement


Program 2: Write a program to count the number of boys whose weight is less than 50 kg and height is greater than 170 cm using if statement in C.

Steps mentioned below helps you to understand the program,
Algorithm
Step1: Start the program.
Step2: Input data number_of_boys, i, count=0, weight, and height.
Step3: Write condition in if statement (weight should be less than 50 kg and height should be greater than 170 cm).
Step4: When if the condition is true, then the number of count of boys will increase by one. When the condition is false, then go to Step5.
Step5: Print the output.
Step6: Stop the program.

Flow Chart

if statement





































Program
#include <stdio.h>
int main()
{
    int number_of_boys, i, count = 0;
    float weightheight;
    printf ("Enter number of boys\n");
    scanf ("%d", &number_of_boys);
    printf ("Entered number_of_boys are %d\n", number_of_boys);
    printf ("Enter number of weight and height");
    for (=1;i<=number_of_boys; i++)
    {
        scanf ("%f%f", &weight, &height);
        if (weight < 50 && height >170)
        {
            count ++;
        }
    }
    printf ("Number of boys with weight less than 50kg and height greater than 170cm %d\n"count);
    return 0;
}


Output
output of a program using if statement

 

Program 3: Write a Program to find out the given number is even or not using if statement in C.

If a number is divided by 2 and the remainder comes to zero, then that number is even otherwise that number is odd. 
Algorithm
Step1: Enter the number a=5.
Step2: If the remainder is equal to zero, then the given number is even otherwise it is odd.
Step3: Stop

Program
#include <stdio.h>
int main()
{
    int a=5,rem;
    rem 5%2;
    if (rem==0)
    {
        printf ("Entered number %d is even %d",a);
    }
    printf ("Entered number %d is odd ",a);
    return 0;
}

Output
Entered number 5 is odd.







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 on 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.