Tampilkan postingan dengan label C. Tampilkan semua postingan
Tampilkan postingan dengan label C. Tampilkan semua postingan

Selasa, 24 Desember 2013

Bubble Sort Algorithm in Computer Programming: C

More often in computer programming, programmers works with large amount of data and it may be necessary to arrange them in ascending or descending order. This process of arranging the given elements in a order is called sorting, the order may be ascending or descending.

For example, consider the unsorted elements:
10, 60, 50, 20, 30, 70, 40
After arranging them in ascending order, the elements are rearranged as shown below:
10, 20, 30, 40, 50, 60, 70
After arranging them in descending order, the elements are rearranged as shown below:
70, 60, 50, 40, 30, 20, 10

The two important and simple sorting techniques are described below with example:

Bubble sort

This is the simplest and easiest sorting technique. In this technique, the two successive items or elements arr[i] and arr[i+1] are exchanged whenever the condition arr[i]>arr[i+1] will be true. For example, consider the elements shown below:

Bubble Sort Algorithm in Computer Programming: C

In the first pass 50 is compared with 40 and they are exchanged since 50 is greater than 40. Next 50 is compared with 30 and they are exchanged since 50 is greater than 30. If we proceed in the same manner, at the end of the first pass the largest item occupies the last position. On each successive pass, the items with the next largest value will be moves to the bottom and thus elements are arranged in ascending order.

Note: Observe that after each pass, the larger values sink to the bottom or next position of the array and hence it is also called sinking sort. The following figure shows the output of each pass:

Bubble Sort Algorithm in Computer Programming: C

Note: Observe that at the end of each pass, smaller values gradually "bubble" up to the top (like air bubble moving to surface of water). So, this sorting technique is called bubble sort.

The comparisons that are performed in each pass are as follows:

In general, we can say i = 0 to n-(j+1) or i=0 to n-j-1. Here, j=1 to 4 represent pass numbers. In general j=1 to n-1. So, the partial code can be written as follows:
for(j=1; j<n; j++)
{
  for(i=0; i<n-j; i++)
   {
     if(arr[i]>arr[i+1])
     {
       exchange (arr[i], arr[i+1])
      }
   }
}

Algorithm

Step 1:    [Input number of items]
Read: n
Step 2:    [Read n items]
    for I = 0 to n-1
        Read: arr[i]
    [End of for]
Step 3:    for j = 1 to n-1 do
          for i = 0 to n-j do
        if(arr[i] >= arr[i+1])
             temp = arr[i]
             arr[i] = arr[i+1]
             arr[i+1] = temp
        [End of if]
          [End of for]
    [End of for]
Step 4:    for i = 0 to n-1
          Write: arr[i]
    [End of for]
Step 5:    Exit

C Program.

