-->

Tuesday, February 10, 2015

Jump Statement used in Computer Programming, C Language

After discussing about looping statements in computer programming, programmer should know about jump statements. These statements are used to jump forward/backward, on a given condition. This article will give you a brief overview in c language.

Sometimes, during the execution of a loop it may be desirable to skip execution of some statements or leave the loop when a certain condition occur. For example, during searching process, if the desired item found then there is no need to search further. In such cases, we have to terminate the loop using jump. The various jumps in loops are as follows:


Jump Statement used in Computer Programming, C Language

goto statement

goto statement is a jump statement that transfers the control of the specified statement in a program. This is an unconditional branch statement. The specified statement is identified by a symbolic name (any identifier) ending with colon ':'.
Syntax:
    goto label:
Where
  • goto – is a reserve word or keyword
  • label – is an identifier ending with colon ‘:’
Disadvantages:
  • Using goto statement in a program is an unstructured programming style.
  • The unstructured program written using goto statement are very difficult to read and understand.
  • It is also very difficult to debug the program.
Example: A C program to add all the natural numbers using goto statement.
main()
{
  int n,i,sum;
  clrscr();
  printf(“Enter the number od terms:”);
  scanf(“%d”,&n);
  sum=i=0;
  top:    sum=sum+i;
    i=i+1;
    if(i<=n) goto top;
    printf(“Sum of series = %d”,sum);
  getch();
}


Jump Statement used in Computer Programming, C Language output

Break Statement

The break statement is another jump statement which is frequently used in switch statement and loops. The break statement works as follows:
  • The 'break' statement is part of switch statement causes control to exit the switch statement. Usually, in any case, the break statement will be the last statement.
  • If break is executed in any type of loop like for, while or do-while, the control comes out of the loop and the statement following the loop will be executed. The break statement is used mainly to terminate the loop when a specific condition is reached.
Note: If ‘break’ appears in the inner loop of a nested loop, control only comes out of the inner loop.
Consider the following program segment:
    i = 1;
    for(; ; )
    {
      if(i==5) break;
      printf(“%d”,i++);
    }
In the given for loop, there is no initialization, condition and re-initialization part. Such loop is called as infinite loop. Even though it appears as an infinite loop, as the value of i reaches to 5, the control immediately comes out of the loop. When the value of i is compared with 5, the break statement is executed and the control immediately comes out of the loop.

Continue statement:

The continue statement is used only in the loops to terminate the current iteration. During execution of a loop, it may be necessary to skip a part of the loop based on some condition e.g. during processing of student records, it may be necessary to exclude student names whose marks are less than or equal to 35. In such case, a test is made to see whether the marks scored are less than or equal to 35. If so, the part of the program that processes the student details can be skipped using continue. 

But, the execution continues with next iteration of the loop. In the while statement and do-while statement, whenever a continue statement is executed, the rest of the statements within the body of the loop are skipped and the conditional expression (conditional statement) is executed. But, in for loop, the updating statement will be executed. For example, consider the statements shown below:
    for(i=1;i<=5;i++)
    {
      if(i==2) continue;
      printf(“%d”,i);
    }
Note that when i takes the value 2, the continue statement is executed and the statements following continue are skipped. The control is transferred to updating i.e. i++ statement and the execution continues from that point. The output of this program is 1 3 4 5.

Difference between break and continue statement


Difference between jump statements in computer programming

Array in Computer Programming

How to use ASP.NET validator control with example

INTRODUCTION
ASP.NET validator are controls used for validating the data entered in an input control , such as the textbox of a Web page.When a user enters invalid data in an associated control, the ASP.NET validator  control displays an error message on the screen. The error message is defined as a property value of the validation control . The data being entered is validated each time it is entered by the user , and the error message disappears only when the data is valid. Validation controls help save time and enhance the efficiency of the application by validating the data before a request is sent to the server.
The BaseValidator class
The System.Web.UI.WebControls.BaseValidator class provides basic implementation required for all validation controls.


Public Properties of the BaseValidator Class

ControlToValidate : Handles an input control, such as the TextBox Control , which needs to be validated.

Display : Handles the behavior of the error message in a validation control.

EnableClientScript : Handles a value indicating whether or not client-side validation is enabled

Enabled : Handles a value that indicates whether or not the validation control is enabled or not.

ErrorMessage : Handles the text for the error message displayed in a ValidationSummary control when validation fails.

ForeColor : Handles the color of the messgage displayed when validation fails.

IsValid : Handles a value that indicates if the focus is set on the control or not , specified by the ControlToValidate property when validation fails.

