Wednesday, October 29, 2014

4.1.1 ARRAYS - INTRODUCTION

Why arrays?
 
The fundamental data types namely char, int, float are constrained by the fact that a variable of these types can store only one value at any given time. In order to handle a large volume of data in terms of reading, processing and printing we need a derived data type known as array.
 
Def:
An array is a fixed-size sequenced collection of elements of the same data type.
 
Examples where the concept of an array can be used:
·         List of temperatures recorded every hour in a day, or a month, or a year.
·         List of employees in an organization.
·         List of products and their cost sold by a store.
·         Test scores of a class of students.
 
For instance, we can use an array name salary to represent a set of salaries of a group of employees in an organization. We can refer to the individual salaries by writing a number called index or subscript in brackets after the array name.
e.g. salary[10]
      represents the salary of 10th employee
 
The ability to use a single name to represent a collection of items and to refer to an item by specifying the item number enables us to develop concise and efficient programs.
 
We can use arrays to represent not only simple lists of values but also tables of data in two, three or more dimensions. We have the following types of arrays:
·         One-dimensional array
·         Two- dimensional array
·         Multi- dimensional array
 
Advantages and Disadvantages of Array
Advantages
1)      It is used to represent multiple data items of same type by using only single name.
2)      It can be used to implement other data structures like linked list, stacks, queues, trees, graphs, etc.
3)      2D arrays are used to represent matrices.
4)      The elements of arrays are stored in consecutive memory locations so searching an element is easy.
 
Disadvantages
1)      We must know in advance that how many elements are to be stored in array.
2)      Array is static structure. It means that array is of fixed size. The memory which is allocated to array can not be increased or decreased.
3)      Since array is of fixed size, if we allocate more memory than requirement then the memory space will be wasted. And if we allocate less memory than requirement, then it can create problem.
4)      As the elements are stored in consecutive memory locations so insertions and deletions are very difficult and time consuming.

Friday, October 3, 2014

3.1b DECISION MAKING & LOOPING

 
§  In looping, a sequence of statements are executed until some conditions for termination of the loop are satisfied.
§  A program loop consists of two segments, one known as the body of the loop and the other known as the control statement.
§  The control statement tests certain conditions and then directs the repeated execution of the statements contained in body of the loop.
§  Depending on the position of the control statement in the loop, a control structure may be classified either as the entry-controlled loop or as the exit controlled loop.

 

The C language provides for three constructs for performing loop operations. They are:
1.      the while statement
2.      the do statement
3.      the for statement

Categories of Loops
Based on the nature of control variable and the kind of value assigned to it for testing the control expression, the loops may be classified into two general categories:
a)      Counter-controlled Loops
§  When we know in advance exactly how many times the loop will be executed, we use a counter-controlled loop.
§  A control variable counter is used which is initialized, tested and updated properly for the desired loop operations.
§  The number of times we want to execute the loop may be a constant or a variable that is assigned a value.
§  A counter-controlled loop is also called definite repetition loop.

b)     Sentinel-controlled Loops
§  In a sentinel-controlled loop, a special value called a sentinel value is used to change the loop control expression from true to false.
§  The control variable is called sentinel variable.
§  A sentinel-controlled loop is also called indefinite repetition loop because the number of repetitions is not known before the loop begins executing.

All the three constructs (while, do, for) have three phases, namely:
        i.            Initialization
      ii.            Testing
    iii.            Incrementing / decrementing

 
WHILE STATEMENT
§  Basic format:
initialization;
while (test-condition)
{
            body_of_the_loop;
            increment/decrement;
}
 
§  Flowchart:

§  The ‘while’ is an entry-controlled loop statement.
§  The test-condition is evaluated and if the condition is true, then the body of the loop is executed.
§  This process is repeated until the test-condition becomes false and the control is transferred out of the loop.

NOTE: The body of the loop may not be executed at all if the condition is not satisfied at the very first attempt.

§  Sample Code:
sum = 0;                                 
n = 1;                                       /*Intialization*/
while (n <= 10)                       /*Testing*/
{
            sum = sum + n;
            n = n + 1;                     /*Increment/decrement*/
}
printf(“%d”, sum);

DO STATEMENT
§  Basic format:
initialization;
do
{
            body_of_the_loop;
            increment/ddecrement;
} while (test-condition);
 
§  Flowchart:

§  On reaching the do statement, the program proceeds to evaluate the body of the loop first.
§  The test-condition in the while statement is evaluated at the end of the loop.
§  If the condition is true, the program continues to evaluate the body of loop once again.
§  When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the ‘while’ statement.

NOTE: Since the test-condition is evaluated at the bottom of the loop, the do-while construct provides an exit-controlled loop and therefore the body of the loop is always executed at least once.

§  Sample Code:
sum = 0;                                 
n = 1;                                       /*Intialization*/
do                                           
{
            sum = sum + n;
            n = n + 1;                     /*Increment/decrement*/
} while (n <= 10);                   /*Testing*/
printf(“%d”, sum);

Difference between the working of ‘while’ and ‘do-while’ loop
void main()
{
           int c  = 5;
           while (c < 5)
           {
                      printf (“Hello”);
                      c = c + 1;
           }
}
void main()
{
           int c  = 5;
           do
           {
                      printf (“Hello”);
                      c = c + 1;
           } while (c < 5);
}
Output:
The program will print nothing.
Output:
Hello


FOR STATEMENT
§  Basic format:
for (initialization; test-condition; increment/decrement)
{
            body_of_the_loop;
}
 
§  Flowchart:
 
§  The ‘for’ loop is an entry-controlled loop statement.
§  Initialization of the control variables is done first, using the assignment statement.
§  The value of the control variable is tested using the test-condition. If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.
§  When the body of the loop is executed, the control is transferred back to the ‘for’ statement after evaluating the last statement in the loop.
The control variable is incremented/decremented and is again tested to see whether it satisfies the loop condition.

§  Sample Code:
sum = 0;
for (n = 1; n <= 10; n++)
{
            sum = sum + n;
}
printf(“%d”, sum);

NESTING OF ‘FOR’ LOOP
§  Nesting of loops, that is, one for statement within another for statement, is allowed in C.
§  Sample code:
for (i = 1; i <= 5; i++)
{
            for (j = 1; j <= i; j++)
            {
                        printf(“*”);
            }
            printf(“\n”);
}
 
                  Output:

                 *
                 **
                 ***
                 ****
                 *****

 
BREAK & CONTINUE STATEMENT

1.      Jumping out of a loop – break statement
§  An early exit from a loop can be accomplished by using the break statement or goto statement.
§  while Statement

§  do-while Statement

§  for Statement

§  nested for Statement
 


NOTE: when a break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop.
When the loops are nested, the break would only exit from the loop containing it.

§  Sample Code:
                        void main()
                        {
                                    int i;
                                    for (i = 1; i <= 10; i++)
                                    {
                                                if (i = = 5)
                                                    break;
                                                else
                                                    printf(“%d”, i);
                                    }
                                    printf(“Hello”);
                        }
 
                        Output:
                        1 2 3 4 Hello

2.      Skipping a part of a loop – continue statement
§  The continue statement tells the compiler to skip the following statements and continue with the next iteration.
§  while Statement

§  do Statement

§  for Statement

§  Sample Code:
void main()
{
            int i, j;
            for (i = 1; i <= 3; i++)
            {
                        for (j = 1, j <= 3; j++)
                        {
                                    if (i != j)
                                        continue;
                                    printf(“\n%d%d”, i, j);
                        }
            }
}
 
Output:
1 1
2 2
3 3

Difference between break and continue statement
Break
Continue
It helps to make an earlier exit from the block where it appears.
It helps in avoiding the remaining statements in a current iteration of the loop and continuing with the next iteration.
It can be used in all control statements including switch construct.
It can be used only in loop constructs.

 
SELECTING A LOOP
Given a problem, the programmer’s first concern is to decide the type of loop structure to be used. To choose one of the three loops supported by C, we may use the following strategy:
v  Analyse the problem and see whether it requires a pre-test or post-test loop.
v  If it requires a post-test loop, then we can use only one loop, do-while.
v  If it requires a pre-test loop, then we have two choices – for & while.
v  Decide whether the loop termination requires counter-based control or sentinel-based control.
v  Use ‘for’ loop if the counter-based control is necessary.
v  Use ‘while’ loop if the sentinel-based control is required.

COMPARISION BETWEEN A PRE-TEST AND POST-TEST LOOP
 
PRE-TEST LOOP
POST-TEST LOOP
Initialization
once
once
Number of tests
n + 1
n
Actions executed
n
n
Updating executed
n
n
Minimum iteration
not even once
at least once
Constructs
while, for
do