Tuesday, 15 January 2019

for loop C


Description: For loop C


For loop execute a block of code number of times (repeatedly). For loop is a looping statement in the C programming language, which allows the code to be executed repeatedly until the condition becomes false. It has three parts:


  • Initialization
  • Condition
  • Update statement (Increment or Decrement)


Syntax

for (initialization; condition; update statement)
{

//Block of Code

}


For loop C




Recommended Posts



FLOW DIAGRAM OF FOR LOOP C



For loop C
Flow Diagram of for loop C



Initialization: This step is executed first and it is executed only once when we are entering the loop for the first time. This step allows you to declare and initialize loop control variables.

Condition: Next step after initialization is to check the condition if the condition is true, it must return a boolean value. It is an entry controlled loop so the condition will check before entering into the block of code.

Update statement: After execution of the loop body, increment or decrement step is executed. This statement updates any loop variable.


Control flow of for loop C




For loop C



  • First, initialize the variable 'i=1', It executes only once when we are entering into the loop.
  • In the second step check condition i.e. 'i<=5'.
  • In the third step, control goes inside the loop body and execute (print Hello five times).
  • Next step is to increase the value of the variable i.e. (i=i+1 i.e i=2).
  • Repeat above four steps until the condition becomes false.


Common pitfalls in using for loop C



  • A valid expression should be written in for loop statement otherwise it can lead to an infinite loop. The statement,

for ( ; ; )

// C program to illustrate infinite loop

#include <stdio.h>
int main ( )
{
for ( ; ; )
{
printf ("Hello");
}
return 0;
}


Output: This code prints the statement "Hello" repeatedly (infinite times).



For loop C


  • Many variables can be initialized in the initialization block of for loop, whether you use it in the loop or not.

//Program to illustrate initializing many variables in the initialization block.


#include <stdio.h>
int main ( )
{
int x = 2;
for (int y = 0, z = 4; x < 10 && y < 10; x++, y++)
{
    printf (" x=%d y=%d \n", x, y);
}
return 0;
}


Output

x=2 y=0
x=3 y=1
x=4 y=2
x=5 y=3
x=6 y=4
x=7 y=5
x=8 y=6
x=9 y=7


Two variables are initialized and declared in initialization block, in which one variable i.e. 'z' is not used.

  • The variables that are declared in the initialization block can be accessed only within the loop. 

//Program to illustrate scope of initializing variables within the loop

#include <stdio.h>
int main ( )
{

for (int x = 3; x < 7; x++)
{
    printf (" x=%d\n", x);
}

printf "x=%d\n", x );
return 0;
}

Output

error: 'x' undeclared


In the above example, variable x is not accessible outside the loop. The statement which is commented gives a compile error.



Thursday, 10 January 2019

What are the Loops in C?


Before knowing what are the loops in C? or how many types of loops available in the C programming language, it is important to know why we need loops in C? Suppose, 


printf ("Welcome to C Programming ");


I have to print above statement 100 times, it is easy to write above statement 100 times, Not at all,  this is a small example but when you design software, 1000 times or maybe more than that you need to write a statement or instructions which is not possible to write it is time-consuming that's why we need  loops in C.


           In computer programming, a loop instruction is a sequence i.e. continuously repeated until it reaches a certain position. Generally, a certain process is done, such as getting an item of data and changing it, and then some conditions are checked as if the counter has reached the specified number. If not, then the next instruction in the sequence is the instructions to return to the first instruction and repeat the instructions. 

What is the difference between a conditional statement and looping statement in C?

  • The conditional statement will execute only once if the situation is correct while the loop will execute repeatedly unless the situation is false.

For example

Conditional statement                                         Looping statement
                                                    

int a = 10;                                                                int a= 5;
if (a = = 10)                                                             While (a <=5)
{                                                                               {
printf ("a is equal to 10");                                        printf ("executed ");
}                                                                                a--;
else                                                                           }
{
printf ("a is not equal to 10");
}


In a conditional statement, condition "a==10" is true then the output is "a is equal to 10" otherwise the output is "a is not equal to 10".
     In looping statement, we initialize a=5, check the condition in while loop if the value of a is less than or equal to 5 then print executed otherwise it terminates from the loop.



Types of Loops in C


1. Entry Controlled Loops in C: In this type of loop, the test condition is checked before entering into the loop body. If the test condition is not true, then the body of the loop will not be executed.




Loops in C
Entry Controlled Loops in C

For Example

FOR Loop and While Loop



2. Exit Controlled Loops in C: In this type of loop, the test condition is checked at the end of the loop of the body that means loop body will execute unconditionally at least once.