Text : Handles the text displayed in the validation control when the validation fails.

ValidationGroup : Handles the name of the validation group to which this validation control belongs.

Note: ValidationGroup property , when set, validates only the validation controls within the specified group when the control is posted back to the server.

Public Methods of the BaseValidator Class

validate() : Helps in performing validation on the associated input control and update the IsValid property

GetValidationProperty : Help in determining the validation property of a control , if it exists.

The following ASP.NET validator controls are

Sunday, February 8, 2015

C Language: How to Store Multiple values in Array

One data item can only be stored in one variable, in the context of computer programming. If programmer want to store more information in the memory, he/she should have more variables. Programmer can choose another option that is an Array.

Suppose that a student has scored 90 marks. These marks can be stored in a variable in c programming language as shown below:
int marks=90;

After executing this statement, the value 90 will be stored in the variable marks. Suppose there programmer needs to store marks of 10 students. In such case, we have to use 10 variables like marks1, marks2, marks3, …, marks10. But, if it is required to store the marks of 100 students, definitely it is not feasible to use 100 variables marks1, marks2, marks3, …, marks100. In mathematics, we use sets to group the items of similar kind. For example, consider the set shown below:

Marks = {75, 76, 78, 79, 86, 56, 98, 89, 56, 89}

This is a set of 10 students. Note that every item can be accessed by prefixing marks along with the position of marks in the sheet. The first item 75 corresponds to the marks of first student, 76 corresponds to the marks of second student and so on i.e., marks1=75, marks2=76, marks3=78, ….., marks10=89. In C language, this is where; the concept of arrays is used. Since all the marks are of the same type, we can group and refer all the marks with a common name using arrays.

An array is defined as an ordered set of similar data items. All the data items of an array are stored in consecutive memory locations in main memory. The elements of an array are of same data type and each item can be accessed using the same name. e.g., consider an array of marks of 5 students as shown below:

How to Store Multiple values in Computer Programming: Array

To refer an item in the array, we specify the name of the array along with position of the item. The position of the item must be written within square brackets '[ ]'. The position of the item enclosed within square brackets is called 'subscript' or 'index'. For example, the above figure represents an integer array called marks where marks of 5 students are stored. The marks of each student can be accessed as shown below:

  • Marks[0] i.e. 75 – represents marks of first student
  • Marks[0] i.e. 76 – represents marks of second student
  • Marks[0] i.e. 78 – represents marks of third student
  • Marks[0] i.e. 79 – represents marks of fourth student
  • Marks[0] i.e. 86 – represents marks of fifth student

Note: Using Marks[0] through Marks[n-1] we can access the marks of n students in general.

In an array it is not possible to have a group of items with different data types. For example,

How to Store Multiple values in Computer Programming: Array

This is an invalid way of storing the elements in an array. This is because, it is a collection of multiple datatypes, so we have to classify the array. The classification will be done in next article.

Implementation of STACK using Linked List in C language

Implementation of STACK using Linked List

             To implement the STACK using Linked List, the Linked List itself is created in different manner. In this case instead of ROOT in normal Linked List, an external pointer TOP is used to point all the time to the just added node.
      Initially when the STACK is empty TOP points to a NULL address.

When the PUSH operation is to be done, a NEW node is created and TOP is made point to it. Suppose for the first time one PUSH operation is done. The linked list is shown below:

When again another ITEM is PUSHed, a NEW node is created and the address of the node pointer by TOP, is copied in the LINK field of NEW node the TOP is made point to the NEW node. The Linked List is as below:
When again another item is to be PUSHed it is done similarly. After the PUSH of one more ITEM the Linked List is as shown below:
So, the Linked List created as STACK can be graphically shown as below:
While deletion, POPping is to be done from the STACK, TOP is checked. If it is NULL then the STACK is empty and ‘underflow’ occurs otherwise the ITEM of the node pointed by TOP can be copied in a variable and TOP is updated by link of TOP. Then ITEM is returned.
                      In the above-created STACK, if the POP operation is done once, the Linked List can be shown as below:







Standard streams in C language

A stream is nothing but a collection or sequence of bytes that is moved from main memory and I/O devices. The standard streams in ‘C’ are predefined streams. They are automatically opened whenever the program is executed. When the “main()” function of a C program is invoked, it already has predefined streams open and available for use. Two of these streams represent the standard input and output channels that will be opened for the transfer of data in the form of bytes. These streams are declared in the header file ‘stdio.h’. in total there are FIVE standard streams available, which are:

stdin : the standard input stream, which is the normal source of input for the program. The stream of data is transferred from standard input device like ‘keyboard’ to main memory referred in the form of variables.

stdout :  the standard output stream, which is used for normal output from the program. The stream of data is transferred from main memory referred in the form of variables to the output device like ‘monitor’.

stderr:  the standard error stream, which is used to output error messages and diagnostics from the program.

stdaux : the standard auxiliary device stream, which is used for the connected secondary devices.

stdprn : the standard printer stream, which is used for printing the data in the form hard copy from the program. The data is printed on die attached printer.

In the GNU system the shell provides the pipe and redirection facilities. With the help of these facilities the streams using the files and processes are specified. Most of the other operating systems also provide the similar mechanisms, but the details of usage may vary.

In the GNU C library, ' stdin', ‘stdout', and ' stderr' are normal variables which you can set just like others. For example, to redirect the standard output to a file, you could do:

fclose (stdout);

stdout = fopen (“output_file”, “w”);

Note however that in other systems ' stdin', ‘stdout', and ' stderr' are macros and cannot be assigned to any file in the normal way. But the function ' freopen ()' can be used to get the of closing one file and reopening another file.

C language: Implementation of STACK Using one-dimensional ARRAY

To implement the STACK, a simple one-dimensional array can be used. The size the array is the size of the STACK. Instead of using the normal index to access the elements of the array a special index TOP is used to access the individual elements of the array. Initially TOP is stored with 0, considering the lower bound of array as 1. If the lower bound of the array is other than 1, suppose say LB, then LB-1, may be used as TOP value. STACK may be treated as name of the array.

           If any insertion, PUSH is to be done on the STACK, TOP is incremented by one and the element is stored at TOP i.e. TOP<--TOP+1 and STACK [TOP]<--ITEM, ITEM is the item to be inserted by 1 and the ITEM is placed at TOP. While PUSHing the ITEM the TOP is checked for size, if the TOP is equal to the STACK size N, then no more PUSH operations are possible, the STACK is full. The ‘overflow’ occurs.
  If any deletion, POP, is to be done from the STACK, the item pointed by TOP is stored in a variable, and the TOP is decremented by 1 and the variable is returned. Similarly further POP operations are done. While POPping the STACK is empty and ‘underflow’, occurs.

                To implement the STACK using one-dimensional array the following PUSH and POP operations’ algorithms are used.

Algorithm for PUSH:

           PUSH (STACK,TOP,N,ITEM)
           [STACK is name of the array, ITEM is the data to be PUSHed, TOP is the current index of                        STACK and N is the size of STACK]
           If TOP=N Then;
            write: ’Overflow’; Exit.
           [End of If]
           TOP<--TOP+1
           STACK[TOP]<--ITEM
           Exit.

Function in C to implement PUSH operation:

    void push (int stack[],int n,int *top, int item)
    {
      if(top= =n-1)
       {
         printf(“Over flow”); exit(0);
        }
     top++; stack[top]=item;
    }

Algorithm for POP operation:

     POP (STACK, TOP)
     [STACK is name of the array and TOP is the current index]
     If TOP=O Then;
      Write: ’Underflow’; Exit.
     [End of If]
     ITEM<--STACK[TOP]
     TOP<--TOP-1
     Return ITEM
     Exit.

Function in C to implement POP operation:

     int pop (int stack[], int *top)
     {
       int item;
       if(top= =1)
         {
           printf(“Under flow”);
           exit(0);
           }
       item=stack[top];
       top--;
       return item;
     }

Opening and closing a file in C language

Opening a file

As discussed earlier whenever the file manipulation is to be performed the logical file is attached to the physical file. It means the file pointer holds the address of physical file. This can be achieved by means of opening a file. This operation is also called as linking a logical file with physical file. The fopen() function is used to link the logical file with that of physical file.

The file is opened to perform read/write operations on it and it is promptly closed to indicate the completion of the desired read/write operations.

The syntax of the function fopen() is as follows:

filepointervariable = fopen(“physicalfilename”,”openingmode”);

Here, filepointervariable represents a pointer variable of FILE data type. Physicalfilename represents a name of the  physical file (a string variable or constant). Openingmode represents one of the available modes (a string constant).
The filepointervariable may be any of the file pointers as discussed in the earlier article. The physicalfilename is a string constant or a variable used to represent name of the physical file. The file may be an existing one or a new one that is to be created. The write operations can be performed on any new file and both read/write operations can be performed on an existing file. The openingmode is also a string constant that indicates the operations to be performed on new or existing file.

