Lec 2 Array Stack
Lec 2 Array Stack
Arrays
Declaring Arrays
Syntax:
• type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant greater than zero
and type can be any valid C++ data type.
Example:
To declare a 10-element array called salary of type double, use this statement −
•double salary[10];
Initializing Arrays
•You can initialize C++ array elements either one by one or using a single statement as follows −
•double salary[5] = {1000.0, 20000.0, 34000, 170000.0, 5000000.0};
•The number of values between braces { } can not be larger than the number of elements that we declare for the
array between square brackets [ ]. Following is an example to assign a single element of the array −
•If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you
write −
•double salary[] = {1000.0, 20000.0, 34000, 170000.0, 5000000.0};
•You will create exactly the same array as you did in the previous example.
•salary[4] = 50000.0;
• The above statement assigns element number 5 th in the array a value of 50000.0. Array with 4th index will be
5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base
index.
Accessing Array Elements
#include<iostream>
using namespace std;
class stack{
private:
int * arr;
int top,i;
public:
stack(){
arr=new int[10];
top=-1;
}
Implementation(cont.)
void pop(){
if(top==-1){
cout<<"stack is empty"<<endl;
}
top--;
}
Implementation(cont.)
int topval(){
if(top==-1){
cout<<"empty"<<endl;
return -1;
}
return arr[top];
}
Implementation(cont.)
void show(){
if(top==-1){
cout<<"stack is empty"<<endl;
}
for(i=top;i>=0;i--){
cout<<"value of stack "<<i<<" is "<<arr[i]<<endl;
}
}
};
Implementation(cont.)
int main(){
stack st;
st.push(1);
st.push(2);
st.push(4);
cout<<"TOP= "<<st.topval()<<endl;
// st.pop();
// cout<<"TOP= "<<st.topval()<<endl;
st.show();