SlideShare a Scribd company logo
1 of 17
Download to read offline
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

What's hot

Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Languagepandey3045_bit
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and SetsNicole Ryan
 
Pointer to array and structure
Pointer to array and structurePointer to array and structure
Pointer to array and structuresangrampatil81
 
Unit 2 linked list and queues
Unit 2   linked list and queuesUnit 2   linked list and queues
Unit 2 linked list and queueskalyanineve
 
MySQL developing Store Procedure
MySQL developing Store ProcedureMySQL developing Store Procedure
MySQL developing Store ProcedureMarco Tusa
 
Estrutura de Dados - Aula 02 - Estrutura de Dados e TAD
Estrutura de Dados - Aula 02 - Estrutura de Dados e TADEstrutura de Dados - Aula 02 - Estrutura de Dados e TAD
Estrutura de Dados - Aula 02 - Estrutura de Dados e TADLeinylson Fontinele
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in pythonhydpy
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional arrayRajendran
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)Elavarasi K
 
Chapter 5 data processing
Chapter 5 data processingChapter 5 data processing
Chapter 5 data processingUMaine
 
Library Management system Database queries
Library Management system Database queriesLibrary Management system Database queries
Library Management system Database queriesreshmajohney
 
JNDI Data source Setup in Glassfish Server
JNDI Data source Setup in Glassfish ServerJNDI Data source Setup in Glassfish Server
JNDI Data source Setup in Glassfish ServerSuman Behara
 

What's hot (20)

Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
Data structures chapter 1
Data structures chapter  1Data structures chapter  1
Data structures chapter 1
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Pointer to array and structure
Pointer to array and structurePointer to array and structure
Pointer to array and structure
 
Unit 2 linked list and queues
Unit 2   linked list and queuesUnit 2   linked list and queues
Unit 2 linked list and queues
 
MySQL developing Store Procedure
MySQL developing Store ProcedureMySQL developing Store Procedure
MySQL developing Store Procedure
 
Data Structures
Data StructuresData Structures
Data Structures
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Nodejs buffers
Nodejs buffersNodejs buffers
Nodejs buffers
 
Estrutura de Dados - Aula 02 - Estrutura de Dados e TAD
Estrutura de Dados - Aula 02 - Estrutura de Dados e TADEstrutura de Dados - Aula 02 - Estrutura de Dados e TAD
Estrutura de Dados - Aula 02 - Estrutura de Dados e TAD
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Apostila C ANSI
Apostila C ANSIApostila C ANSI
Apostila C ANSI
 
Data warehouse testing
Data warehouse testingData warehouse testing
Data warehouse testing
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 
Chapter 5 data processing
Chapter 5 data processingChapter 5 data processing
Chapter 5 data processing
 
Linked list
Linked listLinked list
Linked list
 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
 
Library Management system Database queries
Library Management system Database queriesLibrary Management system Database queries
Library Management system Database queries
 
JNDI Data source Setup in Glassfish Server
JNDI Data source Setup in Glassfish ServerJNDI Data source Setup in Glassfish Server
JNDI Data source Setup in Glassfish Server
 

Viewers also liked

មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++Ngeam Soly
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Muhammad Hammad Waseem
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsAakash deep Singhal
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its typesNavtar Sidhu Brar
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTUREArchie Jamwal
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURESbca2010
 
Data Flow Diagram Example
Data Flow Diagram ExampleData Flow Diagram Example
Data Flow Diagram ExampleKaviarasu D
 

Viewers also liked (8)

Student record
Student recordStudent record
Student record
 
មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++មេរៀនៈ Data Structure and Algorithm in C/C++
មេរៀនៈ Data Structure and Algorithm in C/C++
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithms
 
Data structure and its types
Data structure and its typesData structure and its types
Data structure and its types
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
 
Data Flow Diagram Example
Data Flow Diagram ExampleData Flow Diagram Example
Data Flow Diagram Example
 

Similar to Data structures / C++ Program examples

So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfarjuncollection
 
Virtual function
Virtual functionVirtual function
Virtual functionharman kaur
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperDeepak Singh
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101premrings
 
Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Deepak Singh
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - ReferenceMohammed Sikander
 
introductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdfintroductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdfSameerKhanPathan7
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfaathiauto
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxDeepasCSE
 
Oops practical file
Oops practical fileOops practical file
Oops practical fileAnkit Dixit
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxShashiShash2
 

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

C++ practical
C++ practicalC++ practical
C++ practical
 
Computer Programming- Lecture 10
Computer Programming- Lecture 10Computer Programming- Lecture 10
Computer Programming- Lecture 10
 
C++ file
C++ fileC++ file
C++ file
 
C++ file
C++ fileC++ file
C++ file
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdf
 
Bijender (1)
Bijender (1)Bijender (1)
Bijender (1)
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
 
Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
CP 04.pptx
CP 04.pptxCP 04.pptx
CP 04.pptx
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
introductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdfintroductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdf
 
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdfDoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
DoublyList-cpp- #include -DoublyList-h- using namespace std- void Doub.pdf
 
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptxCONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
CONSTRUCTORS, DESTRUCTORS AND OPERATOR OVERLOADING.pptx
 
Oops practical file
Oops practical fileOops practical file
Oops practical file
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 

More from Kevin III

Ang Pananaliksik at Mananliksik -Filipino 002
Ang Pananaliksik at Mananliksik -Filipino 002Ang Pananaliksik at Mananliksik -Filipino 002
Ang Pananaliksik at Mananliksik -Filipino 002Kevin III
 
Employment of ict graduates in region 2
Employment of ict graduates in region 2Employment of ict graduates in region 2
Employment of ict graduates in region 2Kevin III
 
History of Zynga
History of Zynga History of Zynga
History of Zynga Kevin III
 
Confirmation ppt report
Confirmation ppt reportConfirmation ppt report
Confirmation ppt reportKevin III
 
Organizational communication english reporrt
Organizational communication english reporrtOrganizational communication english reporrt
Organizational communication english reporrtKevin III
 
Introduction to Aptana
Introduction to Aptana Introduction to Aptana
Introduction to Aptana Kevin III
 

More from Kevin III (6)

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

Recently uploaded

ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 

Recently uploaded (20)

ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 

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