The following table provides the list of file opening modes available which are used as string constants like “m” where m is the mode:
table provides the list of file opening modes

The Following table provides the "flags" of the streams (which are defined in FILE structure)
table provides the "flags" of the streams

Consider the following declaration and file opening statement:
 FILE *fpl;

fpl=fopen(“physicalfilename”,”openingmode”);

The fopen() function links the logical file ‘fpl’ with the physical file ‘physicalfilename’. The 'openingmode’ indicates the operation mode as per the table shown above. One of them is selected as per the requirements. If the file is created for the first time then either “w” or “a” can be selected. When the data to be transferred is in binary format the mode “wb” or “ab” can be selected.

 The header file ’stdio.h’ contains declarations for the file I/O and should always be included at the very beginning of C programs that use ‘data files’. The constants such as EOF, NULL, etc. are also defined in ’stdio.h’. If the physical file mentioned is successfully opened then the logical file is linked with it otherwise the function fopen() returns NULL. This NULL value helps in testing the successful  opening of any physical file for the respective operation. In case of failure to open the file, proper error message can be displayed indicating “file opening error” may be along with the filename.

Consider another statement like: fp = fopen(“prog.c”, “r”);

Here “prog.c” is the physical file that is opened. It is opened in ‘read’ mode. So, the above statement opens a file called “prog.c” (a physical file) for reading and associates the file pointer fp(logical file) with it. Note here that the file opened is a text file. If the file “prog.c” exists then it is  successfully opened and a valid address is stored in “fp” otherwise a NULL is stored in the file pointer “fp”. In such case an error can he reported like:
if(fp = NULL)

{

printf(“Error in opening the file..");
 exit(l);

}

If “emp.dat” file is to be created for the first time and the data is to be written in binary format then the statement used to do so is:
 fp = fopen( “emp.dat”, “wb”) ;

By chance if the file “emp.dat” already exists then the contents of it are erased and the new data is transferred after every write operation. To retain the data and write the data at the end the file opening mode is changed like:

fp = fopen( “emp.dat”, “ab”) ;

Once the file is open in the respective mode then it is ready for either input (read) or output (write) or append (write at the end) operation.

Closing a file


As discussed earlier the file is opened for input or output operations. After either of the operations it is required to close the opened file to ensure the detachment of physical file. Of course this detachment is done automatically by the system when the program execution is over. To ensure the completeness of the program every programmer must close the opened file in the file handling programs. In order to reuse the file pointer variable declared, to open another file, it is must to close the earlier physical file that is already attached. The closing of file is basically related to closing the logical file that indirectly closes the physical file for I/O operations.

To close a file simply the function fclose(filepointer) is used with the file pointer as the parameter to close a single file. If more than one files are to be closed at a time then the function fcloseall() is used without any parameters.

You can open a file for writing, close it, and reopen it for reading, then close it, and open it again for appending, etc. Each time you open it, you could use the same file pointer. Of course it is the better way of using same file pointer all the time. If more than one file is simultaneously to be operated then different file pointers are required. The file pointer is simply a tool that you use to point to a file and you decide what file it will point to.

The following statements show the usage of the functions used for closing the files:
 FILE *fpl;

fp 1 =fopen(“emp.dat”,”w”); /* the logical file fpl linked to physical file emp.dat in WRITE mode */
................
 /* Write operations on the file*/
 ................

fclose(fpl); /* The file is closed */
 fpl=fopen(“trans.dat”,”r”); /* the logical file fpl linked to physical file trans.dat in READ mode */
 .....................
/* Read operations on the file*/
......................
fclose(fpl); /* The file is closed */

In the above description the logical file fpl is closed before linking it with another physical file.

In the next description more than one file pointer usage and fcloseall() to close all the opened files simultaneously can be observed.

 FILE *fpl, *fp2, *fp3;

fp1 =fopen(“emp.dat”,”a”); /* the logical file fpl linked to physical file emp.dat in APPEND mode*/
fp2=fopen(“transl.dat”,”r”); /* the logical file fp2 linked to physical file transl.dat in READ mode*/
fp3=fopen(“trans2.daf","r”); /* the logical file fp3 linked to physical file trans2.dat in READ mode*/
....................

/* Simultaneously Read operations on the files fp2 and fp3 and Write operations on the file fp4 */
....................

fcloseall(); /* all the three files are closed at a time */

The observation from above two descriptions provide the usage of the parameter in flcose() and non-usage in fcloseall().
© Copyright 2013 Computer Programming | All Right Reserved