SlideShare a Scribd company logo
IT 211
DATA STRUCTURES
   MIDTERM
 REQUIREMENT
IT 211 DATA STRUCTURES
               MIDTERM REQUIREMENT


   1. Write a program to enter the name and votes of 5 candidates. The program
      should display each candidate’s name, votes and percentage of votes. The
      program should also declare the winner.

         #include <string>
         #include<iostream>
         using namespace std;

         class ElectionResults
         {
         public:
         string name;
         int votes;
         };

         int main()
         {
         ElectionResults res[5];
         int voteTotal = 0;
         int winner = 0;
         int byVotes = 0;
         float percent = 0.0;


         for(int i = 0; i < 5; i++)
         {
         cout << "Enter Last Name of Candidate "<<i+1<<"                 : ";
         cin >> res[i].name;

         cout<<"Enter the Votes Received for Candidate "<<i+1<< ": ";
         cin >> res[i].votes;
         cout<<"--------------------------------------------------------"<<endl;

         voteTotal += res[i].votes;
         if( res[i].votes > byVotes)
         winner = i;
         }




Kevin Dulay III                                                                    Lleif Christian Binasoy
Hazel Joy Paguyo                                                                   Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
              MIDTERM REQUIREMENT



           cout<<"Name of candidatetVotes receivedtPercentage"<<endl;

           for(int i = 0; i < 5; i++)
           {
           cout<<res[i].name<<"ttt"<< res[i].votes
           <<"ttt"<<(res[i].votes*100)/voteTotal << "%." <<endl;
           }
           cout<<"nTotal Votes: "<<voteTotal<<endl;
           cout << "The Winner is:" << res[winner].name<<endl;
           cin >> voteTotal;
           }




Kevin Dulay III                                                       Lleif Christian Binasoy
Hazel Joy Paguyo                                                      Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
              MIDTERM REQUIREMENT


   2. STRINGS
      a. Write a program to accept and display the number of letters, words and
      sentences of a text input.

                   #include <iostream>
                   #include <string>
                   #include <cctype>
                   using namespace std;

                   int main(){
                       string userInput;
                       char myChar;

                        int words = 1;
                        int sentences = 0;
                        int paragraphs = 1;
                        cout << "Enter some text: ";
                        getline (cin, userInput);

                        for (int i = 0; i <int(userInput.length()); i++)
                        {
                          myChar = userInput.at(i);

                            /*if (userInput[i] == isascii(NUL))       {
                              words --;
                              paragraphs --;
                            }*/

                            if (userInput[i] == ' ')
                               words++;

                            if (userInput[i] == '.')
                                sentences++;

                            if (userInput[i] == 'n' && userInput[i] == 't')
                                paragraphs++;

                        }

                        cout << "words: " << words << endl;
                        cout << "sentences: " << sentences << endl;
                        cout << "paragraphs: " << paragraphs <<endl;

                        int p;
                        cin >> p;
                        return 0;
                    }

Kevin Dulay III                                                                 Lleif Christian Binasoy
Hazel Joy Paguyo                                                                Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
              MIDTERM REQUIREMENT



b. Write a program to determine if a word is palindrome


            #include<iostream.h>
            #include<string.h>

            int main()
            {
            char str[25],str1[25];
            cout<<"Enter a string: ";

            gets(str);

            strcpy(str1,str);
            strrev(str);
            if(strcmp(str,str1)!=0)
            {
            cout<<"string is not palindrome";
            }
            else
            {
            cout<<"string is a palindrome";
            }

            cout<<endl;
            cin.get();
            return 0;
            }




Kevin Dulay III                                           Lleif Christian Binasoy
Hazel Joy Paguyo                                          Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
                MIDTERM REQUIREMENT


   3. RECURSION
      Write a program to convert a binary number to its decimal equivalent using a
      recursive function.
       //BINARY TO DECIMAL
       #include <iostream>
       #include <math.h>

       using namespace std;

       int sum = 0;
       using namespace std;
       int BinaryToDecimal (int BinaryNumber, int weight);

       int main(){
         int bitWeight;
         int binaryNum;
         bitWeight = 0;
         cout<<"======CONVERTING BINARY TO DECIMAL======="<<endl;
         cout<<"Enter the Binary Number: ";
         cin>>binaryNum;

           cout<<"n";

           int sum = BinaryToDecimal (binaryNum, bitWeight);
           cout<<"The Decimal Equivalent of inputed Binary is: "<<sum<<endl;

           system("PAUSE");
           return 0;
       }

       int BinaryToDecimal (int BinaryNumber, int weight)
       {
       int bit;
       if (BinaryNumber>0){
                 bit = BinaryNumber % 10;
                 sum = sum + bit * pow (2, weight);
                 BinaryNumber = BinaryNumber /10;
                 weight++;
                 BinaryToDecimal (BinaryNumber, weight);
                 {

       return sum;
       }
       }
       }



Kevin Dulay III                                                                Lleif Christian Binasoy
Hazel Joy Paguyo                                                               Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
                MIDTERM REQUIREMENT



    //DECIMAL TO BINARY
    #include <iostream>

    using namespace std;

    void binary(int);

    int main(void) {
    int number;

    cout << "Please enter a positive integer: ";
    cin >> number;
    if (number < 0)
    cout << "That is not a positive integer.n";
    else {
    cout << number << " converted to binary is: ";
    binary(number);
    cout << endl;
    }
    }

    void binary(int number) {
    int remainder;

    if(number <= 1) {
    cout << number;
    return;
    }


    remainder = number%2;
    binary(number >> 1);
    cout << remainder;
    cin.get();
    }




Kevin Dulay III                                      Lleif Christian Binasoy
Hazel Joy Paguyo                                     Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
                MIDTERM REQUIREMENT




LECTURE REQUIREMENTS

Research on the definitions, C++ implementation, and program examples of the
following:

      Stack
      Lists
      Queues
      Pointers



1. Stack
LIFO stack

Stacks are a type of container adaptor, specifically designed to operate in a LIFO context
(last-in first-out), where elements are inserted and extracted only from the end of the
container.

stacks are implemented as containers adaptors, which are classes that use an encapsulated
object of a specific container class as its underlying container, providing a specific set of
member functions to access its elements. Elements are pushed/popped from the "back" of
the specific container, which is known as the top of the stack.

The underlying container may be any of the standard container class templates or some
other specifically designed container class. The only requirement is that it supports the
following operations:




      back()
      push_back()
      pop_back()


Therefore, the standard container class templates vector, deque and list can be used. By
default, if no container class is specified for a particular stack class, the standard container
class template deque is used.

In their implementation in the C++ Standard Template Library, stacks take two template
parameters:
  template < class T, class Container = deque<T> > class stack;


Kevin Dulay III                                                            Lleif Christian Binasoy
Hazel Joy Paguyo                                                           Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
               MIDTERM REQUIREMENT



Where the template parameters have the following meanings:



      T: Type of the elements.
      Container: Type of the underlying container object used to store and access the
       elements.




Kevin Dulay III                                                      Lleif Christian Binasoy
Hazel Joy Paguyo                                                     Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
               MIDTERM REQUIREMENT


2. LISTS

Lists are a kind of sequence container. As such, their elements are ordered following a linear
sequence.

List containers are implemented as doubly-linked lists; Doubly linked lists can store each of
the elements they contain in different and unrelated storage locations. The ordering is kept
by the association to each element of a link to the element preceding it and a link to the
element following it.

This provides the following advantages to list containers:



      Efficient insertion and removal of elements before any other specific element in the
       container (constant time).
      Efficient moving elements and block of elements within the container or even
       between different containers (constant time).
      Iterating over the elements in forward or reverse order (linear time).



Compared to other base standard sequence containers (vectors and deques), lists perform
generally better in inserting, extracting and moving elements in any position within the
container for which we already have an iterator, and therefore also in algorithms that make
intensive use of these, like sorting algorithms.

The main drawback of lists compared to these other sequence containers is that they lack
direct access to the elements by their position; For example, to access the sixth element in
a list one has to iterate from a known position (like the beginning or the end) to that
position, which takes linear time in the distance between these. They also consume some
extra memory to keep the linking information associated to each element (which may be an
important factor for large lists of small-sized elements).

Storage is handled automatically by the list object, allowing it to be expanded and
contracted automatically as needed.

In their implementation in the C++ Standard Template Library lists take two template
parameters:
  template < class T, class Allocator = allocator<T> > class list;




Kevin Dulay III                                                          Lleif Christian Binasoy
Hazel Joy Paguyo                                                         Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
               MIDTERM REQUIREMENT



Where the template parameters have the following meanings:



      T: Type of the elements.
      Allocator: Type of the allocator object used to define the storage allocation model.
       By default, theallocator class template for type T is used, which defines the
       simplest memory allocation model and is value-independent.

In the reference for the list member functions, these same names are assumed for the
template parameters.




Kevin Dulay III                                                       Lleif Christian Binasoy
Hazel Joy Paguyo                                                      Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
               MIDTERM REQUIREMENT


3.Queues

FIFO queue

queues are a type of container adaptor, specifically designed to operate in a FIFO context
(first-in first-out), where elements are inserted into one end of the container and extracted
from the other.

queues are implemented as containers adaptors, which are classes that use an
encapsulated object of a specific container class as its underlying container, providing a
specific set of member functions to access its elements. Elements are pushed into
the "back" of the specific container and popped from its "front".

The underlying container may be one of the standard container class template or some
other specifically designed container class. The only requirement is that it supports the
following operations:

      front()
      back()
      push_back()
      pop_front()


Therefore, the standard container class templates deque and list can be used. By default, if
no container class is specified for a particular queue class, the standard container class
template deque is used.




Kevin Dulay III                                                          Lleif Christian Binasoy
Hazel Joy Paguyo                                                         Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
              MIDTERM REQUIREMENT



In their implementation in the C++ Standard Template Library, queues take two template
parameters:
 template < class T, class Container = deque<T> > class queue;




Kevin Dulay III                                                     Lleif Christian Binasoy
Hazel Joy Paguyo                                                    Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
                 MIDTERM REQUIREMENT




4.Pointers

A pointer is a variable that is used to store a memory address. The address is the
location of the variable in the memory. Pointers help in allocating memory
dynamically. Pointers improve execution time and saves space. Pointer points to a
particular data type. The general form of declaring pointer is:-


       type *variable_name;


type is the base type of the pointer and variable_name is the name of the variable of
the pointer. For example,


       int *x;


x is the variable name and it is the pointer of type integer.


Pointer Operators


There are two important pointer operators such as ‘*’ and ‘&’. The ‘&’ is a unary
operator . The unary operator returns the address of the memory where a variable is
located. For example,


       int x*;
       int c;
       x=&c;




Kevin Dulay III                                                   Lleif Christian Binasoy
Hazel Joy Paguyo                                                  Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
                 MIDTERM REQUIREMENT


variable x is the pointer of the type integer and it points to location of the variable c.
When the statement


                 x=&c;


is executed, ‘&’ operator returns the memory address of the variable c and as a
result x will point to the memory location of variable c.


The ‘*’ operator is called the indirection operator . It returns the contents of the
memory location pointed to. The indirection operator is also called deference
operator. For example,


       int x*;
       int c=100;
       int p;
       x=&c;
       p=*x;


variable x is the pointer of integer type. It points to the address of the location of the
variable c. The pointer x will contain the contents of the memory location of variable
c. It will contain value 100. When statement


                 p=*x;


is executed, ‘*’ operator returns the content of the pointer x and variable p will
contain value 100 as the pointer x contain value 100 at its memory location. Here is
a program which illustrates the working of pointers.


Kevin Dulay III                                                       Lleif Christian Binasoy
Hazel Joy Paguyo                                                      Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
                 MIDTERM REQUIREMENT




#include<iostream>
using namespace std;


int main ()
{
       int *x;
       int c=200;
       int p;
       x=&c;
       p=*x;
       cout << " The address of the memory location of x : " << x << endl;
       cout << " The contents of the pointer x : " << *x << endl;
       cout << " The contents of the variable p : " << p << endl;
       return(0);
}


The result of the program is:-




Kevin Dulay III                                                     Lleif Christian Binasoy
Hazel Joy Paguyo                                                    Joanna Katrin Corpuz
IT 211 DATA STRUCTURES
              MIDTERM REQUIREMENT




Kevin Dulay III                        Lleif Christian Binasoy
Hazel Joy Paguyo                       Joanna Katrin Corpuz

More Related Content

PDF
Array data structure
PPTX
Queue Implementation Using Array & Linked List
PPTX
Array operations
PDF
Data Structure using C
PPT
Linked list
PPTX
Binary search
PPTX
C++ programming (Array)
PPSX
Algorithm and Programming (Searching)
Array data structure
Queue Implementation Using Array & Linked List
Array operations
Data Structure using C
Linked list
Binary search
C++ programming (Array)
Algorithm and Programming (Searching)

What's hot (20)

DOCX
Report 02(Binary Search)
PPTX
Hashing Techniques in Data Structures Part2
PPT
Arrays in c
PPTX
Arrays in Data Structure and Algorithm
PPT
Strings
PPTX
Python array
PPTX
Rahat &amp; juhith
PPTX
Array in c programming
PDF
Unit - 2.pdf
PDF
Arrays in python
PPTX
Java - Collections framework
PPT
Counting sort(Non Comparison Sort)
PPT
Lecture 1 data structures and algorithms
PPTX
Arrays In C++
PPTX
Linear and Binary search
PPTX
Trees (data structure)
DOCX
Data Structures Using C Practical File
PPTX
Arrays in java
PPTX
An Introduction to Tuple List Dictionary in Python
PPTX
Hashing in datastructure
Report 02(Binary Search)
Hashing Techniques in Data Structures Part2
Arrays in c
Arrays in Data Structure and Algorithm
Strings
Python array
Rahat &amp; juhith
Array in c programming
Unit - 2.pdf
Arrays in python
Java - Collections framework
Counting sort(Non Comparison Sort)
Lecture 1 data structures and algorithms
Arrays In C++
Linear and Binary search
Trees (data structure)
Data Structures Using C Practical File
Arrays in java
An Introduction to Tuple List Dictionary in Python
Hashing in datastructure
Ad

Viewers also liked (7)

DOC
Student record
PPT
មេរៀនៈ Data Structure and Algorithm in C/C++
PPTX
Data Structures - Lecture 7 [Linked List]
PPTX
Data structure and its types
PPTX
STACKS IN DATASTRUCTURE
PPT
DATA STRUCTURES
PPSX
Data Flow Diagram Example
Student record
មេរៀនៈ Data Structure and Algorithm in C/C++
Data Structures - Lecture 7 [Linked List]
Data structure and its types
STACKS IN DATASTRUCTURE
DATA STRUCTURES
Data Flow Diagram Example
Ad

Similar to Data structures / C++ Program examples (20)

