Wednesday 9 October 2013

Generate random no & push it stack

This is very basic program .We have to generate few random no. & check no is even or odd. If even than push it to stack 1 else IF no is odd push it to stack 2. Than print stack 1 & stack 2.

             C Program :

We use pointer to pass array & for push operation.
 #include<stdio.h>  
 # define max 10;     // defining value of MAX=10 globaly.   
 main()  
 {  
      int estk[10],top1; //array stack 1   
      int ostk[10],top2; //array stack 2  
      int i,ran;  
      top1=-1; // initialise top to -1 i.e initialt stack is empty  
      top2=-1;  
      for(i=0;i<10;i++)  
       {             //predefine funtion rand() used to generate randome no.   
            ran=rand() % 100 + 2;  // it ensure randome no is in between 2 to 100  
            printf("random no is =%d \n",ran);  
            if(ran%2==0)      // check random no is even or odd  
             push(&estk,&top1,ran);   // push to stack 1  
                else            // if no is odd  
                 push(&ostk,&top2,ran); //push to stack 2  
       }  
       printf("\n even stack is ::\n");   
       display(&estk,top1);  
       printf("\n odd stack is ::\n");  
       display(&ostk,top2);  
 }  
 int push(int *stk,int *top,int n)  
 {  
      if(*top>=10) // check for overflow condition  
       {  
            printf("\n overflow conditon\n");   
       }  
       else  
       *top=*top+1;  // incrementing top by 1  
       *(stk+*top)=n; // putting new volue in to it  
 }  
 int display(int *stk,int top)  
 {  
      int i;  
      for(i=0;i<top;i++)  
       printf(" %d ",*(stk+i));  
 }  

OUTPUT :-


No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets