Programming in C++ - Module 05
Programming in C++ - Module 05
Partha Pratim
Das Module 05: Programming in C++
Objectives & Stack and its Applications
Outline
Stack in C
Reverse a String
Eval Postfix
Stack in C++
Partha Pratim Das
Reverse a String
Eval Postfix
Department of Computer Science and Engineering
Summary Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 05
Stack in C
Reverse a String
Eval Postfix
Stack in C++
Reverse a String
Eval Postfix
Summary
Module 05
Summary
Module 05
Some common C programs that use stack:
Partha Pratim
Das Reversing a string
Objectives & Input: ABCDE
Outline Output: EDCBA
Stack in C
Reverse a String
Evaluation of postfix expression
Eval Postfix
Input: 1 2 3 * + 4 - (for 1 + 2 * 3 - 4)
Stack in C++
Reverse a String
Output: 3
Eval Postfix Stack states:
Summary
1 2 3 6 7 4 3
1 2 1 7
1
Evaluation 3
Module 05
Partha Pratim C++ standard library provide a ready-made stack for any
Das
type of elements
Objectives &
Outline
To create a stack in C++ we need to:
Stack in C Include the stack header
Reverse a String Instantiate a stack with proper element type (like char)
Eval Postfix
Stack in C++
Use the functions of the stack objects for stack operations
Reverse a String
Eval Postfix
Summary
return 0; return 0;
} }
Module 05 // FileName:Postfix_Evaluation_c++.cpp
#include <iostream>
Partha Pratim #include <stack>
Das using namespace std;
int main() {
Objectives & // Postfix expression: 1 2 3 * + 4 -
Outline char postfix[] = {’1’,’2’,’3’,’*’,’+’,’4’,’-’}, ch;
stack<int> s;
Stack in C
Reverse a String
for(int i = 0; i < 7; i++) {
Eval Postfix
ch = postfix[i];
Stack in C++ if (isdigit(ch)) { s.push(ch-’0’); }
Reverse a String else {
Eval Postfix int op1 = s.top(); s.pop();
int op2 = s.top(); s.pop();
Summary switch(ch) {
case ’*’: s.push(op2 * op1); break;
case ’/’: s.push(op2 / op1); break;
case ’+’: s.push(op2 + op1); break;
case ’-’: s.push(op2 - op1); break;
}
}
}
cout << "\nEvaluation " << s.top();
return 0;
}
Module 05
Module 05
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Stack in C
Srijoni Majumdar, TA [email protected] 9674474267
Reverse a String Himadri B G S Bhuyan, TA [email protected] 9438911655
Eval Postfix
Stack in C++
Reverse a String
Eval Postfix
Summary