PDF
CBSE Question Paper Computer Science with C++ 2011
PPTX
ICT Lecture 3 introduction to ICT and computer.pptx
DOCX
compiler_yogesh lab manual graphic era hill university.docx
PDF
computer science sample papers 2
PDF
Computer science-2010-cbse-question-paper
DOC
project report in C++ programming and SQL
PPTX
Opject Oriented Brogramming - WHat is that?
DOCX
C++ program: All tasks .cpp
PPTX
Programming - Marla Fuentes
DOCX
Cs pritical file
DOC
Data structure
DOCX
Type header file in c++ and its function
PDF
2 1. variables & data types
PPT
Lecture03
PDF
c++ practical Digvajiya collage Rajnandgaon
PDF
C++ Chapter I
DOCX
lab03build.bat@echo offclsset DRIVE_LETTER=1set.docx
PDF
Ds lab handouts
PPTX
Example Programs of CPP programs ch 1.pptx
PPT
FP 201 Unit 2 - Part 2
CBSE Question Paper Computer Science with C++ 2011
ICT Lecture 3 introduction to ICT and computer.pptx
compiler_yogesh lab manual graphic era hill university.docx
computer science sample papers 2
Computer science-2010-cbse-question-paper
project report in C++ programming and SQL
Opject Oriented Brogramming - WHat is that?
C++ program: All tasks .cpp
Programming - Marla Fuentes
Cs pritical file
Data structure
Type header file in c++ and its function
2 1. variables & data types
Lecture03
c++ practical Digvajiya collage Rajnandgaon
C++ Chapter I
lab03build.bat@echo offclsset DRIVE_LETTER=1set.docx
Ds lab handouts
Example Programs of CPP programs ch 1.pptx
FP 201 Unit 2 - Part 2

More from Kevin III (6)

PPTX
Ang Pananaliksik at Mananliksik -Filipino 002
PPT
Employment of ict graduates in region 2
PPTX
History of Zynga
PPTX
Confirmation ppt report
PPTX
Organizational communication english reporrt
PDF
Introduction to Aptana
Ang Pananaliksik at Mananliksik -Filipino 002
Employment of ict graduates in region 2
History of Zynga
Confirmation ppt report
Organizational communication english reporrt
Introduction to Aptana

Recently uploaded (20)

PDF
Computing-Curriculum for Schools in Ghana
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Cell Types and Its function , kingdom of life
PPTX
Pharma ospi slides which help in ospi learning
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Complications of Minimal Access Surgery at WLH
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Lesson notes of climatology university.
PPTX
Cell Structure & Organelles in detailed.
Computing-Curriculum for Schools in Ghana
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Microbial disease of the cardiovascular and lymphatic systems
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPH.pptx obstetrics and gynecology in nursing
Cell Types and Its function , kingdom of life
Pharma ospi slides which help in ospi learning
Sports Quiz easy sports quiz sports quiz
Module 4: Burden of Disease Tutorial Slides S2 2025
human mycosis Human fungal infections are called human mycosis..pptx
Anesthesia in Laparoscopic Surgery in India
Complications of Minimal Access Surgery at WLH
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
O7-L3 Supply Chain Operations - ICLT Program
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Lesson notes of climatology university.
Cell Structure & Organelles in detailed.