Loops in C
Exit Controlled Loops in C

For Example

Do-While Loop


  • Exit controlled loops and entry controlled loops in C is also known as post-test and pre-test loops in C.

Saturday, 29 December 2018

OPERATOR IN THE C PROGRAMMING LANGUAGE


OPERATOR IN C


Before start deep discussion on the operator. First of all, I would like to do the discussion on three terms which are operator, operand, and operation. OK, anyone tells me what is it? No, OK fine, I will explain to you. Start with the term operation, the operation is nothing it is just a process. Understand the meaning of this line, no, it's OK, No issue. Try to understand operation with the lock and a key example I want to open the lock using a key, in this line what is the process is going to happen that is opening a lock right. The task or action which you performed is called operation. Now, anybody can tell me what is operand from the lock and key example, of course, lock and key are operands, quantity or thing on which operation is going to be performed is called operand. Now, come to our main term i.e. the operator when a person derives or operate a machine or equipment or device is called operator, simple is that in mathematics '+' is the operator which perform the addition operation on the operand.

     Operator in the C programming language is a symbol which tells the compiler which operation is going to be performed or which operation is to be performed on the operand.





For example

                      g=10, f=29

                      output= g+f;

In the above example, g and f are operands, '+' is operator and addition is an operation.



Operator in C
Operators in C






TYPES OF OPERATOR IN C


  1. Arithmetic operator


The arithmetic operator performs the mathematical operations like addition, subtraction, multiplication, division and modulus operation.



Operator in C
Symbols of Arithmetic Operator



  • C Program to Demonstrate the Working of Operator



C Program to Demonstrate the Working of Arithmetic Operator


When you compile and  run above program in Turbo C or in Code Block You will get the following result:


Enter  the value of a and b 12 3

a+b=15
a-b=9
a*b=36
a/b=4
a%b=0

The calculation of addition, subtraction, multiplication, division and modulus is similar to the mathematical calculation. Modulus operator is used to getting the remainder because the value of variable a and b is integer type and is completely divisible so we get remainder 0. Let's find out what happened:
 1. When both values i.e. 'a' and 'b' are float data type
 2. When 'a' is float data type and 'b' is an int data type.



1. When both values i.e. 'a' and 'b' are float data type

operator in C
Operation of Modulus operator when both types of data are float 


Output

error: invalid operands to binary % (have 'float'  and 'float')


An error occurs after compilation of the above program because modulus operator is not applicable when both the operands are of the float data type.



2. When 'a' is float data type and 'b' is an int data type.


operator in C
Modulus operator when one type of data is a float and other is int


Output

error: invalid operands to binary % (have 'float' and 'int')

An error occurs after compilation of the above program because modulus operator is only worked on an integer data type values.


  • If you want to print two digits after decimal point then instead of writing %f you will write %0.2f and now only two most significant bits are printed after a decimal point or if you want to print four digits after decimal point then you can write %0.4f.

For example


#include <stdio.h>
int main ( )
{
float a; int b;
printf ("Enter value of a and b");
scanf ("%d%d", &a,&b);
printf ("a/b=%f", a/b);
printf ("a/b=%0.2f", a/b);
printf ("a/b=%0.4f", a/b);
return 0;
}


Output

Enter the value of a and b 11 2
a/b=5.500000
a/b=5.50
a/b=5.5000






2. Unary Operator


The unary operator operates on a single operand that means it only needs one variable to perform an operation.


  • Unary minus: Symbol of unary minus is denoted as (-). Unary minus is different from a subtraction operator because subtraction operator needs two operands to operate but unary minus needs only one operand to operate. Unary minus is used to make positive value negative or vice versa.


         For example

        
         int g = 67;
         int f = - g     // f = - 67
          
         OR
         int  g= -67
         int f = -g;      // f=67



  • Increment operator: Increment operator is used to incrementing the value of operand by one. Increment operator is denoted by the symbol (++).
         

Post-increment: This increment first used the value then increases the value of an operand. 

For example 

 int x= 10;
 printf ("x++=%d\n\n",x++); 

 First of all value of x is printed i.e. x=10 then the value of x is incremented by one i.e x++=11.

 printf ("value of x after post-increment of x=%d\n\n", x);        // Output: x=11



Pre-increment: In pre-increment, the first value of the operand is incremented by one then it is used further. 

For example:

int z = 34;
printf ("++z=%d\n", ++z);