main()
{
 int n,i,j,temp,arr[10];
 clrscr();
printf("Enter the number of items:");
scanf("%d",&n);
printf("Enter the items:");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(j=0;j<n;j++)
{
 for(i=0;i<n-j;i++)
{
 if(arr[i]>=arr[i+1])
{
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
printf("The sorted items are:\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
getch();
}

Bubble Sort Algorithm in Computer Programming: C

Advantages

  • Very simple and easy to program
  • Straight forward and approach

Disadvantages

  • It runs slowly and hence it is not efficient. More efficient sorting techniques are present.
  • Even if the elements are sorted, n-1 passes are required to sort.


Selection Sort in C

What is Variable Length String Format in Computer Programming: C Language

As the name implies, variable–length strings don’t have a pre-defined length. In this string, neither the precise length nor maximum length is known at the time of creating it. The array storage structure for a string can expand or shrink to accommodate any number of characters. But, there should be a mechanism to indicate the end of the string. The two common techniques to implement variable length strings are described in the article.

Length Controlled String

A length controlled string is a string whose length is stored as part of the string itself. This technique uses a count that specifies string length. The count is normally stored as the first byte followed by the string. This count is used by the string manipulation functions to determine the actual length of the string data.
For example, the strings "DOT" and "PROGRAM" are stored using length controlled format are:

What is Varaible Length String Format in Computer Programming: C Language

Note: The first byte contains string length. Since its length is 1 byte (* bits) w can have a string length whose range is from 0 to 255. So, the string length should not exceed 255 characters.

The disadvantages can be overcome using delimited string. As we use various delimiters such as semicolons, colon, comma, period (.), in a sentence in English, the string can also be ended with delimiters.

Delimited String

In a variable length string, the string ends with a delimiter NULL (denoted by '0') character. This string which ends with a delimiter denoting the end of the string is called delimited string.

For example, the string "DOT" and "PROGRAM" are stored using a delimiter as shown here.

What is Varaible Length String Format in Computer Programming: C Language



String Literals and Constants in Computer Programming: C Language

There is no separate data type for strings in C language. In C language, a string is an array of characters and terminated by NULL character which is denoted by the escape sequence '0'. A NULL terminated string is the only type string defined using C language.

A string is stored as a sequence of characters in an array terminated by \0. For example, consider the string "DOTPROGRAMMING". This string is stored in the form of an array as shown below:

String Literals and Constants in Computer Programming: C Language
Note that the characters are stored from location zero. Each location holds one character string from 0 to 14. The string always ends with NULL. Character denoted by '\0'. Here, the string "DOTPROGRAMING" is called a string literal.

String Literal or Constant

A string literal or constant is a sequence of characters enclosed within double quotes. For example, "DOT PROGRAMMING", "DOT", "PROGRAMMING" are all string literals. When a string literal is defined, the C compiler does the following activities:

  • The compiler creates an array of characters.
  • Initializes each location of array with the characters specified within double quotes in sequence.
  • Null-terminates the string that is appends ‘\0’ at the end of the string. This is done by the compiler automatically.
  • Stores the starting address of the string constant that can be used later. For example, the literals "DOT", and "PROGRAM" can be stored in the memory as shown below:

String Literals and Constants in Computer Programming: C Language

Referencing String Literal or Constant

An array of integers is stored in contiguous memory locations, it is clear from the above figures that a string literal is also stored in memory contiguously one after the other. So, each character of the literal or constant can be accessed using index (array or pointer concept can be used). For example, consider the following program:

main()
{
clrscr();
printf("5c","DOT"[0]);
printf("5c","DOT"[1]);
printf("5c","DOT"[2]);
getch();
 }

The entire string can be referred and display as shown below:

main()
{
clrscr();
printf("DOT");
getch();
 }

Each of the above program will outputs "DOT" string on the monitor or any output device connected with the PC.

Jumat, 20 Desember 2013

About and Uses of String Data Types in Computer Programming: C

String is a data type and is often used as an array of bytes that stores a sequence of elements i.e. characters, in computer programming. C language supports string in every calculation of programming, the article describes the use with examples.

No program generally exists without the manipulation of the strings. In all our previous articles, we have used several times the statements:
pritnf("Enter the number of n");

Here, the sequence of characters enclosed within a pair of double quotes is a string. Strings are generally used to store and manipulate data in text form like words or sentences.

Definition: An array (or sequence) of characters is called as string. A string is most conveniently represented using continuous storage locations in memory. The storage representations of strings are classified as shown below:

Fixed length Format:

A fixed length string is a string whose storage requirement is "known when the string is created". In this string, irrespective number of characters the string has, the length of the string is always fixed. Once the string is defined, the length of a string cannot be changed. It is ‘fixed’ for the duration of program execution. In this format, the non-data characters such as space are added at the end of the data.

For example, the string "DOT" and "PROGRAM" are stored in fixed format where size is fixed for 10 bytes as shown below:


Note: The string "DOT" is 10 bytes string ending with 7 blanks characters.
Note: The string "PROGRAM" is 10 bytes string ending with 3 blanks characters.
Note: The blank characters cannot be used as data since it acts as end of the string.

Disadvantages
  • If the length reserved for string is too small, it is not possible to store the large string.
  • If the length reserved for string is too large, too much memory is wasted.
  • Once the string is defined, the length of a string cannot be changed. It id ‘fixed’ for the duration of program execution.
  • There is the problem of distinguishing data character from non-data characters. Normally non-data character such as spaces are added at the end of the data.
The above disadvantages can be overcome using variable length format, will be discussed in later article.

String literals and constants

Selection Sorting Algorithm in Computer Programming: C

Selection sort, also called in-place comparison sort, is a sorting algorithm in computer programming. It is well-known algorithm for its simplicity and also performance advantages. The article shows the process with C language code and an example.

As the name indicates, first we select the smallest item in the list and exchange it with the first item. Then we select the second smallest in the list and exchange it with the second element and so on. Finally, all the items will be arranged in ascending order. Since, the next least item is selected and exchanged accordingly so that elements are finally sorted, this technique is called selection sort.

For example, consider the elements 50, 40, 30, 20, 10 and sort using selection sort.

Selection Sorting Algorithm in Computer Programming: C

Design: The position of smallest element from i'th position onwards can be obtained using the following code:

pos = i;
for(j=i+1; j<n; j++)
{
   If(arr[j] < arr[pos])
   pos = j;
}

After finding the position of the smallest number, it should be exchanged with i'th position. The equivalent statements are shown below:

temp = arr[pos];
arr[pos] = arr[i];
arr[i] = temp;

The above procedure has to be performed for each value of i in the range 0 < i < n-1. The equivalent algorithm to sort N elements using selection sort is shown below:

Step1:    [Input the number of items]
    Read: n
Step2:    [Read n elements]
    for i = 0 to n-1
        Read: arr[i]
    [End of for]
Step3:    for i = 0 to n - 2  do
        pos = i;
        for j = I + 1 to n – 1 do
            if(arr[j] < arr[pos]) then
                pos = j
            [End of if]
        [End of for]
        temp = arr[pos]
        arr[pos] = arr[i]
        arr[i] = temp
    [End of for]
Step4:    [Display Sorted items]
    for i = 0 to n -1
        Write: arr[i]
    [End of for]
Step5:    Exit

C program to implement the selection sort.

main()
{
 int n, arr[10], pos, i, j, temp;
clrscr();
 printf("Enter the number of items:\n");
 scanf("%d",&n);
 printf("Input the n items here:\n");
 for(i = 0; i< n; i++)
{
 scanf("%d",&arr[i]);
 }
for(i = 0; i <n; i++)
    {
        pos = i;
        for(j = i+1; j< n; j++)
            {
                if(arr[j] < arr[pos])
                    pos = j;
            }
            temp = arr[pos];
            arr[pos] = arr[i];
            arr[i] = temp;
    }
printf("The sorted elements are as:\n");
for( i = 0; i < n; i++)
    {
        printf("%d\n",arr[i]);
    }
getch();
}
The program will outputs as:

Selection Sorting Algorithm in Computer Programming: C, output

Advantages

  • Very simple and easy to implement.
  • Straight forward approach.

Disadvantages

  • It is not efficient. More efficient sorting techniques are present.
  • Even if the elements are sorted, n-1 passes are required.

Binary Search in C
Linear Search in C

Selasa, 17 Desember 2013

How to Perform Initialization of Two Dimensional Arrays in C: Computer Programming

Assigning required value to a variable before processing is called initialization. As we initialize a variable to the required value (for example, a=10), we can also initialize the individual elements of a two dimensional array. The initialization can be done at the time of declaration with the following syntax:

data_type array_name [exp1][exp2]={
                                 {a1, a2, a3, ……, an},
                                 {b1, b2, b3, ……, bn},
                                  {c1, c2, c3, ……, cn},
                                           .…………………………
                       };
Where

  • data_type can be int, float, char, etc.
  • array_name is the name of the array
  • exp1 and exp2 are enclosed within square brackets
  • a-1 to a-n are the values assigned to 1st row, b1 to bn are the values signed to 2nd row and so on.

Initializing all specified memory locations

Consider the initialization statement shown below:

int  arr[3][3] = {{1, 2, 3},
           {4, 5, 6},
           {7, 8, 9}};

The declaration indicates that array arr has 3 rows and 3 columns. The pictorial representation of the two dimensional array is shown below:

How to Perform Initialization of Two Dimensional Arrays in C: Computer Programming

Note that a[0][0] = 1 and so on with increment the value of square brackets.

Partial array initialization

If the numbers of values to be initialized are less than the size of the array, then the elements are initialized from left to right one after other. The remaining locations will be initialized to zero automatically.

Example:     int arr[3][3] = {(1,2),(3,4),(5,6),(7,8)};

The declaration indicates that the array arr has 3 rows and 3 columns in which only first column of each row are initialized. The 3rd column of each row bill be initialized with zeros automatically as shown in the following figure:

How to Perform Initialization of Two Dimensional Arrays in C: Computer Programming

i.e., all arr[0][2], arr[1][2], arr[2][2] are initialized to zeros.

Example: Consider the partial initialization shown below:

int arr[3][3] = {{1,2,3,4},{5,6},{7,8}};

In this array each row should have three columns. But, in this example, we have initialized row 0 with 4 elements. This results in syntax error.

Memory Map: To represent the memory map of two dimensional array, consider the following two dimensional array declaration:
int arr[3][3] = {
            {1,2,3},
            {4,5,6},
            {7,8,9}
};

Even though we represent a matrix pictorially as a two dimensional array, in memory they are stored contiguously one after the other. Assume that address of first byte of arr (known as base address) is 12000 and size of integer is 2 byte. The memory map for the two dimensional array arr is shown in below figure:

How to Perform Initialization of Two Dimensional Arrays in C: Computer Programming

How to Use and Declare Two Dimensional Array in C: Computer Programming

Introduction

The elements of the arrays that explain or represent two characteristics are called two dimensional arrays in context of computer programming. Arrays with one set of square brackets '[]' are single dimensional arrays. Arrays with two sets of square brackets '[][]' are called two dimensional arrays and so on. Arrays with two or more dimensions are called multi-dimensional arrays. It is responsibility of the programmer to specify the number of elements to be processed within square brackets. For example,

int arr[5];       
int arr1[5][5];
int arr2[5][5][5];

In the above declaration the array named with arr is declared as one dimensional array, the array named with arr1 is declared as two dimensional arrays and the array named with arr2 is declared as three dimensional arrays.

A two dimensional array is used when data items are arranged row-wise and column-wise in a tabular form. Here, to identify a particular item or element, we have to specify two indices (also called subscripts). The first index identifies the row number and second index identifies the column number of the item or element.

Declaration of two dimensional arrays

A two dimensional array must be declared before it is use along with row-size and column-size of the array. The size used during declaration of the array, is useful to reserve the specified memory locations. A two dimensional array in C can be declared using the following syntax:

data_type array_name[exp1][exp2];

Where
  • data_type – can be a basic data type such as int, float, char etc.
  • array_name – is the name of the array
  • exp1 and exp2 – are constant or ordinal expression. The expression should be enclosed within square brackets ‘[]’. No variables are allowed inside the brackets. Should be evaluated to a positive integer only. It can also be an integer constant.
Note: exp1 specifies rows to be accessed using first index or subscript and exp2 specifies columns to be accessed using second index or subscript.

Consider the following declaration:
int arr[3][3];

The array arr has two sets of square brackets '[][]' and hence it is a two dimensional array with 3 rows and 3 columns. This declaration informs the compiler to reserve 9 locations (3 x 3 = 9) contiguously one after the other. Total memory reserved is 9 x 2 = 18 bytes. The pictorial representation of this arr array is shown below:

How to Use and Declare Two Dimensional Array in C: Computer Programming

Initialization of Two Dimensional Array

Senin, 16 Desember 2013

How to Read and Write Single Dimensional Array in C: Computer Programming

In Computer Programming, it is very easy to read or write variables by following some of the syntaxex listed in the rules. While programming in C, as discussed in earlier article, single dimensional array have such a simple declaration, initialization and now read and write syntax.

Consider the declaration shown below:

int arr[5];

Here, 5 memory locations are reserved and each item in the memory location can be accessed by specifying the index as: arr[0] through arr[4], we can access 5 data items. What, if there are n no. of items to be stored in the array.
Note: In general, using arr[0] through arr[n-1] we can access n data items of an array.

The n data items are read from the keyboard using the scanf() function as shown below:

scanf("%d", &arr[0]);
scanf("%d", &arr[1]);
scanf("%d", &arr[2]);

……………………………
……………………………
scanf("%d", &arr[n-1]);

In general syntax of scanf("%d", &arr[i]) i may be valued as 0, 1, 2, 3, ……., n-1. So, in C language, if we want to read n data items from the keyboard, the following looping statement can be used:

for(i=0; i<n; i++)
{
   scanf(“%d”,&arr[i]);
}

Similarly, to display n data items stored in the array, replace scanf() by printf() statement as shown below:

for(i=0; i<n; i++)
{
   printf(“%d”,arr[i]);
}

Now, write a small C program to read n elements from the keyboard and to display those same n elements on to the screen.

main()
{
  int n, i, arr[10];
  clrscr();
  printf("Enter the value of n:");
  scanf("%d",&n);
  printf("Enter n elements here:\n");
  for(i=0; i<n; i++)
    {
       scanf("%d",&arr[i]);
    }
 for(i=0;i<n;i++)
   {
       printf("The entered elements are :%d\n", arr[i]);
   }
getch();
}

The above program, when run, will show the following output screen:

How to Read and Write Single Dimensional Array in C: Computer Programming

How to Perform Array Initialization in Computer Programming: C

After declaration of arrays, the process of initialization starts in computer programming. Array initialization in C may be perform in many ways will be discuss in this article. C programming provides to let the programmer initialize the array to specific values when it is declared, when it is required or etc. Each option have its own examples described in the article.

How to Perform Array Initialization in Computer Programming: C

Initialization of all specified locations

Arrays can be initialized at the same time of declaration when their initial values are known in advance. Array elements can be initialized with data items of type int, char, float, etc.

int arr[5] = {15, 45, 85, 96, 69};

During compilation, 5 contiguous memory locations are reserved by the compiler for the array arr and all these locations are initialized as shown below:

How to Perform Array Initialization in Computer Programming: C

If the size of an integer is 2 bytes, 10 bytes will be allocated for the array arr. Lets discuss another initialization

int arr[5] = {15, 58, 98, 89, 65, 54, 55, 25, 85};
This declaration will notify an error with a message Number of initial values are more than the size of the array arr

char str[7] = {'P', 'R', 'O', 'G', 'R', 'A', 'M'};

During compilation, 7 contiguous memory locations are reserved by the compiler for the variable str and all these locations are initialized as shown below:

How to Perform Array Initialization in Computer Programming: C

In fact in place of character, ASCII values are stores in the memory. Since a character occupies 1 byte, 8 bytes will be allocated for the variable str.

Partial Array Initialization

C language also provides partial array initialization. If the number of values to be initialized is less than the size of an array, then the elements are initialized in order from 0th location. The remaining locations will be initialized to zero automatically. For example, consider the partial initialization shown below:

int arr[5] = {56, 76, 98};

Even though compiler allocates 5 memory locations, using this declaration statement, the compiler initialized first three locations with 56, 76 and 98. The next set of memory location are automatically initialized to 0's by the compiler as shown below:

How to Perform Array Initialization in Computer Programming: C

Initialization without Size

Consider the declaration along with initialization shown below:
char str[] = {'P', 'R', 'O', 'G', 'R', 'A', 'M'};

In this declaration, even though we have not specified exact number of elements to be used in array str, the array size will be set to the total number of initial values specified. So, the array size will be set to 7 automatically. The array str is initialized as shown below:

How to Perform Array Initialization in Computer Programming: C

String Initialization

Consider the declaration with string initialization:

char str[] = "PROGRAM";

The array str is initialized as shown below:

How to Perform Array Initialization in Computer Programming: C

Even though the string "PROGRAM" contains 7 characters, because it is a string, it always ends with NULL character '\0'. So, the array size is 8 bytes i.e. string length + 1 byte for NULL character.

char str[8] = "PROGRAM"; is Correct, size of the array is string length + 1 byte for NULL character.
char str[7] = "PROGRAM";  is Wrong, size of the array should be minimum 8.

For string initialization, usually the programmer prefer the following declaration:
char str[] = "PROGRAM";

Reading and Writing Single Dimensional Array

Jumat, 13 Desember 2013

Array Classification in Computer Programming with Declaration

Array in computer programming is used to store data items in a list, that may of any type. The array can be classified based on how the data items are arranged for human understanding. We have discussed about the concept of array, in this article we will classify an array.

The following figure shows the classification of the array:

Single dimensional arrays

A single dimensional array (also called one dimensional array) is a linear list consisting of related and similar data items. In memory, all the data items are stored in contiguous memory locations one after the other. Pictorial representation of single dimensional array is shown below:


Here, all the items are arranged in a row. It is called 'row major' arrangement. Instead, they can also be arranged column wise. It is called 'column major' arrangement. The memory requirement for the array depends on the type of data items stored and number of items. Let us assume, data items are of type int and assume that int takes 2 bytes (in majority of PCs size of integer will be 4 or 8 bytes). Since 5 elements are stored and the size of int is 2 bytes, the memory required for the array is 10 bytes. If the size of integer is 4 bytes, the array uses 40 bytes of memory and so on in general

Memory for array – n * sizeof (data type)

Where

  • n  is the number of data items
  • data type  the data type of data items

An array has the following basic properties:

  • The data items (called elements) stored in the array should be of the same data type. The data items are stored contiguously in memory with subscript of the first item always 0 (zero).
  • Each data item is accessed using the same name long with different subscript.
  • The subscript or index of the array is always an integer.

Declaration of single dimensional arrays:

We know that all the variables are declared before they are used in the program. Similarly, an array must be declared before it is used. During declaration, the size of the array has to specify. The size used during declaration of the array informs the compiler to allocate and reserve the specified memory locations. A single dimensional array in C can be declared using the following syntax:

data_typearray_name[expression];

where

  • data_type – can be a basic data type such as int, float, char, etc.
  • array_name – is the name of the array
  • expression – should be evaluated to a positive integer only. It can also be an integer constant. The expression should be enclosed within square brackets ‘[]’.

Note: Expression such as 10 or 10+2 is allowed. No variables are allowed in expression, for example, 10+b is not allowed because b is a variable.

For example, consider the following declaration statement: int arr[10];
The compiler reserves 10 locations (i.e. 2 *10 bytes) for the array arr. In each of the location we can store an integer value. The memory allocated by the compiler is, pictorially represented as:


Kamis, 12 Desember 2013

How to Store Multiple values in Computer Programming: 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.

Senin, 09 Desember 2013

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

Sabtu, 07 Desember 2013

Do-While Loop with Example in C: Computer Programming

In Computer programming, do-while loop is similar to while loop and used when a set of statements may have to be repeatedly executed until a certain condition is reached. When we do not know exactly how many times a set of statements have to be repeated, do-while can be used. The syntax of the do-while loop is shown below in C:

do
{
 statement1;
 statement2;
 statement3;
   .
   .
statementn;
} while (exp);

Where
  • do and while – are reserve words or keywords
  • exp – is the expression which is evaluated to TRUE or FALSE. The semicolon indicates the termination of the loop.
Working of do-while loop:
The following sequences of the operations are carried out during the execution of the do-while loop statement:
  • The body of the do-while loop consisting of statements statement-1, statement-2,….statement-n are executed.
  • Then, the exp is evaluated. If the expression exp is evaluated to TRUE, the body of the loop is executed again and the process is repeated.
  • If the exp is evaluated to FALSE, control comes out of the do-while loop and the statements after (outside) the do-while loop are executed.

Since the expression exp is evaluated to TRUE or FALSE at the bottom of the do-while loop, so, the do-while loop is called bottom testing loop or exit controlled loop. Here, the body of the loop is executed at least once.

Difference between while & do-while loop

Do-While Loop with Example in C: Computer Programming

Here's an example to get sum of 1 to given no.s
Algorithm:

Step1:    [Input the number of terms]
    Read: n
Step2:    [Initialization]
    sum=0
    i=0
Step3:    do
    sum = sum+i
    i = i+1
    while (i<=n)
Step4:    Write: sum
Step5:    Exit

Do-While Loop with Example in C: Computer Programming

C program
main()
{
int n,i,sum;
clrscr();
printf("Enter the value of n here: \n");
scanf("%d",&n);
sum=i=0;
do
{
sum=sum+i;
i++;
}while(i<=n);

printf("Sum of the series is %d",sum);
getch();
}

Do-While Loop with Example in C: Computer Programming, output

Read Also: Jump statements in C

While Loop with Example in C: Computer Programming

A set of statements may have to be repeatedly executed till a certain condition is reached, in every computer programming. In such situations (C language), we do not know exactly how many times a set of statements have to be repeated. So, naturally we need to have a condition controlled loop like in looping statements. In C language, the condition controlling is done generally by a while statement or while loop. It is also called test and do structure.

Syntax
while (exp)
{
  statement1;
  statement2;
  .
  .
  .
statementn;
}
Where

  • while -  is a reserve word or keyword
  • exp – is the expression which is evaluated to TRUE or FALSE.

Working of the while loop: 

The following sequences are carried out after executing the statements that appear just before the while loop

  • If the expression exp is evaluated to FALSE at the time of entry into the loop, the control comes out of the loop without executing the body of the loop. Later, the statements after the while loop are executed.
  • If the expression exp is evaluated to TRUE, the body of the loop is executed. After executing the body of the loop, control goes back to the beginning of the while loop and exp is again checked for TRUE or FALSE.
  • Thus, the body of the while loop is repeatedly executed as long as exp is evaluated TRUE. Once the expression exp is evaluated FALSE, the control comes out of the while loop and the statements which after the while loops are executed.

As the expression exp is evaluated to TRUE or FALSE in the beginning of the while loop, the loop is also called entry controlled or top testing loop.

If a relational expression is evaluated to TRUE, the result is 1. If a relational expression is evaluated to FALSE, the result is 0. If an arithmetic/logical/bitwise or any other expression is evaluated to non-zero value (for example 10, 999, etc) then the condition is TRUE. After evaluation, if the result is zero (0), then the condition is FALSE.

Some special forms of while loop are shown in table below:

While Loop with Example in C: Computer Programming

Algorithm: to reverse a given number

Step1:    [Input the number]
    Read : N
Step2:    [Initialize reverse number rev to 0]
    Rev = 0
Step3:    [Separate and reverse the number]
    While N !=0
        digit = N%10
        N = N/10
        Rev = rev*10+digit
    [End of while]
Step4:    [Output the reversed number]
    Write: rev
Step5:    Exit

Let N is 123, which is the give number to be reversed. In step1, N will be 12. In step2, N will be 1 and finally in step3, N is zero after separating a digit each time. So, the above three statements should be executed as long as N is not zero. Also, in step1, note that initial value of reverse is 0 and at the end of final step, reverse is 321.

Step by step Analysis
Step1:   
    Obtain 1st digit     =    123%10     = 3
    Reverse         =    0*10+3      = 3
    Separate 1st digit    =    123/10      = 12
Step2:   
    Obtain 2nd digit     =    12%10         = 2
    Reverse         =    3*10+2      = 32
    Separate 1st digit    =    12/10          = 1
Step3:   
    Obtain 3rd digit     =    1%10         = 0
    Reverse         =    32*10+1      = 321
    Separate 3rd digit    =    1/10          = 0
While Loop with Example in C: Computer Programming

C Program
main()
{
int n,revnum=0,digit;
printf("Enter any integer number here:\n");
scanf("%d",&n);
while(n!=0)
{
digit=n%10;
revnum=revnum*10+digit;
   n=n/10;
}
printf("The reverse number of %d is %d",n,revnum);
}

While Loop with Example in C: Computer Programming
The output is exactly the reverse no of input by the user.

Do-While loop in C

Senin, 02 Desember 2013

Looping Statements in Computer Programming, C Language

Introduction

We have learnt about branching statements that transfer the control from one point to another point in the computer programming. In this article, we concentrate on another important constructs like loop statements, which executes a set of statements repeatedly. Sometimes, it is required to execute a set of statements repeatedly in c programming. In such cases, the looping statements are used.

The statements that enables the programmer to execute a set of statements repeatedly till the required activity is completed, called looping statements or simply loop statements. These statements are also called repetitive or iterative statements. The statements within a loop may be executed for a fixed number of times or until a certain condition is reached. The various types of loop statements that are supported by the C language are as follows:

For Loop

A set of statements may have to be repeatedly executed for a specified number of times. In such situations, we use for loop statement. This type of loop is defined as an iterative statement that causes a set of statements to be executed repeatedly for a fixed number of times. If we know well in advance as how many times a set of statements have to be executed repeatedly, then for loop is the best choice.

The syntax of for loop as follows:
for (initialization; condition; increment/decrement)
{
    statement1;
    statement2;
    statement3;
}

Where

  • for: is the reserve word or keyword
  • Initialization: used to provide starting value to the variable. It should end with semicolon (;).
  • Condition: used to determine whether value of variable has reached the number of repetitions desired. It should end with semicolon (;).
  • Increment/Decrements: It is used to update the variable value by increment or decrements.

Note: Initialization, condition and updating statement can be multiple statements separated by comma (,).

In for loop some points have to keep in mind by c programmer, which are:

  • The initialization statement executes first and only once when the execution begins.
  • After this, condition is executed. If the condition is evaluated as the True then the body of for loop is executed. After executing the body of the loop the increment/decrements statement is executed. It is normally update the variable value by the specified step size. Then termination condition statement is executed and the process is repeated.
  • If the condition is evaluated to False, then the control comes out of the loop without executing the body of the loop. Later, the rest of the code is executed.

As long as condition is evaluated to True, the body of for loop and the updating statement are executed.
For example

for(i=1; i<=5;i++)
{
  printf(“%d”,i);
}
printf(“\nOut of the loop”);

In the above example,

  • For loop is executed for the first time and initialize the value of i =1.
  • Then, condition is checked and it is true since i = 1.
  • So, control enters into body of the loop and displays 1 on the screen using printf statement.
  • Then i is incremented by 1 and condition is checked again. The loop is repeatedly executed for i=1, 2, 3, 4 and 5, all these values are displayed one after other.
  • Finally, when i will be 6, the condition fails and control comes out of the loop and the message "Out of the loop" is displayed on the screen.

Here's an example to find sum of N natural numbers using For loop.

Algorithm:
Step1:    [Read the number of terms]
Read: N
Step2:    [Initialization]
    Sum = 0
Step3:    for i = 1 to N in steps of 1 do
    Sum = Sum + i
    [End of for]
Step4:    Write: Sum
Step5:    Exit

Looping Statements in Computer Programming, C Language


C program to find sum of natural number

main()
{
  int i,n,sum=0;
  printf("Enter the number of terms here:\n");
  scanf("%d",&n);
  for(i=1; i<=n; i++)
   {
     sum=sum+i;
   }
printf("The sun of n %d term = %d",n,sum);
getch();
}

Looping Statements in Computer Programming, C Language

Branching Statements in C