Thursday 19 September 2013

Program to ckeck for a prime

// Program to ckeck for a prime

 

#include<stdio.h>  //Preprocessor statement

#include<conio.h>  //Preprocessor statement

void main()             //main function begins

{

  int n,i;                 // integer variable declaration

  char flag=’f’;      //character variable declaration

  clrscr();             //to clear the output screen

  printf(“ enter an integer value “); // display the message

  scanf(“%d”,&n); // read the value from keyboard and  

                      //store in the address location of variable n

                      // check for prime logic begins

  if(n<=0)

   {

         printf(“\n undefined”);

       }

  else if(n==1)

       {

       printf(“\n Natural Number”);

       }

  else if((n==2)||(n==3)) 

       {

         printf(“\n The Number is Prime”);

       }

  else          // this else part is for numbers > 3

       {        // remainder after division is checked taking                 

                //divisors from 2 to n/2 values if for any value              

               //the remainder is zero flag is changed to ‘t’ so

              //that further checking is stopped

          i=2;

       while((i<=n/2)&&(flag==’f’))

              {

                if((n%i)==0)

                     {

                           flag=’t’;

                     }

               i++;

              }                   // end of while loop

         if(flag==’t’)

              {

                     printf(“\n The number is not Prime”);

              }

         else

              {

                     printf(“\n The number is Prime”);

              }

        }                // end of else for numbers > 3

 

  getch();

}

Sunday 15 September 2013

C language:Upto Loops

1)  What are translators?

            Translators are programming tools that translate high level language into the machine language. Examples: assemblers, compilers and interpreters.

2)  Difference between Interpreter and compiler

             Interpreters translate code one line at time, if an error occurs it display the error and terminates.
               Where as Compiler takes whole program at a time and checks for errors and display the errors cumulatively, if no errors are there then convert the whole program into byte code or machine code.
 
3) Features of C language.
 
(1)     Low-level Features:
 
è  It is closely related to low-level Lang such as Assembly language.
è  It is easy to write assembly codes in C.
 
(2)     Portability:
 
è  C programs are portable i.e.; they can be run on any computer with little or no modification.
è  Compiler & Preprocessor make it possible for C program to run it on different PC.
 
(3)     Powerful:
è  Provides wide variety of data types.
è  Provides wide variety of functions.
è  Provides useful control & loop control statements.
 
(4)     Bit manipulation:
è  C programs can be manipulated using bits.
è  It provides wide variety of bit manipulation operators.
 
(5)     High level features:
è  It is more user friendly as compare to previous languages.
 
(6)     Modular programming:
è  Modular programming is a software design technique that increases the extent to which software is composed of separate part called modules.
è  C program consist of different modules that are integrated together to form complete program.
 
(7)     Efficient use of pointers:
 
è  Pointers have direct access to memory.
è  C supports efficient use of pointer.
4) Applications of C language.
     
       C language is used for creating computer applications and also used a lot in writing embedded software/firmware for various electronics, industrial and communications products which use micro-controllers. It is also used in developing verification software, test code, simulators etc. for various applications and hardware products.

5) Structure of C program.

        A C program basically has the following form:
·         Documentation Section/Comments
·         Link Section /Preprocessor Commands
·         Definition Section/ Defining Constants
·         Global Variable DeclarationSection
·         Main function Section
o   Variable Declaration
o   Statements & Expressions
·         Sub Routines /User Defined Functions
Documentation Section/Comments: are used to give additional useful information like name of the program, author or details of each section inside a C Program. These are not executed. All the comments enclosed in  /*...*/
Link Section/Preprocessor Commands: These commands tell the compiler to link functions or files from the system library.
Example: #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation.
Definition Section/ Defining Constants:  The Definition Section defines    symbolic constants. Example: #define  PI  3.147
Global Variable Declaration Section: Variables that are to be used in more than one function are called global variables and are declared in the global variable section that is outside of all the functions.
Main function Functions: are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main () function. This section contains two parts, one is variable declaration and the other is executable statements. These two parts together have to be enclosed in Flower brackets. The program execution begins at the opening braces and ends at the closing braces.
Variables: are used to hold numbers, strings and complex data for manipulation. Example : int x, y;
Statements & Expressions: Expressions combine variables and constants to create new values. Statements are expressions, assignments, function calls, or control flow statements which make up C programs.
Subprogram Section: This contains all the user defined functions that are called in the main function. User defined functions are generally placed immediately after or before the main function.
7) What is a character set?(about ASCII)
C character set: Each C character is also called “Lexim” i.e.; [Basic Lexical element]
  Character set consists of:
è  Lower case letters
è  Upper case letters
è  Digits
è  Special characters
è  White spaces
Types
Character set
Lower case letters
a-z
       Upper case letters
A to Z
Digits
0-9
Special characters
!@#$%^&*
White spaces
[Tab, New line, Space]
8) ‘C’ tokens?
In a C source program, the basic element recognized by the compiler is the "token." A token is source-program text that the compiler does not break down into component elements. C tokens include keywords, identifiers, constants, strings, special symbols & operators.
9) Keywords & Identifiers? Mention some of them.
    IDENTIFIERS refer to the “names" of variables, functions and arrays. These are user-defined names and consist of a sequence of letters and digits, with a letter as a first character. Whereas KEYWORDS are special words reserved by the C language itself such as int, for, ,while, void etc....

Rules for identifiers:
è  Must consist of only letters, digits or underscore.
è  Only first 31 characters are significant.
è  Cannot use a keyword
è  Must not contain white space.

10) Constants?
A constant is a fixed value that does not change during the execution of a program. Constants can be any of the basic data types i.e. they can be int, float or char. Constants are also known as literals in C.
 CONSTANTS: (1) NUMERIC CONSTANTS    ->INTEGER CONSTANTS
                                                                 ->REAL CONSTANTS
                   (2) CHARACTER CONSTANTS   ->SINGLE CHARACTER CONSTANTS
                                                                ->STRING CONSTANTS
11) Integer constants?        
     An integer constant refers to a sequence of digits. There are 3 types of integers, namely, decimal integer, octal integer and hexadecimal integer.
è  Decimal integer constants (base 10) consist of one or more digits, 0 through 9, where 0 cannot be used as the first digit.
è  Octal constants (base 8) consist of one or more digits 0 through 7, where the first digit is 0.
è   Hexadecimal constants (base 16) begin with a 0x or 0X prefix, followed by a hexadecimal number represented by a combination of digits 0 through 9, and characters A through F.
12) Single character constants?
A single character constant contains a single character enclosed within a pair of single quote marks. Ex: ‘5’,  ‘x’.
Character constants have integer values known as ASCII values. For Ex: printf ( “%d” , ’a’); would print the number 97, the ASCII value of letter a.
13) String constants?
     A string constant is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, special characters and blank space.
   Ex:  “Hello”, “1987”
What backslash character constants or escape sequence? What are they?
                 Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a new line character, single quotation mark, or certain other characters in a character constant, we use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant.
Escape Sequence
Represents
\b
Backspace
\n
New line
\t
Horizontal tab
\v
Vertical tab
\'
Single quotation mark
\ "
Double quotation mark
\\
Backslash



v What are variables? Types of variables?
    A Variable is a data name that may be used to store a data value. A variable may take different values at different times during execution.
   ->Variable names may consist of letters, digits and the underscore character
   -> Uppercase and lowercase are significant. i.e. the variable Total is not the same as total or TOTAL.
    -> It should not be a keyword.
    -> White space is not allowed.
EX: Average, X1, raise
There are four basic types of variables in C; they are: char, int, double, and float.
Type name
Meaning
char
The most basic unit addressable by the machine; typically a single octet (one byte).
int
The most natural size of integer for the machine; typically a whole 16, 32 or 64-bit (2, 4, or 8 bytes respectively) addressable word.
float
A single-precision floating point value.
double
A double-precision floating point value.

 Declaration of Variables:
Every variable used in the program should be declared to the compiler. The declaration does two things.
  1. Tells the compiler that these are variable names are used in the program.
  2. Specifies what type of data the variable will hold.
  3. Compiler then allocates memory.