Firstly, the value of z is incremented by one i.e. ++z=35 then the value of z is printed.



  • Decrement operator: Decrement operator is used to decrementing the value of operand by one. Decrement operator is denoted by the symbol (--).


 Post-decrement: This decrement first used the value then decreases the value of an operand by one. 

For example 

int w = 45;
printf ("w=%d\n", w--);

Firstly, the value of w is printed i.e w= 45 then it is decreased by one i.e. w = 44.
           


Pre-decrement: In pre-decrement, the first value of the operand is decremented by one then it is used further. 

For example

int w = 45;
printf ("w=%d\n", --w);

First of all, the value of w is decremented by one i.e. w=44 then it is printed.


  • Logical Not operator: Logical Not operator is denoted as (!) and it reverses the logical state of the operand. 

For example 

if the value of k is true, then !k is false
if the value of k is false, then !k is true


  • sizeof ( ) operator: sizeof operator is used to calculating the size of the operand.

For example

int a;
sizeof (a);

After the run of "sizeof" instruction compiler tells the size of integer 'a' i.e 4 bytes. Similarly, if you want to find out the size of float, double, char etc. you can write "sizeof" command before operand.



3. Assignment Operator


The assignment operator is used to assign a value to an operand. Associativity of the assignment operator is from right to left i.e. value give on the right-hand side of an operator is assigned to the variable on the left.

Variable = Value;

The assignment operator is combined with other operators to make a shorter version like

a = a+15 can be written as a +=15. This operator first adds the 15 to the value of 'a' and then transfer to operand 'a'.
Similarly, a = a-15 can be written as a-=15.
 a = a/15, a = a*15 and a = a%15 can be written as a/=15, a*=15 and a%=15.



4. Relational Operator


Relational operator is used to checks the relation between two variable like a comparison, greater than, less than etc. If that relation or expression is true then it gives/returns true value i.e. 1 otherwise zero/ false value.

== equal to operator checks the value of two variables if the value of operands is equal then it returns true value i.e. one otherwise false i.e. zero.

!= not equal to operator is used to checks the value of the given operand is equal or not, if it is equal it returns false value else true value i.e. 1.
  
> greater than operator checks the value of the first operand is greater than the second operand if it is true then it return 1 else it returns 0.

< less than operator checks the value of the first operand is less than the second operand if yes then it returns 1  else it returns zero.

<= less than equal to operator checks the value of the first operand is less than or equal to the second operand if yes then it returns 1 otherwise it returns zero.

>= greater than equal to operator checks the value of the first operand is greater than or equal to the second operand if yes then it returns 1 else it returns zero.


  • C program to demonstrate the working of the relational operators.

operator in C
Example of working of Relational Operator

 Output

operator in C
An output of the above program


5. Logical Operator



Logical operators are used to performing a logical operation like AND, OR and NOT operation. The operation of these operators are similar to the operation of AND, OR and NOT gate in digital electronics. A logical operator is used to checking two or more conditions. Logical operators are described below:


  • Logical AND operator: When both conditions are true (any non-zero value is considered as true value) then the output is true if any single condition is false then the output is false. Logical AND operator is denoted by the symbol (&&).

Table of Logical AND operator


For example

int b = 19;

(b 20) && (b++)

First of all, the compiler checks the value of 'b' which is greater than 20 or not? If it's not, then compiler not move to check next condition and gives false output. If the value of 'b' is greater than 20 then the compiler will check the condition i.e. increase the value of 'b' by one. Because 'b > 20' and ' b++' is true then output will be true.

  • Logical OR operator: Any single condition is true (any non-zero value) then the output will be true. Logical OR operator is denoted as (||).


Table of Logical OR operator

For example

int w = 20;
(w > 21) || (w == 20)


In the above expression, first checks the condition (w > 21) or not, the value of the operand w is 20 and the condition w > 21 becomes false because 20 is not greater than 21. Now the compiler checks the next condition mention in the expression i.e. w==20 and this condition is true. So, the output of the expression is true.


  • Logical NOT operator: This operator is a unary operator which reverses the value i.e. if the value is true then this operator make the value false or vice-versa. A symbol used for NOT operator is (!).

Table of Logical NOT operator


6. Ternary Operator


Ternary means three objects whenever any operator operates on three operands are known as Ternary operator. The ternary operator is a shorter version of the if-else statement. It is also known as a conditional operator.


Syntax

Condition-1 ? statement-2 : statement-3


The above statement says that when condition-1 is true then the statement-2 is operated else statement-3 is operated.


Operator in C
Ternary operator

In the above program, when condition (a > =b) is evaluated to true then the output is k=c else k= d.


