-->

Friday, January 30, 2015

Implementation of pointer variable in Data Structures through C Language

            Implementation of pointer variable with example

Pointer Operations

One can do only possible two operations on pointers One is assignment and another one is simple addition or subtraction of values with pointer variables. No other operation is permitted to perform on the pointer variables because they simply contain the memory addresses or locations not the variables.

Assignment operation:

      The assignment operation is nothing but assigning a pointer variable with the memory address. The memory address must be known (static or dynamic). A pointer can be assigned with the address stored in another pointer variable. To perform assignment operation the two “pointer variables” must be of the same type. The pointer must point to memory locations that contain the similar type values like integers, floating-point number, characters etc. If ‘a’ is an integer variable then the address of ‘a’ can be assigned to any pointer variable of the type integer.

Example:
Void main()
{
Int*p, a=120;
 /* p is a pointer variable, a is a simple variable*/
Printf(“Address = %Id, Value = %d\n”,&a,a);
P = &a;
/*p is assigned with address of a */
Printf(“Address = %Id, Value = %d”,p*p);
/*Both of the above printf statements Display the same values*/

In the above example, the pointer variable is assigned with the memory address that is already allocated by the system to other variable. In this type of simple assignment  the address of variable ‘a’ is stored in pointer p. You can also note that the data type of both the variables, ‘a’ and ‘b’ is similar i.e. ‘int’.

       If the pointer variable is used to change the value at the memory location, then it automatically changes the value of the non-pointer variable ‘a’. This is the concept that comes into picture when ‘call-by-reference’ is used (i.e. when the formal parameters are pointer types)
Example:
Main()
{
Int *p,a=10;
Printf(“Value of a, before pointer operation: %d”,a);
/*10*/
P=&a;
*p=26;
Printf(“Value of a, after pointer operation: %d”,a);
/*26*/
}
In the example the address of a variable (a) is assigned to a pointer variable (p). When the content of memory is changed by the pointer variable it affects the original variable. It is mainly because both the variables refer the same memory location or address.
Example to show the effect of ‘call-by-reference’:
Void fun (int a, int *b)
/*a is a value parameter, b is a reference parameter*/.
{
a++;
/*’a’ local variable of fun() incremented by 1*/
*b = *b + a; /* pointer ‘b’ points to the memory location of variable ‘b’ of main()*/
}
main()
{
Int a=10, b=12;
Printf(“a=%d, b=%d\n”,a,b);
fun(a,&b);
printf(“a=%d,b=%d”,a,b);

}


 

The parameter ‘b’ of function fun() is a pointer. So, it changes the value of variable ‘b’ of main(). Both refer to same memory.
Example:
Main()
{
Int *p1, *p2, a=10;
Printf(“a=%d\n”,a);          /*a=10 is displayed*/
p1=&a;    /*pointer p1 is assigned with address of variable ‘a’*/
p2=p1;    /*pointer p2 is assigned with value of p1 (address of a). another way of assignement */
printf(“Value at p1=%d\n”,*p1);     /* 10 is displayed */
printf(“Value at p2=%d\n”,*p2);      /* 10 is displayed */
}
The above example is self-explaining via comments. You can mainly note that the non-pointer variable ‘a’, pointer p1 and p2 are of same type (int). Now let us see an example of dynamic memory allocation:
Main()
{
Int*p;
p=(int*) malloc(sizeof(int)); *p=10; printf(“%d”,*p);
}
In this example the pointer variable p is assigned with the address that is returned from the malloc(). An example of assigning dynamically allocated memory. The dynamically allocated memory  stores integer and the pointer is also of the type integer.

Pointer and Dynamic memory Allocation in data structure through C Language

                                                            When the variables are declared in a program, usually the memory is allocated during the compilation that is statically. The memory referred by such variables is used to store the value (data) directly. Instead of data directly if another memory location is to be stored in the variables, then it should be a pointer variable. As we are already familiar with the dynamic memory allocation, and if it is to be implemented then without pointer variables it is not possible. During the execution of program dynamic memory is allocated, so there must be a variable that stores addresses of memory at that time. That is the reason why pointer variable is used. When pointer variables are declared no memory is allocated to store the data. The memory is allocated to them only to store the memory address not the data. Taking this as an advantage the pointer variable can be made to point dynamically allocated memory location.

For example if “p” is a pointer variable declared of the type “int” then for p memory is allocated to store the address of a memory is location that stores an “int” (integer data). Here the memory address that is to be stored in pointer variable may be static or dynamic. Usually it is to be dynamic memory allocation. It can be pictured as follows:
int *p, a;           ‘p’ is a pointer variable, ‘a’ is a simple integer variable. For ‘a’
                           memory is allocated statically to store integer data. Of course for                  
                           ‘p’ also memory is allocated but to store an address not data.
a=10;                 at memory location is reserved by ‘a’, an integer 10 is stored.
P=&a;                ‘p’ as it is pointer variable used to store address of statically
                           allocated memory.
With the help of pointer ‘p’ is possible to refer integer value stored at variable ‘a’ indirectly through pointer ’p’.

If ‘a’ is user to print, it prints the value 10, if &a (&a is called address operator) is used, it prints 1000 as per the examples. If p is used it also prints 1000 the content of p the address of memory is allocated to a. If *p (de-referencing of pointer) is used it prints the value of memory location pointed by the pointer variable. Here it prints the value of ‘a’ that is 10.
We can take the advantage of storing the memory address by a pointer variable during the execution of program. So instead of storing the already allocated static memory, a dynamic memory maybe requested during the execution of program and the dynamically allocated memory address may be stored in a pointer variable and it is used as it is normal variable.
Dynamically the memory is allocated using the standard functions calls depending on the high level languages used. Like in Pascal new used, in C++ new operator is used and in C language the functions like malloc(), calloc() and realloc() are used.
So, in C language if memory is requested by the user during the execution of the program to store data one of the following functions may be used. The functions are different as per the purpose and the numbers of arguments passed to the functions. All these functions return an address called the base address of dynamically allocated memory and is store in a pointer variable.


For example (int *) malloc (20) – allocates 20 bytes of consecutive memory dynamically on success, (or return a NULL address if not successfully allocates) and returns the base address. The returned address may be stored in a pointer variable of the type int and 10 integers can be referred with the help of that pointer variable. It is nothing but an array of size 10 for which the memory is allocated during the execution of program. The initial values stored in the memory location allocated are garbage values.




So, the memory allocated by the ‘calloc’ function is the product of number_of_elements and size_of_each_element. For example (int *) calloc (10, 2) allocates 20 bytes of dynamic memory. So, 10 integers can be stored in those memory locations. The initial values of these memory locations will be zero. Similar to malloc (), the returned address may be stored in a pointer variable and treated as an array of 10 integers.


If the dynamic memory allocated using either calloc or malloc is to be changed during the execution of program then realloc is used. It allocates completely a new memory block and copies the contents of already allocated block and returns the new base address. That address may be stored in the same pointer variable. Otherwise it expands the existing block and returns the same base address. The change may even reduce the size of already allocated block.
The dynamic memory is allocated from the heap area of main memory. If the requested memory is not available the dynamic memory is allocation functions return NULL address or invalid address, it is also treated as a 0 (zero) value. The dynamically allocated memory may be freed from the programmer after his/her usage using free () function. The prototype of void free (void *block) is available in alloc.h. If the user does not free the dynamically allocated memory, it is the function of operating system to collect the dynamic memory periodically and give it back to heap. This function of operating system called as “garbage collection”. It is better practice for the programmers to free the dynamically allocated memory after the use of such memory. If you write the statements for dynamic memory allocation then remember that the free statement is also used in the program before the end of program to ensure to free the dynamically allocated memory. 

How to Validate DropDownList in ASP.NET

Introduction

Various methods is available to validate the TextBox but very few methods is available to validate the Dropdownlist. Here i have two methods to validate it. In the first method i will use RequiredFieldValidator control with InitialValue property, in the second method i will use javaScript. for validation.


I-Method

In the first method, first to add some items in the dropdownlist. Now, take a RequiredFieldValidator control to validate the Dropdownlist. Set some required properties of validator control. These are:

ControlToValidate="Id of Dropdownlist control"
ErrorMessage=" Please select item from Dropdownlist "
InitialValue = "Match with Text item which is available in Dropdownlist also you do not want to display. Like

<asp:ListItem>select one</asp:ListItem>
            <asp:ListItem>Apple </asp:ListItem>
            <asp:ListItem>Mango</asp:ListItem>
            <asp:ListItem>Orange</asp:ListItem>

Here, i set the InitialValue = select one.

Complete code to describe more:


<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text += "Your selected item is <br/>"+DropDownList1.SelectedItem.Text;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
   
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" Height="30px" Width="149px" AutoPostBack="True">
            <asp:ListItem Selected="True">select one</asp:ListItem>
            <asp:ListItem>Apple </asp:ListItem>
            <asp:ListItem>Mango</asp:ListItem>
            <asp:ListItem>Orange</asp:ListItem>
        </asp:DropDownList>
        <br />
    </div>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1" ErrorMessage="RequiredFieldValidator" InitialValue="select one">Please Select Item</asp:RequiredFieldValidator>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
    </form>
</body>
</html>



Output
How to Validate DropDownList in ASP.NET

How to Validate DropDownList in ASP.NET



II-Method

In the second method we use javascript to validate the Dropdownlist. First to add some Text and Value in the control, Now With the help of getElementById property we can access the value of this control. Generate error message with the help of alert dialog box when accessed value is match with selected value of this control.

Complete code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
   function validate()
   {
       var req = document.getElementById('<%=DropDownList1.ClientID %>');
       if(req.value=="0")
       {
           alert("please select one item");
       }
    }
   </script>
</head>
<body>
    <form id="form1" runat="server">
 
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem Value="0" Text ="Select"></asp:ListItem>
            <asp:ListItem Value="1" Text ="Education"></asp:ListItem>
            <asp:ListItem Value="2" Text ="Technology"></asp:ListItem>
            <asp:ListItem Value="3" Text ="Entertainment"></asp:ListItem>
        </asp:DropDownList>
       
   
   
        <p>
            <asp:Button ID="Button1" runat="server" style="height: 26px" Text="Button" OnClientClick="validate()" />
        </p>
   
    </form>
</body>
</html>

Download : Complete Code

String Literals and Constants in 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.

Thursday, January 29, 2015

What is Variable Length String Format in 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



Bubble Sort Algorithm in C Language

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

STACK in C Language

  • It’s special data structure based on LIFO (Last In First Out Concept).
  • It can be implemented using One dimensional Array as well as Singly linked list.
  • TOP  is the external pointer points to last node element pushed.
  • There are two operation which is performed on stack i.e., Push (Insertion) and Pop (Deletion).
  • Push and Pop operation is performed through TOP end.( means insertion and deletion is restricted through one end i.e., TOP end)

Write an algorithm to perform push operation.

PUSH(TOP)
[ PUSH is the name of algorithm and TOP is the external pointer points to last inserted node. ]
NEW<--FREE
FREE <--  FREE --> NEXT
If NEW=NULL Then:
    Write : ‘ Memory allocation errot’
     Exit
[ End of If]
Read : NEW-->INFO
NEW -->  NEXT <-- TOP
TOP <--NEW
END

Write an algorithm to perform pop operation.

POP(TOP)
[ POP is the name of algorithm]
If TOP = NULL Then:
   Write: ‘ Stack is empty’
   Exit
[ End of If]

I <-- TOP --> INFO
Write: ‘Poped element is’, TOP -->  INFO
TOP <-- TOP --> NEXT
END

Write the program to perform PUSH and POP operation:

#include<stdio.h>
#include<conio.h>

struct node
{
   int info;
      struct node *next;
};
struct node *top=NULL;

void push(int i);
{
 struct node *new;
 if(new==NULL)
{
    printf(“Memory allocation error\n”);
    exit(0);
 }
new->info=i;
new->next=top;
top=new;
}

void pop(void)
{
  if(top==NULL)
  {
    printf(“Stack is empty”);
    exit(0);
  }
  printf(“%d->”,top->info);
  top=top->next;
}

void main()
{
  int i;
 char ch;
  clrscr();
  do
  {
     printf(“Enter your choice\n”);
     printf(“1. PUSH\n”);
     printf(“2. POP\n”);
     scanf(“%d”,&choice);
     switch(choice)
     {
  case 1:
printf(“Enter the value to push in stack\n”);
scanf(“%d”,&i);
push(i);
break;
case 2:
pop();
break;
default:
printf(“Invalid choice try again\n”);
    }
   printf(“Do you want to continue press ‘Y’\n);
  ch=getche();
    }while(ch==’Y’);
getch();
}

Algorithm to Push an element on  Stack using One dimensional Array:

PUSH( S, TOP, N, ITEM )
[S is the name of Array , TOP is the current index of a STACK , N is the size of an Array, ITEM is the element to be inserted]

If TOP==N Then:
   Write: ‘Overflow’
   Exit
[ End of If]
TOP <--TOP+1
S[TOP]=ITEM
END

Algorithm to Pop the Stack using One dimensional Array:

POP(S, TOP)
[ S is the name of an array and TOP is the current index]

If TOP=-1 Then:
   Write: ‘Underflow’
    Exit
[ End of If]
I <-- S[TOP]
TOP <-- TOP-1
Return I
END

WACP to perform Push and Pop operation on Stack using One dimensional Array:

/* Function to perform push operation */
void push(int s[], int n, int *top, int i)
{
  if (top==n)
    {
        printf(“Over flow”);
        exit(0);
    }
s[++top]=i;
}
/* Functio to perform pop operation */
int pop( int s, int *top)
{
  int i;
  if( top==-1)
   {
      printf(“Underflow”);
      exit(0);
   }
i=s[top--];
return i;
}
main( )
{
 int s[8],top,item,choice;
char ch;
do
{
   printf(“Enter your choice\n”);   
   printf(“1.Push Operation\n”);
   printf(“2. Pop operation\n”);
   scanf(“%d”,&choice);
   switch(choice)
   {
      case 1: printf(“Enter the element to push\n”);
scanf(“%d”,&item);
push(s, 8,&top,item);
break;
case 2: printf(“Poped element=%d”,pop(s, &top));
break;
default: printf(“Invalid choice\n”);
}
printf(“Do you want to continue press ‘Y’\n”);
ch=getche();
}while(ch==’Y’);
getch(); }

Polish Notation:

Infix expression takes much time and scanning to evaluate in computer due to operator hierarchy and 
parenthesis. so to overcome this problem French Mathematician Polish has given parenthesis free 
notation. i.e., Postfix and Prefix notation. 
In Postfix notation operator is placed after the operand. 
And in Prefix notation operator is placed before operand.

Conversion of Infix expression into prefix and postfix notation:
Infix exp: 5*9^2/3

First place parenthesis according to operator hierarchy
((5*(9^2))/3)
Postfix Conversion:
Step 1: Conversion done from higher order operator and place the operator at the place of left parenthesis. Remove the both of parenthesis.
((5*^92)/3)
Step 2: Place the operator again at the left of parenthesis and remove according to operator hierarchy.
(*5^92/3)
Step 3:
/5*92^3

Prefix Converesion:

Step 1: Conversion done from higher order operator and place the operator at the place of right parenthesis. Remove the both of parenthesis.
((5*92^)/3)
Step 2: Place the operator again at the Right of parenthesis and remove according to operator hierarchy.
(592^*/3)
Step 3:
592^*3/

Algorithm to Convert  an INFIX expression to POSTFIX expression using stack:

INFIX_TO_POSTFIX(I)
[ I is the INFIX expression]

STEP 1: Add  ‘) ‘ at the end of I. and push ‘ ( ‘ on to the stack.
STEP 2: Repeat scanning the characters of I from left to right while stack is not empty
  STEP 2(a):    If the scanned character is an operand Then:
  Add it to P (PostFix expression)
[ End of If]
  STEP 2(b):    If the scanned character is ‘(‘ Then:
Push it on the stack
[End of If]
STEP 2(c):    If the scanned character is’)’ Then:
Repeatedly POP the stack till ‘(‘ , add the poped operators to P
 and remove ‘(‘ from the stack 
[End of If]
STEP 2(d):    If the scanned character is operator Then:
Check the top of stack repeatedly for higher or same hierarchy of operators till lower hierarchy. if any pop them and add to P
and push the scanned character onto Stack
[End of If]

 [ End of While]
STEP 3: Write: P
STEP 4: EXIT

Convert the Infix exp. I: (A+B) / ( C-D ) ^ E + F * G 

Add ) to I at the end, PUSH ( on to the stack.
S. NO.
 Scanned Character
STACK
POSTFIX exp P
1.
(
(

2.
(
((

3.
A

A
4.
+
((+
A
5.
B
((+
A B
6.
)
(
A B +
7.
/
( /
A B +
8.
(
( / (
A B +
9.
C
( / (
A B + C
10.
-
( / ( -
A B + C
11.
D
( / ( -
A B + C D
12.
)
( /
A B + C D -
13.
^
( / ^
A B + C D -
14.
E
( / ^
A B + C D – E
15.
+
( +
A B + C D – E ^ /
16.
F
( +
A B + C D – E ^ / F
17.
*
( + *
A B + C D – E ^ / F
18.
G

A B + C D – E ^ / F * +

Evaluation of POSTFIX expression using STACK.

POSTFIXEVAL(P)

[ P is a POSTFIX expression]
Repeat Scanning P from left to right While Scanned Character != #
  If  Scanned character = operand Then:
      STACK[TOP] <-- operand
      TOPßTOP+1
  Else
      B<-- STACK[TOP], TOP<--TOP-1
      A<-- STACK[TOP], TOP<--TOP-1
      RES<--A operator B
      STACK[TOP] <--RES
  [ End of If]
[End of While]
VAL <-- STACK[TOP]
Write: ‘ Value of postfix expression’, VAL
END

Example: Evaluate the Postfix exp 5 6 * 3 + 5 – 

Soln : Add # at the end of Postfix expression
Start scanning the exp. from left to right.
S.NO.
Scanned Character
STACK
1.
5
5
2.
6
5, 6
3.
*
30   // (5*6)
4.
3
30, 3
5.
+
33   // (30+3)
6.
5
33, 5
7.
-
28  // (33-5)

© Copyright 2013 Computer Programming | All Right Reserved