Saturday, 25 October 2014

Control Statement break and continue

Break Statement

break statement is used inside loops and switch statements. Sometime it becomes necessary to come out of the loop even before the condition becomes false. in such a situation, break statement is used to terminate the loop. This statement causes an immediate exit from that loop in which this statement appears. it can be written as-

break;
When break statement is encountered, loop is terminated and the control is transferred to the statement immediately after the loop. The break statement is generally written along with a condition. if condition. if break is written inside a nested loop structure then it causes exit from the innermost loop.


// program to understand the use of break/

#include<stdio.h>
main()
{
int n;
for(n=1;n<=5;n++)
{
     if(n==3)
     {
       printf("I understand the use of break\n");
       break;
     }
       printf("Number =%d\n",n);
}
printf("Out of for loop\n");
}

Output:

Number=1
Number=2
I understand the use of break
out of for loop

// program to understand use of break another example:
#include<stdio.h>
main()
{
    int choice;
    printf("Enter Your choice:");
    scanf("%d",&choice);
    switch(choice)
    {
        case 1:
        printf("First\n");
        break;
          
          case 2:
          printf("Second\n");
           break;
          
           case 3:
           printf("Third\n");
             break;
          
           default:
           printf("Wrong choice:\n");

}

Output

Enter your choice : 2
second 

in second example when break find then compiler goes out of switch condition, if we does not use break condition in the above example then if we select case 1 then print "First" as well as "second" Third and wrong choice all printed because c is sequential programming language program compile in sequentially, when above program compiler find the break that terminate the condition and goes out of that block. 


Wednesday, 15 October 2014

Control Statement Switch

Switch
-------------------------------------------------------------------------------------------------------------------
This is a multi-directional control statement. sometime there is need in program choice among number of alternatives. if we want to create a program that inclde number of option but we can choose among of this, for that we use switch condition.

Syntax:- 
             switch (expression)
                   {
                      case 1:
                      statement;
                      ...............;
                      
                      case 2:
                      statement;
                      ...............;

                      case n:
                      statement;
                      ...............;

                      case default:
                      statement;
                      ...............;

Here switch, case and default are keywords, The expression in the case which is integer like 1 , 2 ..n, it can be integer character variable. switch expression that is enter into switch matches to case expression then executes any one case, if expression is not find into case then default executed and print massage user define. the case keyword should be of integer or character type. They can be either constants or constant expressions. These constant must be different from one another, we can't use float.

Method to writing valid and invalid ways of writing switch and case.

Valid
   
 int a,b,c   char d,e     float f;
switch(a), switch(a>b), switch(func(a,b))

case 4:       case 'a':       case 2+4:       case 'a'>'b':

Invalid 

  int a,b,c   char d,e     float f;

switch(f)  switch(a+3.5)

case "second"              case 3.5:              case a+2:


Working of switch

Firstly the switch expression is evaluated, then the value of this expression is compared one by one with every case constant.If the value of expression matches with any case constant, then all statements under that particular case are executed. if none of the case constant matches with the value of the expression then the block of statements under default is executed."default" is optional, if it is not present and no case matches then no action takes place.

// program to understand the switch control statement.

#include<stdio.h>
main()
{
    int choice;
    printf("Enter Your choice:");
    scanf("%d",&choice);
    switch(choice)
    {
        case 1:
        printf("First\n");
        
          case 2:
          printf("Second\n");

           case 3:
           printf("Third\n");

           default:
           printf("Wrong choice:\n");

}


Output

Enter your choice : 2
second 
Third 
Wrong choice

Here value of choice matches with second case so all the statement after case 2 are executed sequentially. because its flow is sequentially and when case 2 is find but after this there is no stop or break statement that stop the flow of switch so it print all case after selected case. we use break keyword in every case.
        
        
#include<stdio.h>
main()
{
    int choice;
    printf("Enter Your choice:");
    scanf("%d",&choice);
    switch(choice)
    {
        case 1:
        printf("First\n");
        break;
          
          case 2:
          printf("Second\n");
           break;
          
           case 3:
           printf("Third\n");
             break;
          
           default:
           printf("Wrong choice:\n");

}

Output

Enter your choice : 2
second 

in this example we use break keyword because sequential flow in the switch when our input matches with any case then that case execute after that when compiler find break keyword, compiler stop and go out of switch.

Flow Chart of Switch



switch executed when switch expression==case constant, otherwise default is executed.



// program to perform arithmetic calculations on           integer.

#include<stdio.h>

void main()
{
char op;
int a,b;
printf("Enter number operator and arithmetic number");
scanf("%d%c%d",&a,&op,&b);
switch(op)
{
case '+':
printf("Result=%d\n",a+b);
break;

case '-'
printf("Result=%d\n",a-b);
break;

case '*'
printf("Result=%d\n",a*b);
break;

case '/'
printf("Result=%d\n",a/b);
break;

case '%'
printf("Result=%d\n",a%b);
break;

default:
printf("Enter Valid operator\n");
break;

} // end of switch
} // end of main

Output :

Enter number operator and another number : 2+5

Result :7

in this program, the valid operator for multiplication is only '*', if want to make 'x' 'X' also valid operator for multiplication.


                 

                      

Friday, 10 October 2014

Control Statement If....else















Control Statement

In C program Statement are executed sequentially in order in which they appear in the program.But sometime we may want to use a condition for executing only a part of program. Also many situations arise where we may want to execute some statement several times. Control statements enable us to specify the order in which the various instructions in the program are to be executed.This determines the flow of control. Control statements define how the control is transferred to other part of program.
C language supports four types of control statement,


  1. if......else
  2. goto
  3. switch
  4. loop

If......else

This is bi-directional conditional control statement. This statement is used to test a condition and take one two possible actions. if the condition is true then a single statement or block of statements is executed (one part of the program), otherwise another single statement or block of statement is executed (other part of program).

Syntax of if-

if(condition)
{
statement;
.............
.............
}



Flow chart if if. statement..





here if the condition is true then statement is executed and if it false then the next statement which is immediately after the control statement is executed.


Syntax of if...... else 


if(condition)
{
statement;
............
}
else
{
statement;
.............
}
in this syntax , if condition is true then first block is execute, otherwise second block executed.

Flow Chart of if...... else Control Statement 




Here if the condition is true then statement 1 is executed and if it is false then statement 2 is executed. After this the control transfers to the next statement which is immediately after the if...else control statement.

// Program to print a message if negative number is entered.

#include<stdio.h>
main()
{
int num;
printf("Enter a number");
scanf("%d",&num);
if(num<0)
printf("number entered is negative");
printf("Value of num is%d,num);
}

Output

Enter a number :-6
numaber entered is negative
value of num is = -6

// program to print the larger and smaller of the two number

#include<stdio.h>
main()
{
int a,b;
printf("Enter the first number");
scan("%d",&a);
printf("Enter the Second number");
scan("%d",&b);
if(a>b)
printf("larger number =%d and smaller number=%d,a,b);
else
printf("larger number =%d and smaller number=%d",b,a);
}

Output

Enter the first number: 9
Enter the Second number :11
larger number=11 and smaller number =9


Nesting of if ..... else

When we include another if.... else in the portion of if block or else block(as we need). this is called nesting of if.... else statements. we can include only if portion or else portion separately as we need in the program, not need to write if... else both portion simultaneously.  

Syntax:-  

                                     if (Condition 1)
                        {
                               if (Condition 2)
                                     Statement;
                               else 
                                     Statement;
                         }

                         else
                         {
                                 if (Condition 3)
                                      Statement;
                                                   else
                                       Statement;
                          }


// Program to find largest number from given number.

#include<stdio.h>
main()
{
     int a,b,c,large;
     printf("Enter three number:");
     scanf("%d%d%d",&a, &b, &c);
     
     if( a>b)
     {
          if(a>c)
               large=a;
           else
               large=c;
     }

    else
    {
          if (b>c)
                 large=b;
          else
                 large=c;
    }
}                                   // end of main




While nesting if....else statements, sometime confusion may arise in associating else part with appropriate in if part. example-

if (grade=='A')
{
     if(marks>95)
      print("excellent");
}

else
      printf("work hard for result");

if we write the above code without braces

if (grade=='A')

     if(marks>95)
      print("excellent");


else
      printf("work hard for result");


here the else part is matched with the second if. but we wanted to match it with the first if. The compiler does not associate if and else parts according to the indentations, it matches the the else part with closest unmatched if part. so whenever there is double regarding matching of if and else parts can use braces to enclose each if and else blocks.


// Program to find whether a year is leap or not.

#include<stdio.h>
main( )
{
int year;
printf("Enter Year:");
scanf("%d",&year)
if(year%100==0)
{
    if(year%400==0)
          printf("Leap Year\n");
    else
          printf("Not leap");
}

else
{
    if(year%4==0)
         printf("Leap year\n");
    else
         printf("Not leap");
}


else if ladder

This is a type of nesting in which there is an if....else statement in every else part except the last else part.

Syntax:-
                  if( condition 1)
                           statement;
                        else     
                                  
                                 if (condition)
                                     statement;
                                 else
                                            
                                           if(condition)
                                               statement;
                                            else
                                                statement;

we can write this syntax in another form, this is a compact form.

                          if( condition 1)
                                    statement;
                          else  if (condition)
                                     statement;
                          else if(condition)
                                      statement;
                                            
                            else
                                      statement;


Flow chart of else if ladder



Here each condition is checked, and when condition is found to be true, the statement corresponding to that are executed, and the control comes out of the nested structure  without checking remaining conditions. if none of the condition is true then last else part is executed.

//program to find out the grade of a student when the marks of 4 subjects are given. The method of assigning grade is as-
per>=85                                      grade A
per<85 and per>=70                    grade B
per<70 and per>=55                    grade C
per<55 and per>=40                    grade D
per<40                                        grade E

#include<stdio.h>
main()
{
float m1,m2, m3, m4, totle, per;

char grade;

printf("Enter marks of 4 subjects");

scanf("%f%f%f%f",&m1, &m2,&m3,&m4);

totle=m1+m2+m3+m4;

per=totle/4;

if(per>=85)
 grade='A';
          
           elseif(per>=70)
           grade='B';

elseif(per>=55)
grade='C';
          
           elseif(per>=40)
           grade='D';
else
   grade='E';

printf("Percentage is %f\n grade",per,grade);
}



Saturday, 4 October 2014

Operator and Expressions

Operators and Expressions

An operator that performs a specific task and  yield the value. The variables, constants can be joined by various operators to form an expression. An operand is a data on which operator acts. Some operators require two operands.


There are many type of Operators-
  1. Arithmetic Operators
  2. Assignment Operators 
  3. Increment and Decrements Operator
  4. Relational Operator
  5. Logical Operator 
  6. Conditional Operator 
  7. Comma Operator 
  8. Sizeof Operator
  9. Other Operators 

Arithmetic Operator

Arithmetic operator are used for numeric calculations. They are of two type-
  1. Unary arithmetic operator
  2. Binary arithmetic operatoer

Unary Arithmetic Operator : In unary operator only one operand are used.
e.g. +x , -y ,+z , +r.

Binary Arithmetic Operator : Binary operator require two operands. There are five binary arithmetic operators-

Operator
Purpose


+
Addition
-
Subtraction
*
Multiplication
/
division
%
Give the remainder


Example :-

Integer Arithmetic :- When both operand are integer then the arithmetic operation with these operands is called integer arithmetic and the resulting value is always an integer. take two variable a and b. The value of a=17 and b=4, the result of the following operand are-


Expression
Result


a+b
21
a-b
13
a*b
68
a/b
4
a%b
1

After division operation the decimal part will be truncated and result is only
integer part of quotient.

#include<stdio.h>
main()
{
int a=17 , b=4;
printf("Sum =%d\n", a+b);
printf("Substract =%d\n",a-b);
printf("Product =%d\n",a*b);
printf("Quotient=%d\n,a/b);
printf("Remainder =%d\n",a%b);
}

Output-
Sum=21
Substract=13
Product=68
Quotent=4
Remainder=1


Floating point Arithmetic : When both operands are of float type then the arithmetic operation with these operands is called floating point arithmetic. Take two variable a=12.4 and b=3.1 then result of the following operations.


Expression
Result


a+b
15.5
a-b
9.3
a*b
38.44
a/b
4.0

The modules operator % cannot be used floating point number

#include<stdio.h>
main()
{
float a=12.4, b=3.8;
printf("Sum =%.2f\n",a+b);
printf("substract =%.2f\n",a-b);
printf("Product =%.2f\n",a*b);
printf("a/b =%.2f\n",a/b);
}


Assignment Operator


A value can be stored in a variable with the use of assignment operator. This assignment operator "=" is used in assignment expression and assignment statement.
The operand on the left hand side should be a variable, while the operand on the right hand side can be any variable, constant or expression. The value of right hand side operand is assigned to the left hand operand. Example --

x=8               8 is assigned to x.
y=5               5 is assigned to y
s=x+y-2        Value of expression x+y-2 is assigned to s
y=x               Value of x is assign to y.
x=y               Value of y is assigned to x

The value that is being assigned is consider as value of the assignment expression. for example =8 is an assignment expression whose value is 8.
We can multiple assignment operation also.

x=y=z=20
Here all three variable x,y,z will be assigned value 20, and the value of the variable whole expression will be 20.
if we put a semicolon after the assignment expression then it become an assignment statement  for e.g. 
x=8;
y=5;
s=x+y-2;
x=y=z=20;
when the variable on the left hand side of assignment operator also occurs on the right hand side then we can avoid writing the variable twice by using compound assignment operators. for e.g.
x=x+5
can also be written as
x+=5
here += is a compound statement
we have other compound statement-
x-=5             is equivalent                      x=x-5
y*=5             is equivalent                      y=y*5
sum/=5         is equivalent                     sum=sum/5



Increment And Decrements Operators

C has two useful operators increment(++) and decrement(--). there are unary operators because they operate on a single operand. The increment operator(++) increment the value of the variable by 1 and decrement by 1 and decrement operator (--) drecrements the value of the variable by 1.
++x    is equivalent    x=x+1
--x      is equivalent    x=x-1
These operators should be used only with variable; they can't be used with constant or expressions.
for example the expressions ++5 or ++(x+y+z) are invalid.

These operator are two type-


  1. prefix increment / decrement 
  2. Postfix increment / decrement 

  prefix increment / decrement 

In prefix,operator written before the operand e.g. ++x or --x . here first the value of the variable is incremented/decremented then the new value is used in the operation. take a variable x whose value is 3. means x=3.
The statement y=++x; means first increment the value of x by 1, then assign the value of x to y.
This single statement is equivalent to these two statements-
x=x+1;
y=x;
Hence now value of x is 4 and value of y is 4.

The statement y=--x; means first decrement the value of x by 1 then assign the value of x and y.
This statement x=x-1;
y=x;
Hence now value of x is 3 and value of y is 3.

// Program to understand the use of prefix increment/ decrements 
#include<stdio.h>
main()
{
int x=8;
printf("x=%d\t",x);
printf("x=%d\t",++x);
printf("x=%d\t,x);
printf("x=%d\t",--x);
printf("x=%d\t",x);
}

Output
x=8, x=9, x=9, x=8;x=8


Postfix Increment /Decrement

Operator is written after the operand. here first the value of variable is used in the operation and then increment/decrement is performed. take a variable x whose value is 3 means x=3;
The statement y=x++; means first the value of x is assigned to y and then x is incremented. This statement is equivalent to these two statements-
y=x;
x=x+1;
hence now value of x is 4 and value of y is 3
The statement y=x--; means first the value of x is assigned to y and then x is decremented. this statement is equivalent to these two varibale-
y=x;
x=x+1
now value of x is 3 and value of y is 4

// understood by program//

#include<stdio.h>
main()
{
int x=8;
printf("x=%d\t",x);
printf("x=%d\t",x++);
printf("x=%d\t,x);
printf("x=%d\t",x--);
printf("x=%d\t",x);
}

Output
x=8, x=8, x=9, x=9;x=8



Relational Operators

Relational operators are used to compare values of two expression depending on their relations. An expression that contains relational operators is called relational expression. If the relation is true then the value of relational expression is 1 and if the relational is false then the value of expression is 0.
The relational operators are.

Operator
Meaning


< 
Less than
<=
Less than or equal to
==
Equal to
!=
Not equal to
> 
Greater than
>=
Greater than or equal to
Two variables a=9 and b=5, and form simple relational expression with them

Expression
Relation
Value of Expression



A<b
False
0
A<=b
False
0
A==b
False
0
A!=b
True
1
a>b
True
1
A==0
False
0
B!=0
True
1

The relational operators are generally used in If.......else construct and loops. 

=Program to understand the use of relational operators.

#include<stdio.h>
main()
{
int a,b;
printf("Enter the value for a and b");
scanf("%d%d",&a,&b);
if(a<b)
printf("%d is less than %d\n",a,b);
if(a<=b)
printf("%d is less than or equal to %d\n",a,b);
if(a==b)
printf("%d is equal to %d\n",a,b);
if(a!=b)
printf("%d is not equal to %d\n",a,b);
if(a>b)
printf("%d is greater than %d\n",a,b);
}

It is important to note that the assignment operator(=) and equality (==) are entirely different. assignment operator = is used to assign the value, and == operator is used to compare the value.



Logical Or Boolean Operators

An expression that combines two or more expressions is termed as a logical expression. for combining these expressions we use logical operators. These operators return 0 for false and 1 for true. The operands may be constants, variable expressions. C has three logical operators.

Operator
Meaning


&&
AND
||
OR
!
NOT

  1. AND (&&) Operators

This operator give the net result true if both the conditions are true,otherwise the result is false.


Condition1
Condition2
Result



False
False
False
False
True
False
True
False
False
True
True
True

Lets us take three  variable a=10, b=5, c=0
if we have a logical expression 
(a==10)&&(b<a)Here both the conditions a==10 and b<a are true, and hence this whole expression is true. Since the logical operators return 1 for true hence the value of this expression is 1.


Expression

Result
Value of expression




(a==10)&&(b>a)
True && false
False
0
(b>=a)&&(b==3)
False && false
False
0
A && b
True && true
True
1
A && c
True && false
False
0


2.OR (| |) Operator :

This operator gives the net result false, if both the conditions have value false , otherwise the result is true.

Condition  1
Condition  1
Result



False
False
False
False
True
True
True
False
True
True
True
True

Let us take three variable a=10 , b=5, c=0
Consider the logical expression-
(a>=b) ||(b>15)

this gives result true because one condition is true.

Expression

Result
Value of expression




A||b
True || true
True
1
A||c
True||false
True
1
(a<9)||(b>10)
False||false
False
0
(b!=7)||c
True||false
True
1

3.Not (!) Operator

This is a unary operator and it negates the value of the condition. if the value of the condition is false then it gives the result true. if the value of the condition is true then it gives the result false.

Condition
result


False
True
True
False

Conditional Operator

Conditional operator is a ternary operator (? and :) which requires the three expression as operands. 

Syntax- (condition)? Expression 1 : Expression 2

If the condition is true then expression 1 is proceed and if condition is false then expression 2 is proceed.
for eg. if a=5 and b=6;
(a>b)?printf("the greater", a):printf("b is greater",b);

// program to print the larger of two number using conditional operator

#include<stdio.h>
main()
{
int a,b,max;
printf("enter value for a and b");
scanf("%d%d",&a,&b);
max=a>b? a:b;
printf("Larger of %d and %d is %d\n"a,b,max);
}

Output

Enter value for a and b: 12  7
Larger of 12 and 7 is 12

Comma Operator

The comma operator (,) is used to permit different expression to appear in situations where only one expression would be used. The expression are separated by the comma operator.The separated expression are evaluated from left to right . Comma Operator separated two or more variable.

a=8, b=7,c=9,a+b+c

Here 4 variable 8 is assigned to variable a, 7 is assigned to variable b, 9 is assigned to variable c and all variable is separated by comma operator.

// Program to understand the use of comma operator.

#include<stdio.h>
main()
{
int a,b,c,sum;
sum=(a=8,b=7,c=9,a+b+c);
printf("Sum=%d",sum);
}

Output

24

Sizeof Operators

Sizeof is an unary operator. This operator gives the size of its operand in the term of bytes. The operand can be a variable, constant or any datatype( int, float,char etc) for example- sizeof(int) gives the byte occupied by the int data type.

// Program to understand the sizeof operator.

#include<stdio.h>
main()
{
int var;
printf("Size of int =%d",sizeof(int));
printf("Size of float =%d",sizeof(float));
printf("Size of var =%d",sizeof(var));
printf("Size of an integer constant=%d",sizeof(45));
}

output

Size of int : 2
Size of float : 4
Size of var : 2
Size of integer Constant =2