CS301 Assignment 2 Solution Fall 2017

Question:                                                                                                                                          Marks 20

Write a C++ program to balance three (3) stacks so the sum of numbers in each stack should be same.

Your program should fulfill following requirements.

1)      Create three (3) stacks, initially each stack will have three same numbers. Number of each stack should be different from other stack numbers. You can see in above diagram that initially each stack have same number but number is different from the numbers in other stacks.

2)      Your program should swap values between stack in the way that after balancing the stacks. Each stack should have different number as showing in above diagram.

3)      Please note that user will enter numbers into stack, not X, Y and Z.

4)      User will enter a number for each stack which will be inserted 3 times in each stack.

5)      You can implement stack through array or link list. It is your choice.

Sample output screen shot of program is given below

Solution Guidelines:

  1. First understand the code given in handouts about stack.
  2. Don’t allow popping if stack is empty and pushing if stack is full.

Solution :

#include<iostream> //starting here
using namespace std; //using standerd namespce
main() //main oarts start here
 int stack1[3],stack2[3],stack3[3],a,b,c,d; //declaring variables stack and simple variable and input numbers
 cout<<"Enter The Number to push in Stack1 : ";//msgs
 cin>>a;//input in a
 for(b=0;b<=2;b++)//using loop to add a value in stack indexs
 stack1[b] = a;//assaignment statement
 cout<<"Enter The Number to push in Stack2 : ";
 cin>>d;//second stack value
 for(b=0;b<=2;b++)//second loop
 stack2[b] = d;//second assaignment
 //cout<<stack2[b]<<" "<<d<<" ";
 cout<<"Enter The Number to push in Stack3 : ";
 stack3[b] = c;//third assaignment to stack
 cout<<endl;//end of line
 cout<<"Stacks Before Balancing "<<endl;//output before balancing
 cout<<"Stack1 numbers :";//output msg
 for(b=0;b<=2;b++)//loop for output stack
 cout<<" "<<stack1[b] <<" ";//stack 1 output
 cout<<endl<<"Stack2 numbers :";//stack 2 output
 cout<<" "<<stack2[b] <<" ";
 cout<<endl<<"Stack3 numbers :";//stack 3 output
 cout<<" "<<stack3[b] <<" ";
 //*cout<< end1;
 cout<<"stacks after balancing"<<endl;//out after balancing
 cout<<"stack1 numbers :";
 stack1[0] = stack3[0];//swaping stacks value here 1 by 1 
 cout<<" "<<stack1[0]<<" ";
 stack1[1] = stack2[1];
 cout<<" "<<stack1[1]<<" ";
 cout<<" "<<stack1[2]<<" "; 
 cout<<"stack1 numbers :";
 stack2[0] = stack1[2];
 cout<<" "<<stack2[0]<<" ";
 stack2[1] = stack3[1];
 cout<<" "<<stack2[1]<<" ";
 cout<<" "<<stack2[2]<<" "; 
 cout<<"stack1 numbers :";
 stack3[0] = stack1[2];
 cout<<" "<<stack3[0]<<" ";
 stack3[1] = stack2[2];
 cout<<" "<<stack3[1]<<" ";
 cout<<" "<<stack3[2]<<" ";