The general format of variable declaration :
The data type followed by list of variables separated by commas.
data_type  v1, v2, v3… vn;
Where v1, v2, v3 are variable names. A declaration statement must end with a semicolon.
Examples:
char  red;
int   i, j;
float   root1, root2;
 





v What are the different data types that C supports?
Data type is used to determine what type of value a variable or a constant can contain throughout the program.

Mainly data types are categorized into 3 categories:-

1. Fundamental Data Types
2. Derived Data Types
3. User Defined Data Types

1. Fundamental Data Types
       All C compilers support 5 fundamental data types, namely integer (int), character (char), floating point (float), double-precision floating point (double) and void.

2. Derived Data Types

Data types that are derived from fundamental data types are called derived data types. Derived data types don't create a new data type; instead, they add some functionality to the basic data types.  The two derived data types are
  Array,  Pointer.

3. User Defined Data Types

User defined data type is used to create new data types. The new data types formed are fundamental data types. Different user defined data types are: struct, union, enum, typedef.


·     Fundamental Data Types?

All C compilers support 5 fundamental data types, namely integer (int), character (char), floating point (float), double-precision floating point (double) and void.

1.
Integer
int
2
Character
char
3.
Floating Point
float
4.
Double precision floating point
double
5.
Void
void

The size and range of each data type is given in the table below
Integer Type:
Integers are whole numbers with a machine dependent range of values. C has 3 classes of integer storage namely short int, int and long int. All of these data types have signed and unsigned forms. The qualifier short int requires half the space than normal integer values. The qualifier Unsigned numbers are always positive and consume all the bits for the magnitude of the number. The qualifier long and unsigned integers are used to declare a longer range of values.
 


   Type                                    Constant Examples               Format Specifiers

      short  int                            -128 , 0x127, 027                  %hd or %hi, %hx, %ho
    unsigned short int            0 ,  0x255, 0255                   %hu 
                                      
     int                              12, -97 ,0xFFE0, 0177         %d or %i, %x, %o
      unsigned int                      12u, 0xffu, 077u                     %u , %x, %o
      long int                        12L, 0xffffL                      %li or %ld, %lx, %lo
     unsigned long int            12UL,0xfeabfUL                 %lu, %lx, %lo


Floating Point Types:
Floating point number represents a real number with 6 digits precision. Floating point numbers are denoted by the keyword float. When the accuracy of the floating point number is insufficient, we can use the double to define the number. The double is same as float but with longer precision. To extend the precision further we can use long double which consumes 80 bits of memory space.
     Type                                  Constant Examples               Format Specifiers

    float                            12.34f                              %f
3.1e-5f --> 3.1*10-5                   %e
                                      0x0.3p10 --> 3/16*210        %g
                                     
    Double                         12.34                               %f
3.1e-5 --> 3.1*10-5                     %e
                                      0x0.3p10 --> 3/16*210        %g

    long double                   12.34l                              %Lf
3.1e-5l --> 3.1*10-5                    %Le
                                      0x0.3p10l --> 3/16*210        %Lg


Void Type:
Void data type is used to represent an empty value. It is used as a return type if a function does not return any value.
Character Type:
A single character can be defined as a character type of data. Characters are usually stored in 8 bits of internal storage. The qualifier signed or unsigned can be explicitly applied to char. While unsigned characters have values between 0 and 255, signed characters have values from –128 to 127.
Type                           Constant Examples               Format Specifiers

  char                           ‘a’, ‘\n’,   ‘9’                            %c


Size and Range of Data Types on 16 bit machine.
type
SIZE (Bits)
Range
Char or Signed Char
8
-128 to 127
Unsigned Char
8
0 to 255
Int or Signed int
16
-32768 to 32767
Unsigned int
16
0 to 65535
Short int or Signed short int
8
-128 to 127
Unsigned short int
8
0 to 255
Long int or signed long int
32
-2147483648 to 2147483647
Unsigned long int
32
0 to 4294967295
Float
32
3.4 e-38 to 3.4 e+38
Double
64
1.7e-308 to 1.7e+308
Long Double
80
3.4 e-4932 to 3.4 e+4932




User defined type
  1. Typedef :
In C language a user can define an identifier that represent an existing data type. The user defined identifierfor the data type can later be used to declare variables.
The general syntax is :

typedef  data_type  identifier;


here type represents existing data type and ‘identifier’ refers to the name given to the data type.


Example:
typedef  int  salary;
typedef  float  average;

        Here salary symbolizes int and average symbolizes float. They can be later used to declare variables as follows:
salary  dept1, dept2;
average  section1, section2;


Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 and section2 are indirectly float data type.



  1. Enumerated data type:  Enumerated data type allows the user to define a data type with range of values. The variables of this type can take values only from the defined  range.
    Syntax:
enum   identifier  {value1, value2 …. Value n};
The identifier is a user defined enumerated data type which can be used to declare variables that have one of the values or identifiers enclosed within the braces. After the definition we can declare variables to be of this ‘new’ type as below.
 enum   identifier   Var1, Var2, Var3, ……… Varn ;

The enumerated variables Var1, Var2… Varn can have only one of the values
Example:
enum  day  {Monday, Tuesday, Wednesday,  Thursday, Friday, Saturday,      
                     Sunday};

enum  day  week_day, week_end;    // variable declaration
week_day = Monday;
week_end = sunday;
if(week_day == Tuesday)
     ----
or identifiers from value1, value2 ….. value n.
The compiler actually treats enumeration data values as integer constants and  by default assigns sequential integers starting with 0. In the example: Monday =0, Tuesday = 1 …..

Enumeration values that subsequently appear in the list are assigned sequential integer values beginning with the specified integer value .

         For example:
  1. enum  day  {Monday=1, Tuesday, Wednesday,  Thursday, Friday,
Saturday,  Sunday};
         Here assigning sequential integers are as Monday =1, Tuesday=2 …….
  1. enum  day  {up, down, right=10, left };

          Here up=0(default), down=1….. but since right=10, left =11…








v Structures:

            Structure represents a collection of data items of different types using a single name.
Syntax :
                                struct tag-name
                                {
                                 Data-type member1;
                                 Data-type member 2;
                                  ……………………
                                };


              struct is a key word,  tag-name is a name defined to hold multiple data items,   Data-type member1,  Data-type member 2 are the various data items can be of different types.                             

Ex:
        struct book-bank
        {
         Char title [20];
         int pages;
         Float price;
         };

 struct is a keyword defines  a structure to hold the details of 3 data fields; title, pages & price. These fields are called structure elements or members; here tag-name is book-bank.

Structure variables can be declared as
Ex:

     struct  book-bank   book1, book2, book3;

  Declares book1, book2, book3 as variables of type struct book-bank.
Members of Structure variables can be accessed with the help of dot (.) operator as :
    book1.title
    book1.pages
    book1.price

v Defining Symbolic Constants
A symbolic constant value can be defined as a preprocessor statement and used in the program as any other constant value. The general form of a symbolic constant is

#define    symbolic-name   value-of-constant
#define is a key  to define a symbolic constant, symbolic-name  is a name to represent the constant,  value-of-constant is the actual value. When compiler encounters symbolic-name,   they are replaced with their defined values. Compiler doesn’t allow the user to modify their values during the execution of the program.

Valid examples of constant definitions are:
# define marks 100
# define total 50
# define pi 3.14159


These constants, marks, total, pi can be used anywhere in the program. When compiler encounters them they are replaced with their defined values. Compiler doesn’t allow the user to modify their values, like marks=marks+1 is not allowed in the program.

18) What are the various operators supported by C?
    C operators are classified into a number of categories. They include:
   (1) Arithmetic operators
   (2) Relational operators
   (3) Logical operators
   (4) Assignment operators
   (5) Increment and decrement operators
   (6) Conditional operators
   (7) Bitwise operators
   (8) Special operators

(1) Arithmetic operators:  
All the basic arithmetic operations can be carried out in C. Both unary and binary operations are available in C language. Unary operations operate on a singe operand, therefore the number 5 when operated by unary – will have the value –5.

Operator

Meaning

+
Addition or Unary Plus
Subtraction or Unary Minus
*
Multiplication
/
Division
%
Returns remainder after division

 Examples of arithmetic operators are
Let x=10 and y=2
x + y =12
x - y = 8
(x*y)/2= 10
x%2 = 0
     Here  x, y are known as operands.
These operators are used in building the arithmetic expressions and relational
expressions as:

·         Root1 = ((-b)+(sqrt ((b*b)-(4*a*c)))/(2*a) ,
      Here right side arithmetic expression is evaluated and the result assigned      
      to the left side variable.
·         if((x%2)==0) 
           Here x%2 is evaluated and the result is compared with value 0
(2) Relational operators:
  Decision making is made by comparing two quantities. Comparisons can be done with the help of relational operators.


Operator

Meaning

<

is less than

<=
is less than or equal to

>

is greater than

>=
is greater than or equal to

==
is equal to

!=

is not equal to

A simple relational expression contains only one relational operator and takes the following form.
exp1 relational operator exp2
 

Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. exp1 is compared with exp2  then returns either true or false.
Given below is a list of examples of relational expressions and evaluated values.
6.5 <= 25 TRUE
-65 > 0 FALSE
10 < 7 + 5 TRUE
Relational expressions are used in decision making statements of C language such as if, while and for statements to decide the course of action of a running program.

(3) Logical operators:
  The  logical operators compares and evaluates by combining multiple relational expressions. C has the following logical operators;


Operator

Meaning

&&

Logical AND

||

Logical OR

!

Logical NOT



Logical AND (&&)
This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true.

Example:
a > b && x = = 10


The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10.

Logical OR (||)
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true.
Example:
a < m || a < n


The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n.
Logical NOT (!)
The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression.

For example:

! (x >= y)


the NOT expression evaluates to true only if the value of x is neither greater than or equal to y




4. Assignment Operators:

The Assignment Operator evaluates an expression on the right of the expression and assigns it to the variable on the left of the assignment operator.
 
SYNTAX:

var oper = exp;

Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper = is known as shorthand assignment operator
Example:
x + = 1 is same as x = x + 1


Example:
x = a + b
Here the value of a + b is evaluated and substituted to the variable x.

5. Increment and Decrement Operators (***)
The increment and decrement operators are one of the unary operators use to increment or decrement the value of the variable by 1. They are extensively used in for and while loops.
The syntax of the operators is given below
1. ++ variable name
2. Variable name++
3. – –variable name
4. Variable name– –

      The increment operator ++ adds the value 1 to the current value of operand and the decrement operator – – subtracts the value 1 from the current value of operand.
++variable name and variable name++ mean the same when they are used as  statements independently, but they behave differently when they are used in any expression.
Consider the following
m = 5;
y = ++m; (prefix)
In case of prefix operator first the value of m is incremented and then its value is assigned to y ie 6
Suppose if we rewrite the above statement as
m = 5;
y = m++; (post fix)
In case of postfix operator first the value of m is assigned to y ie. 5 then the value of m is incremented.

6. Conditional or Ternary Operator   (***)
The conditional operator is used to assign one of the two values based on the result of the condition . It consists of 2 symbols the question mark (?) and the colon (:)
The syntax for a ternary operator is as follows:
exp1 ? exp2 : exp3


The ternary operator works as follows:
exp1 is a relational expression and is evaluated first. If the expression is true then exp2 is evaluated & its value becomes the value of the expression and ignore exp3. If exp1 is false, exp3 is evaluated and its value becomes the value of the expression and ignores exp2 . Note that only one of the expressions is evaluated.
For example:
a = 10;
b = 15;
x = (a > b)? a: b
    Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is assigned to x.

7. Bitwise Operators
A bitwise operator operates on each bit of data. Those operators are used for testing, complementing or shifting bits to the right on left. Bitwise operators may not be applied to a float or double.

Operator

Meaning

&

Bitwise AND

|

Bitwise OR

^

Bitwise Exclusive

<< 

Shift left

>>

Shift right



8. Special Operators
C supports some special operators such as comma operator, size of operator, pointer operators (& and *) and member selection operators (. and ->).


19) Precedence of Arithmetic Operators

       An arithmetic expression without parentheses will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C;
                                     High priority   */%
                                     Low priority    +- 