Output

The final result of k = 20


7. Bitwise operator


These operators are used to perform manipulation of single bits of a number. This can be used with any of the integer types. Bitwise operators are shown below

Operator in C
Description of Bitwise Operator



  • A program which shows the working of all Bitwise Operator

Operator in C
Bitwise Operator


Output

Operator in C
An output of the Bitwise Operator



  • Left Shift Operator (<<): This operator shifts the bits of a number to the left and put zero to the right side.
         For example

0000 1111 << 2 will shift the two bits of a number to the left then the output will be 0011 1100.

Try to understand it using one more example  1111 0011<< 2 and the output is 1100 1100.


  • Right Shift Operator (>>): This operator shifts the bits of a number to the right and put zero to left as a result.


For example


0000 1111 >>2 will shift the two bits of a number to the right then the output will be 0011 1100.










































Monday, 10 December 2018

NESTED IF ELSE & SWITCH STATEMENT IN C


Nested if-else and switch statement
Choose Your Option

NESTED IF ELSE STATEMENT IN C



  • Nested if -else statement is also known as ladder if-else statement in C. 

  • Nested if-else statement is the extension of the if-else statement.

  • Nested if-else statement is decision-making statement.

  • When series of decisions are involved then we use nested if-else statements.


Syntax


if (condition-1)

{
statement-1
}

else-if (condition-2)

{
statement-2
}

else-if (condition-3)

{
statement-3
}

else

{
statement-4
}

When the true condition is achieved, the statement associated with it will execute and control will be reached at the statement-4. When all conditions are false then the default statement will be executed.

Flow Chart of Nested if-else statement in C



nested if-else statement in C
Flow Chart of the nested if-else statement in C





When condition-1 is true, then statement-1 associated with it will execute otherwise condition-2 will be checked. When condition-2 is true then statements associated with it will execute else next condition will be checked by the compiler i.e. condition and if this condition is true then the code of block will execute else default statement will execute. But when all the conditions are false then statement-4 will execute.


Switch statement in C


When we have various options (conditions) then the nested if-else statement is used. But nested if-else statement increases the complexity of a program when the number of options increases. Switch statement checks the value of an entered variable. When the value has occurred then statements associated with it will execute.


Syntax



Switch (expression)

{
case  value-1:
                  block-1
                  break;
case  value-2:
                block-2
                break;
         
______________
______________
______________
______________

default:
              default block
              break;
}

statement


  • Expression is a character or an integer. Value-1 and Value-2 are constant values.

  • These values should be unique in each case otherwise an error will occur.

  • When the switch statement will be executed, the statement associated with the value-1 and value-2 will execute.

  • The break statement is written at the end of the block of statement to exit from the block of the statement.

  • The default value is executed when all the cases occur false.



The switch statement is readable. In the switch statement, an expression is executed only one time but in the nested if-else statement, the expression is executed the number of times. The switch statement is faster than the nested if-else statement in c. Difference between nested if-else statement and switch statement in C.






















Saturday, 8 December 2018

IF-ELSE STATEMENT IN C

IF-ELSE STATEMENT IN C




If-else statement is decision-making statement. if-else statement is an extension of if statement. We try to understand if-else statement using a real-life example. Suppose, you want to go to Bangalore from Delhi, to reach Bangalore you have two ways either you will go through flight or by train. You cannot use both flight and train at the same time. When your passport, flight tickets, identification id will appropriate then you will get a flight but if any one of the things is missed then flight may be missed. Now, what’s the next option you will go by train. From this example, you can understand that if all conditions are full-filled then the statement attached with that condition will execute otherwise other option will choose.

              Similarly, for the if-else statement, when if-condition is true then the block of code with if condition will execute otherwise block of code of else will execute.

Syntax:         
                                                    
if (condition)
{

// block of code

}
else
{

// block of code


FLOW CHART OF if-else statement in C





if-else statement in C
                                                  Flow Chart of the if-else statement in C


Program 1: Write a program to find out given number is odd or even.

Theory


To find out given number is even or odd. That number is divided by 2. After division, if the remainder is zero then that number is even otherwise odd.

Algorithm  

                                                                                                                                    

Step1: Start the program.
Step2: Input Data: num=13.
Step3:  Number is divided by 2.
          If the remainder is zero then given number is even else given number is odd.
Step4: Stop the program.

Flow Chart of Odd/Even Number Using  if-else statement in C




Flow chart of odd/even number program

Program


#include <stdio.h>
int main()
{              
    int num=13, remainder;
    remainder= 13%2;
    if (remainder==0)
    {
        printf ("Number is even  %d \n", num);
    }
    else
    {
        printf ("Number is odd %d \n",  num);
    }
    return 0;
}

Output



if-else statement in C

Program 2: Write a program to find out given year is a leap year or not.


 Theory


A year is considered as a leap year when it is divided by 4. When the remainder is zero it is a leap year otherwise it is not a leap year.


For example         

year =1990


                              Remainder = 1990 % 4 = 2


                             1990 year is not a leap year.


Algorithm                                                                       

Step1: Start the program                         
Step2: year = 1990.
Step3:  remainder = year % 4.
          If the remainder is equal to zero then given year is a leap year.
          Else given year is not a leap year.
Step4: Stop the program.


Flow Chart of Leap Year Using if-else statement in C



if-else statement in C

Flow Chart of the leap year program

Program


#include <stdio.h>
int main()
{
    int year, remainder;
    printf ("Enter year");
    scanf ("%d", &year);
    remainder = year%4;
    if (remainder == 0)
    {                                      
        printf ("%d year is a leap year \n", year);
    }
    else
    {
        printf ("%d year is not a leap year \n", year);
    }
    return 0;
}

Output



if-else statement in C


Program 3: Write a program to find out given number is prime or not.


Theory
Those number which is divided by 1 or itself are prime numbers. For example: 2, 3, 5, 7, 31, 19 etc.

Algorithm
Step1: Start the program.
Step2:  Enter number.
Step3: If a number is divided by 1 and itself then given number is prime number otherwise.
Step4: Stop the program.
             

Flow Chart of  Prime Number using if-else statement in C             

               

if-else statement in C


Flow chart of prime number program using  if-else statement in C

Program


#include <stdio.h>
int main()
{               
    int num=4,i,count=0;
    for (i=1;i<=num;i++)
    {
        if (num%i==0)
        {
            count++;
        }

    }
    if(count==2)
    {
        printf("prime number is %d\n", num);
    }
    else
    {
        printf ("Not a prime number %d \n", num);
    }
    return 0;
}

Output



if-else statement in C

Program 4: Write a program to find out given number is palindrome or not.


Theory




A number is said to be palindrome when it is reversed it always occur same.


For example 



number  = 16361
   

When we reverse it, we occurred the same number. So, 16361 is palindrome number.
               
If we reverse 163 then we get 361. So, 163 is not a palindrome number.


Algorithm         


                   

Step1: Start the program.

Step2: Input Data: num = 131, remainder, result=0, a.
            a = num
Step3: while (num !=0)
           remainder = num%10
            result=result*10+remainder;
            num=num/10;
Step4: if enter number is equal to output then that number is palindrome otherwise it is not a  palindrome number.

Step5: Stop the program.


Flow Chart of Palindrome Number Using if-else statement in C



if-else statement in C


Flow Chart of palindrome number using if-else statement in C



Program



#include <stdio.h>

int main()

{       

    int num=131, remainder, result=0,a;

    a=num;

    while (num !=0)

    {

        remainder = num%10;

        result=result*10+remainder;

        num=num/10;

    }

    if (a==result)

    {

        printf ("%d is palindrome \n",a);

    }

    else

    {

        printf ("%d is not palindrome \n",a);

    }

    return 0;

}


Output



if-else statement in C


Program 5: Write a program to find out given number is Armstrong or not.


Theory



A number is said to be Armstrong number when the sum of cube of each digit is equal to the number itself.

For example:

Number = 123

Result = (1)3 + (2)3 + (3)3          = 1+ 8+27 = 36

Because, 36 is not equal to 123, so it is not an Armstrong number.



Algorithm     


             

Step1: Start the program.
Step2: Input Data: num=371
Step3:  remainder = num%10
            sum=sum+pow(remainder,3)
            num=num/10
Step4: When the sum of cube of each digit is equal to the entered number then that number is Armstrong number otherwise not an Armstrong number.
Step5: Stop the program.




Flow Chart of Armstrong number program using if-else statement in C






if-else statement in C

Flow chart of finding out Armstrong number using if-else statement in C


Program



#include <stdio.h>
#include <math.h>
int main ( )
{              
    int num = 371, remainder, i,  sum=0, a;
    a=num;
    while (num!=0)
    {
        remainder = num%10;
        sum =sum+pow(remainder,3);
        num=num/10;
    }
    if(a==sum)
    {
        printf ("%d is armstrong number \n",a);
    }
    else
    {
        printf ("%d is armstrong number\n",a);
    }
    return 0;
}


Output

if-else statement in C