Data structures / C++ Program examples

  • 1. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT
  • 2. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT 1. Write a program to enter the name and votes of 5 candidates. The program should display each candidate’s name, votes and percentage of votes. The program should also declare the winner. #include <string> #include<iostream> using namespace std; class ElectionResults { public: string name; int votes; }; int main() { ElectionResults res[5]; int voteTotal = 0; int winner = 0; int byVotes = 0; float percent = 0.0; for(int i = 0; i < 5; i++) { cout << "Enter Last Name of Candidate "<<i+1<<" : "; cin >> res[i].name; cout<<"Enter the Votes Received for Candidate "<<i+1<< ": "; cin >> res[i].votes; cout<<"--------------------------------------------------------"<<endl; voteTotal += res[i].votes; if( res[i].votes > byVotes) winner = i; } Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 3. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT cout<<"Name of candidatetVotes receivedtPercentage"<<endl; for(int i = 0; i < 5; i++) { cout<<res[i].name<<"ttt"<< res[i].votes <<"ttt"<<(res[i].votes*100)/voteTotal << "%." <<endl; } cout<<"nTotal Votes: "<<voteTotal<<endl; cout << "The Winner is:" << res[winner].name<<endl; cin >> voteTotal; } Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 4. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT 2. STRINGS a. Write a program to accept and display the number of letters, words and sentences of a text input. #include <iostream> #include <string> #include <cctype> using namespace std; int main(){ string userInput; char myChar; int words = 1; int sentences = 0; int paragraphs = 1; cout << "Enter some text: "; getline (cin, userInput); for (int i = 0; i <int(userInput.length()); i++) { myChar = userInput.at(i); /*if (userInput[i] == isascii(NUL)) { words --; paragraphs --; }*/ if (userInput[i] == ' ') words++; if (userInput[i] == '.') sentences++; if (userInput[i] == 'n' && userInput[i] == 't') paragraphs++; } cout << "words: " << words << endl; cout << "sentences: " << sentences << endl; cout << "paragraphs: " << paragraphs <<endl; int p; cin >> p; return 0; } Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 5. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT b. Write a program to determine if a word is palindrome #include<iostream.h> #include<string.h> int main() { char str[25],str1[25]; cout<<"Enter a string: "; gets(str); strcpy(str1,str); strrev(str); if(strcmp(str,str1)!=0) { cout<<"string is not palindrome"; } else { cout<<"string is a palindrome"; } cout<<endl; cin.get(); return 0; } Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 6. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT 3. RECURSION Write a program to convert a binary number to its decimal equivalent using a recursive function. //BINARY TO DECIMAL #include <iostream> #include <math.h> using namespace std; int sum = 0; using namespace std; int BinaryToDecimal (int BinaryNumber, int weight); int main(){ int bitWeight; int binaryNum; bitWeight = 0; cout<<"======CONVERTING BINARY TO DECIMAL======="<<endl; cout<<"Enter the Binary Number: "; cin>>binaryNum; cout<<"n"; int sum = BinaryToDecimal (binaryNum, bitWeight); cout<<"The Decimal Equivalent of inputed Binary is: "<<sum<<endl; system("PAUSE"); return 0; } int BinaryToDecimal (int BinaryNumber, int weight) { int bit; if (BinaryNumber>0){ bit = BinaryNumber % 10; sum = sum + bit * pow (2, weight); BinaryNumber = BinaryNumber /10; weight++; BinaryToDecimal (BinaryNumber, weight); { return sum; } } } Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 7. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT //DECIMAL TO BINARY #include <iostream> using namespace std; void binary(int); int main(void) { int number; cout << "Please enter a positive integer: "; cin >> number; if (number < 0) cout << "That is not a positive integer.n"; else { cout << number << " converted to binary is: "; binary(number); cout << endl; } } void binary(int number) { int remainder; if(number <= 1) { cout << number; return; } remainder = number%2; binary(number >> 1); cout << remainder; cin.get(); } Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 8. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT LECTURE REQUIREMENTS Research on the definitions, C++ implementation, and program examples of the following:  Stack  Lists  Queues  Pointers 1. Stack LIFO stack Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from the end of the container. stacks are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack. The underlying container may be any of the standard container class templates or some other specifically designed container class. The only requirement is that it supports the following operations:  back()  push_back()  pop_back() Therefore, the standard container class templates vector, deque and list can be used. By default, if no container class is specified for a particular stack class, the standard container class template deque is used. In their implementation in the C++ Standard Template Library, stacks take two template parameters: template < class T, class Container = deque<T> > class stack; Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 9. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT Where the template parameters have the following meanings:  T: Type of the elements.  Container: Type of the underlying container object used to store and access the elements. Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 10. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT 2. LISTS Lists are a kind of sequence container. As such, their elements are ordered following a linear sequence. List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they contain in different and unrelated storage locations. The ordering is kept by the association to each element of a link to the element preceding it and a link to the element following it. This provides the following advantages to list containers:  Efficient insertion and removal of elements before any other specific element in the container (constant time).  Efficient moving elements and block of elements within the container or even between different containers (constant time).  Iterating over the elements in forward or reverse order (linear time). Compared to other base standard sequence containers (vectors and deques), lists perform generally better in inserting, extracting and moving elements in any position within the container for which we already have an iterator, and therefore also in algorithms that make intensive use of these, like sorting algorithms. The main drawback of lists compared to these other sequence containers is that they lack direct access to the elements by their position; For example, to access the sixth element in a list one has to iterate from a known position (like the beginning or the end) to that position, which takes linear time in the distance between these. They also consume some extra memory to keep the linking information associated to each element (which may be an important factor for large lists of small-sized elements). Storage is handled automatically by the list object, allowing it to be expanded and contracted automatically as needed. In their implementation in the C++ Standard Template Library lists take two template parameters: template < class T, class Allocator = allocator<T> > class list; Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 11. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT Where the template parameters have the following meanings:  T: Type of the elements.  Allocator: Type of the allocator object used to define the storage allocation model. By default, theallocator class template for type T is used, which defines the simplest memory allocation model and is value-independent. In the reference for the list member functions, these same names are assumed for the template parameters. Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 12. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT 3.Queues FIFO queue queues are a type of container adaptor, specifically designed to operate in a FIFO context (first-in first-out), where elements are inserted into one end of the container and extracted from the other. queues are implemented as containers adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are pushed into the "back" of the specific container and popped from its "front". The underlying container may be one of the standard container class template or some other specifically designed container class. The only requirement is that it supports the following operations:  front()  back()  push_back()  pop_front() Therefore, the standard container class templates deque and list can be used. By default, if no container class is specified for a particular queue class, the standard container class template deque is used. Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 13. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT In their implementation in the C++ Standard Template Library, queues take two template parameters: template < class T, class Container = deque<T> > class queue; Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 14. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT 4.Pointers A pointer is a variable that is used to store a memory address. The address is the location of the variable in the memory. Pointers help in allocating memory dynamically. Pointers improve execution time and saves space. Pointer points to a particular data type. The general form of declaring pointer is:- type *variable_name; type is the base type of the pointer and variable_name is the name of the variable of the pointer. For example, int *x; x is the variable name and it is the pointer of type integer. Pointer Operators There are two important pointer operators such as ‘*’ and ‘&’. The ‘&’ is a unary operator . The unary operator returns the address of the memory where a variable is located. For example, int x*; int c; x=&c; Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 15. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT variable x is the pointer of the type integer and it points to location of the variable c. When the statement x=&c; is executed, ‘&’ operator returns the memory address of the variable c and as a result x will point to the memory location of variable c. The ‘*’ operator is called the indirection operator . It returns the contents of the memory location pointed to. The indirection operator is also called deference operator. For example, int x*; int c=100; int p; x=&c; p=*x; variable x is the pointer of integer type. It points to the address of the location of the variable c. The pointer x will contain the contents of the memory location of variable c. It will contain value 100. When statement p=*x; is executed, ‘*’ operator returns the content of the pointer x and variable p will contain value 100 as the pointer x contain value 100 at its memory location. Here is a program which illustrates the working of pointers. Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 16. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT #include<iostream> using namespace std; int main () { int *x; int c=200; int p; x=&c; p=*x; cout << " The address of the memory location of x : " << x << endl; cout << " The contents of the pointer x : " << *x << endl; cout << " The contents of the variable p : " << p << endl; return(0); } The result of the program is:- Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz
  • 17. IT 211 DATA STRUCTURES MIDTERM REQUIREMENT Kevin Dulay III Lleif Christian Binasoy Hazel Joy Paguyo Joanna Katrin Corpuz