The basic evaluation procedure includes ‘two’ left-to-right passes through the expression. During the first pass, the high priority operators (if any) are applied as they are encountered. During the second pass, the low priority operators (if any) are applied as they are encountered.
For Ex: x=a-b/3+c*2-1
            When a=9, b=12 and c=3, the statement becomes
           X=9-12/3+3*2-1
And is evaluated as follows
First pass:
Step1: x=9-4+3*2-1
Step2: x=9-4+6-1
Second pass:
Step3: x=5+6-1
Step4: x=11-1
Step5: x=10
    However, the order of evaluation can be changed by introducing parentheses into an expression
For Ex: 9-12/ (3+3)*(2-1)
           Whenever parentheses are used, the expression within parentheses assumes highest priority. If two or more sets of parentheses appear one after another, the expression contained in the left-most set is evaluated first and the right-most in the last.
First pass:
Step1: 9-12/6*(2-1)
Step2: 9-12/6*1
Second pass:
Step3:9-2*1
Step4: 9-2
Third pass:
Step5: 7

20) Mathematical functions:

Cmath declares a set of functions to compute common mathematical operations and transformations:

Trigonometric functions:
Compute cosine (function)
Compute sine (function)


Compute tangent (function)
Compute arc cosine (function)


Compute arc sine (function)
Compute arc tangent (function)


Compute arc tangent with two parameters (function)


Hyperbolic functions:
Compute hyperbolic cosine (function)
Compute hyperbolic sine (function)


Compute hyperbolic tangent (function)

Exponential and logarithmic functions:
Compute exponential function (function)
Compute natural logarithm (function)


Compute common logarithm (function)
Break into fractional and integral parts (function)


Power functions
Raise to power (function)
Compute square root (function)


Rounding, absolute value and remainder functions:
Round up value (function)
Compute absolute value (function)


Round down value (function)
Compute remainder of division (function)


Branching Statements :
The C language programs follows a sequential form of execution of statements. Many times it is required to alter the flow of the sequence of instructions. C language provides statements that can alter the flow of a sequence of instructions. These statements are called control statements. These statements help to jump from one part of the program to another. The control transfer may be conditional or unconditional.
Branching Statements are of following categories:
1. If Statement
2. The If else Statement
3.  Nested if Statement
4. The else if ladder
5. Switch Statement
6. goto statement

if Statement:

The simplest form of the control statement is the If statement. It is very frequently used in decision making and alter the flow of program execution.
The If structure has the following syntax

if (condition)
statement;


The statement is any valid C’ language statement and the condition is any valid C’ language expression, frequently logical operators are used in the condition statement. The condition part should not end with a semicolon. The command says if the condition is true then performs the following statement or If the condition is false the computer skips the statement and moves on to the next instruction in the program.
1.   void main ()
2.      {
3.        int numbers;  // declare the variables
4.        printf ("Type a number:");  
5.        scanf ("%d", &number);  // read the number from standard input
6.        if (number < 0)  // check whether the number is a negative no.
7.        number = -number;   // if it is -ve then convert it into +ve
8.        printf ("The absolute value is %d \n", number);  //
9.      }
The if-else construct:

Another form of the control statement is the if-else statement. It is very frequently used as two way  decision making and alter the flow of program execution to choose one among the two sets of statements.


The syntax of the If else construct is as follows:-
 If (condition)
  Statement 1;
else
  Statement 2; If the result of the condition is true, then program statement 1 is executed, otherwise program statement 2 will be executed. If any case either program statement 1 is executed or program statement 2 is executed but not both.
Example:
if (num < 0)   // check whether number is less than zero
    printf ("The number is negative");  
else  
       printf ("The number is positive");









Nested if Statement:

The if statement may itself contain another if statement is known as nested if statement.
Syntax:

if(condition1)
    {
  if(condition2)
      statement-1;
  else
      statement-2;
    }
else
 statement-3;








The if statement may be nested. One block of code will only be executed if two conditions are true. Condition 1 is tested first then condition 2 is tested. The second if condition is nested in the first. The second if condition is tested only when the first condition is true else the program flow will skip to the corresponding else statement.

Sample Code
1.        if (a > b)
2.           if (a > c)
3.               big = a;
4.           else
5.              big = c;
6.        else
7.              if (b > c)       
8.                big = b;
9.              else
10.                  big = c;
11.         printf ("Largest value %d”, big);   














The else -if Ladder:

When a series of many conditions have to be checked we may use the ladder else if statement which takes the following general form.

if (condition1)
   statement – 1;
else if (condition2)
   statement2;
else if (condition3)
   statement3;
else if (condition)
   statement n;
else
   default statement;
statement-x;


The conditions are evaluated from the top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement – x (skipping the rest of the ladder. When all the condition becomes false, the final else containing the default statement will be executed.







Sample Code :

1.   if (marks <= 100 && marks >= 70)
2.            printf ("\n Distinction");  
3.      else if (marks >= 60)
4.            printf("\n First class");
5.      else if (marks >= 50)
6.            printf ("\n second class");
7.      else if (marks >= 35)
8.            printf ("\n pass class");
9.      else
10.                printf ("Fail");












The Switch Statement:

The switch-case statement is a multi-way decision making statement. The switch statement allows a program to select one set of statements for execution out of a multiple alternative sets. During the execution of the switch statement only one of the possible sets of statements will be executed the remaining sets of statements will be skipped.
The value of the expressions in a switch-case statement must have to be an ordinal type i.e. integer, char, short, long, etc. Double and Float are not allowed.

The general format:
switch( expression )
{
case  case-label-value1: statements1;
[case  case-label-value2: statements2;]
[case  case-label-value3: statements3;]
[default : statements4;]
}


When the switch statement is executed the control expression is evaluated first and the value is compared with the case label values in the given order. If the label matches with the value of the expression then the control is transferred directly to the group of statements which follow the label. If none of the statements matches then the statement against the default is executed. The default statement is optional in switch statement in case if any default statement is not given and if none of the condition matches then no action takes place in this case the control transfers to the next statement of the switch statement.
Sample Code
1.      char operator
2.       ----
3.       switch (operator)
4.      {
5.          case '+':
6.             result = num1 + num2;
7.             break ;
8.          case '-':
9.             result = num1 - num2;
10.              break ;
11.           case '*':
12.              result = num1 * num2;
13.              break ;
14.           case '/':
15.              if (num2 != 0)
16.                 result = num1 / num2;
17.              else
18.              {        
19.                 printf ("warning : division by zero \n");
20.                 result = 0;
21.              }
22.              break ;
23.           default:
24.              printf ("\n unknown operator");
25.              result = 0;
26.              break ;
27.       }
28.       printf ("%d", result);
29.    }
In the above program the break statement is needed after the case statement to break out of the loop and prevent the program from executing other cases.

The GOTO statement:

The goto statement is simple statement used to transfer the program control unconditionally from one statement to another statement.


Syntax:


Forward  Branching:

goto label;
…………
…………
…………
Label;
………..;
      Backward Branching
    
     label;
     …………
     …………
     …………
     goto        
       label;
 




The goto requires a label in order to identify the place where the branch is to be made. A label is a valid variable name followed by a colon.
  The label: can be anywhere in the program either before or after the goto label; statement.

         main () //start of main
{
      int n, sum = 0, i = 0 ;
     printf ("Enter a number");
      scanf ("%d", &n) ;
     loop:
        i++ ;
       sum += i ;
      if (i < n) goto loop ;
      printf ("\n sum of %d natural numbers = %d", n, sum);
 }

 

During running of a program when a statement
                              if (i < n) goto loop;
the flow of control will jump to the statement immediately following the label loop:
     If the label: is before the statement goto label; a loop will be formed and some statements will be executed repeatedly. Such a jump is known as a backward jump. On the other hand, if the label is placed after the goto label; some statements will be skipped and the jump is known as a forward jump.
A goto  is often used at the end of a program to direct the control to go to the input statement, to read further data.

 

C Programming - Decision Making – Looping:

 

During looping a set of statements are executed until some conditions for termination of the loop is encountered. A program loop therefore consists of two segments one known as body of the loop and other is the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.

 

In general looping process would include the following four steps

1. Setting and initialization of a counter

2. Execution of the statements in the loop

3. Test condition for the execution of the loop to continue or terminate.

4. Incrementing the counter.

 

The While Statement:

 

The simplest of all looping structure in C is the while statement.

 

The general format of the while statement is:

 

while (test condition)

{

body of the loop;

}

 

Here the given test condition is evaluated and if the condition is true then the body of the loop is executed. After the execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process continues as long as the test condition is true once the condition is false the control is transferred out of the loop. On exit, the program continues with the statements immediately after the body of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contained two are more statements

 

Example:

 

void main()

{

  int  i=0;                //Declare and initialize the variables

  ----

     while(I < = 10)           // While statement with condition

         {

           printf(“\t%d”,I);

           I++;     //increment I to the next natural number.

         }

}

 

 

 

The Do while statement:

 

The do while loop is an alternative iterative structure. The do while loop tests at the end of the loop after executing the body of the loop. Since the body of the loop is executed first and then the loop condition is checked we can be assured that the body of the loop is executed at least once.

 

The syntax of the do while loop is:

 

Do

{

statement;

}

while(test condition);

 

Here the statements in the loop are executed, then test condition is evaluated. If the condition expression is true then the body is executed again and this process continues till the conditional expression becomes false. When the expression becomes false the loop terminates.

 

 

void main()

{

char inchar; // declaration of the character

    do            // start of the do loop

     {

      printf(“Input Y or N”);

      scanf(“%c”, &inchar);

     }

      while(inchar!=’y’ && inchar != ‘n’); // end of while loop

}

 

For Loop:

 

The for loop provides a more concise loop control structure. Unlike while and do-while the for loop header consists of three essential elements ie: initialization, test condition and increment. The general form of the for loop is:

 

for (initialization; test condition; increment)

{

body of the loop

}

 

When the control enters for loop the variable used in for loop is initialized with the starting value such as I=0,count=0. The value which was initialized is then checked with the given test condition. The test condition is a relational expression, such as I < 5 that checks whether the given condition is satisfied or not if the given condition is satisfied the control enters the body of the loop or else it will exit the loop. The body of the loop is entered only if the test condition is satisfied and after the completion of the execution of the loop the control is transferred back to the increment part of the loop. The control variable is incremented using an assignment statement such as I=I+1 or simply I++ and the new value of the control variable is again tested to check whether it satisfies the loop condition. If the value of the control variable satisfies then the body of the loop is again executed. The process goes on till the control variable fails to satisfy the condition.

 

For loop example program:

 

void main()

{

------

 

for (I = 0; I < 5; I++)

{

      -------

       if(num < 0)

         {

           printf(“You have entered a negative number”);

           continue;       // starts with the beginning of the loop

         }                  // end of if

       sum+=num;

 }                 //end of for loop

  ------

} // end of the program.

 

 


 

 

The Break Statement:

 

The break statement allows us to exit from inside the loop. A break statement provides an early exit from for, while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited immediately.

 

SYNTAX: break;

 

Example program to illustrate the use of break statement.

30.    char operator
31.        ----
32.        switch (operator)
33.       {
34.           case '+':
35.              result = num1 + num2;
36.              break ;
37.           case '-':
38.              result = num1 - num2;
39.              break ;
40.           
41.           default:
42.              printf ("\n unknown operator");
43.              result = 0;
44.              break ;
45.       }
46.       printf ("%d", result);

 

 

Continue statement:

 

During loop operations it may be necessary to skip a part of the body of the loop under certain conditions and begin the next iteration. The continue statement causes the loop to begin with the next iteration.

 

The format of the continue statement is simply:

 

Continue;

 

Consider the following program that finds the sum of five positive integers. If a negative number is entered, the sum is not performed since the remaining part of the loop is skipped using continue statement.

 

 

void main()

{

------

 

for (I = 0; I < 5; I++)

{

      -------

       if(num < 0)

         {

           printf(“You have entered a negative number”);

           continue;       // starts with the beginning of the loop

         }                  // end of if

       sum+=num;

 }                 //end of for loop

  ------

} // end of the program.