MENU











Sunday, 10 November 2013

Ds Week2 programs

Exercise 2

2c)Implement stack operations using pointers

Aim::/*To implement stacks using pointers*/

Program::

#include< stdio.h> //Standard i/p,o/p header file
#define max 100
int  arr[max],top=-1; 
int  *stack=arr; 
 
/*Inserting the elements using push function*/ 
void  push(int  ele) 
{ 
     *stack=ele; 
    printf("\n\nElement %d is pushed......\n\n",ele); 
    stack++; 
    top++; 
} 
 
/*Removing the elements using pop function*/ 
void  pop() 
{ 
    if(top==-1) 
    { 
        printf("\n\nStack is empty....."); 
    } 
    else 
    { 
        printf("\n\nPoped element : %d",*(stack-1)); 
        stack--; 
        top--; 
    } 
} 
 
/*Displaying the elements */ 
void  display() 
{ 
     int  t; 
     if(top==-1) 
        printf("\n\nStack is empty....."); 
    else 
    { 
        printf("\n\nStack elements are : "); 
        for(t=top;t>=0;t--) 
        { 
                printf("%d ",*(stack-(t+1))); 
        } 
    } 
      
} 
int  main() 
{ 
    int  num1=0,num2=0,i,ch; 
    while(1) 
    { 
            printf("\n\t\t MENU "); 
            printf("\n[1]Push Function\n[2] Pop Function\n[3] Elements present in Stack\n[4] Exit\n"); 
            printf("\n\tEnter your choice: "); 
         
            scanf("%d",&ch); 
        switch(ch) 
        {  
                  case 1: printf("\n\tEnter the element to be pushed:"); 
                       scanf("%d",&num1); 
                       push(num1); 
                       break; 
                  case 2: pop(); 
                       break; 
                  case 3: display(); 
                       break; 
                  case 4: break; 
                  default: printf("\nYour choice is invalid.\n"); 
                             break; 
        } 
     
   } 
}

output::

gcc pointers.c -o pointers
./pointers

		 MENU 
[1]Push Function
[2] Pop Function
[3] Elements present in Stack
[4] Exit

	Enter your choice: 1

	Enter the element to be pushed:8


Element 8 is pushed......


		 MENU 
[1]Push Function
[2] Pop Function
[3] Elements present in Stack
[4] Exit

	Enter your choice: 1

	Enter the element to be pushed:2


Element 2 is pushed......


		 MENU 
[1]Push Function
[2] Pop Function
[3] Elements present in Stack
[4] Exit

	Enter your choice: 1

	Enter the element to be pushed:17


Element 17 is pushed......


		 MENU 
[1]Push Function
[2] Pop Function
[3] Elements present in Stack
[4] Exit

	Enter your choice: 3


Stack elements are : 8 2 17 
		 MENU 
[1]Push Function
[2] Pop Function
[3] Elements present in Stack
[4] Exit

	Enter your choice: 4



No comments:

Post a Comment