DATA STRUCTURE WITH C++ PROGRAMMING USING ARRAY AND QUEUE
Fact: As architectural design precedes building a house so does SYNTAX precedes programming or coding.
Invariably, you must learn and master the syntax of each construct in a programming language such as variable declaration, initialization, data structure manipulation, loop, selection statement to mention but few, before you start writing the code to solve a problem through the syntax application.
What are data structures?
Data structures are structures or formats used to organize, store, access, modify and manipulate data elements. The type of problem you are solving will determine the type of data structure you will use.
Datatypes in C++
The datatypes in C++ are categorized as:
Primitive: They are inbuilt datatypes within C++ and can only store one value at a time; such as int, string, float, double, char, boolean, void
Derived: They are made up of the primitive datatypes and they can store more than one value; such as array, function, pointer, reference.
User defined datatype: They are customized datatypes created by the programmer in the course of solving a problem; such as class and object, struct (structure), typedef, enum, union,
Category of data structures
Linear data structures: data elements are arranged in a sequential manner. Examples are arrays, stacks, linked list, queues, hash table (just like dictionary in Python).
Non-linear data structures: data elements are not arranged in a sequential manner but they are arranged at different levels. Examples are graphs, trees, heap
The section below will give a detail overview of each data structures in C++ with program examples.
DS-1: ARRAY
Array is a linear data structure that uses one variable to store or hold multiple data elements with the same datatype.
Terms use in array
array element: it represent the data in the array
array size: it determines the total element in an array
array index: it is use for specifying the position of each or any particular element in the array
square bracket: it does double function, it is used to wrap array size and is also used to wrap array index.
Types of array
One dimensional array (1D array)
Two dimensional array (2D array)
Multi dimensional array (N array)
One dimensional array (1D array)
image
The image above indicate a 1D array, on the left, we have three (3) integer elements while on the right we have two (2) string elements stored in the array respectively in a sequential order.
array declaration
datatype arrayName[arraySize];
example: int score[3];
array initialization
arrayName[arraySize] = value;
example: int score[0] = 5 //store value 5 in the first position of the array
array declaration and initialization (2-in-1)
datatype arrayName[arraySize] = {value1, value2,...,valueN};
example: string fruits[2] = {"apple", "mango"};
aliter (without specifying the array size, the C++ compiler will count the elements in the curly brace to determine the array size)
example: string fruits[] = {"apple", "mango"};
Printing the output of an array
We print the output of the array by traversing the array elements. This means you can visit the elements one by one using the array index, or any order you want, depending on the condition being specified.
To print the elements stored in an array, you can use simple for loop, ranged for loop or iterator.
PRACTICE
1. Declare a 1D array of 7 float elements for cgpa variable
answer: float cgpa[7];
2. Declare a 1D float elements array cgpa variable and store three (3) different cgpas
answer: float[3] = {3.2, 4.5, 4.99};
3. Declare an array of 250 character elements for comment variable
answer: char comment[250];
Two dimensional array (2D array)
array declaration
datatype arrayName[rowSize][columnSize];
example: int stdgrade[4][2];
this above example will store 4*2 elements that is, 8 elements.
PRACTICE
1. Declare a 2D array of integers for 4 student names and 2 scores each
answer: int stdgrade[4][2];
2. Write a runnable C++ program using 1D array to store the scores of ten(1) students and print their names using ranged for loop. You should also print the fifth and ninth element in the array container.
CASE 1A: ONE DIMENSIONAL ARRAY
Phase 1
Problem: A non-interactive program using array to store and display four different integer elements
top-down analysis (Algorithm)
step 1: declare and initialize an array integer variable score to store four (4) different elements
step 2: use for loop and declare integer variable xcount to traverse the userfruit from index 0 to N-1. userfruits[xcount] for user action.
step 4: use index to print a particular element in the array
step 4: use for loop to print the initialized scores
//CODE IMPLEMENTATION
#include<iostream>
using namespace std;
int main(){
//declare and initialize array with 4 elements
int score[4] = {80, 87, 93, 90};
//aliter
//int score[] = {80, 87, 93, 90};
//access the third element
cout<<"\nThe third element is:: "<<score[2]<<endl;
//output headline or title
cout<<"\nAll the elements in the array are:: ";
//process the display of all elements using loop
for(int xcount = 0; xcount<3; xcount++){
cout<<"\nScore: "<<score[xcount];
//aliter
//cout<<score[xcount]<<" ";
}
return 0;
}
OUTPUT
HINT: In int score[] = {80, 87, 93, 90}; you might decide not to specify the array size, here, the compiler will automatically count the number of elements in the curly brace and determine the array size.
In cout<<score[xcount]<<" "; each number will be displayed with a space in between the progression.
Phase 2
Problem: A non-interactive program using array to store and display three different string object elements
//CODE IMPLEMENTATION
#include<iostream>
using namespace std;
int main(){
//declare and initialize array with 4 elements
string fruits[3] = {"apple", "watermelon", "mango"};
//access the first element
cout<<"\nThe first element is:: "<<fruits[0]<<endl;
//output headline or title
cout<<"\nAll the elements in the array are:: ";
//process the display of all elements using loop
for(int xcount = 0; xcount<3; xcount++){
cout<<"\nFruit: "<<fruits[xcount];
}
return 0;
}
Phase 3
Problem: An interactive program using array to read, store and display N elements entered by the user
top-down analysis (Algorithm)
step 1: declare integer variable ncount for number of elements to read
step 2: declare integer variable usefruit with maximum size of your choice, here we use 100 (you can use any other value)
step 3: use for loop and declare integer variable xcount to traverse the userfruit from index 0 to N-1. userfruits[xcount] for user action.
step 4: show how the userinput increases by 1 (xcount + 1)
step 5: use for loop to print the fruits entered by the user.
//CODE IMPLEMENTATION
#include<iostream>
using namespace std;
int main(){
int ncount;
string userfruits[100];
//first user action
cout<<"\nEnter the total number of elements:: ";
cin>>ncount;
cout<<"You entered "<<ncount<<" elements"<<endl;
//second user action
for(int xcount = 0; xcount<ncount; xcount++){
cout<<"Enter fruit "<<xcount+1<<" ::";
cin>>userfruits[xcount];
}
//output headline or title
cout<<"\nAll the elements in the array are:: ";
//process the display of all elements using loop
for(int xcount = 0; xcount<ncount; xcount++){
cout<<"\nFruit: "<<userfruits[xcount];
}
return 0;
}
OUTPUT
Phase 4
Problem: An interactive program using array to read, store and display N elements entered by the user, then find the total
top-down analysis (Algorithm)
step 1: declare integer variable ncount for number of elements to read
step 2: declare integer variable userinput with maximum size of your choice, here we use 100
step 3: declare integer variable sum and initialize it to 0. The sum will store sum of elements of array
step 4: use for loop and declare integer variable xcount to traverse the userinput from index 0 to N-1\
step 5: show how the userinput increases by 1 (xcount + 1)
step 6: for any index xcount, add the value of element at index xcount to sum. sum = sum + userinput[xcount]
step 7: display the variable sum
//CODE IMPLEMENTATION
#include<iostream>
using namespace std;
int main(){
int ncount, sum;
int userinput[100];
//first user action
cout<<"Enter the total number of elements:: ";
cin>>ncount;
cout<<"You entered "<<ncount<<" elements<<endl";
//second user action
for(int xcount = 0; xcount<ncount; xcount++){
cout<<"Enter value "<<xcount+1<<" ::";
cin>>userinput[xcount];
}
//initialize sum
sum = 0;
//process the summation of all elements using loop
for(int xcount = 0; xcount<ncount; xcount++){
sum += userinput[xcount];
}
//output headline or title or descriptive statement
cout<<"\nThe sum of the elements in the array are:: "<<sum;
return 0;
}
OUTPUT
CASE 1B: TWO DIMENSIONAL ARRAY
In this section, we will learn how to work with 2-dim array.
Phase 5
Problem: Use an array data structure to write a runnable C++ program to read and print the position and points of four (4) premier league teams namely: Manchester City, Chelsea, Brentford and Southampton for 2022-23 season. Use escape sequence to format the table outlook, let there be a header, position should be left justified and point should be right justified.
//CODE IMPLEMENTATION
#include <iostream>
using namespace std;
int main() {
//row is 4, then 4-1 = 3, hence r =3; while the table will have two columns, hence c=2
int premier[3][2];
int totalteam = 4;
for (int xcount=0; xcount<totalteam; xcount++) {
cout<<"\n Enter position and points for 4 teams:: ";
cin>>premier[xcount][0];
cin>>premier[xcount][1];
}
//output header
cout<<"Position"<<"\tPoints";
cout<<"\n---------------------------";
// displaying output
for(int xcount=0; xcount<totalteam; xcount++){
cout<<"\n"<<premier[xcount][0]<<"\t\t"<<premier[xcount][1];
}
return 0;
}
OUTPUT
Phase 6
Problem: Write a runnable C++ program that will read and save two (2) test scores (course 1, course 2) for four (4) students in a 2D array and then output the data in a table.
create an array of strings of size 4 called numofstd[], initialize the array with any students of your choice.
create a 2D array of integers of 4 rows and 2 columns called numofscore[][]. Read in the scores for each student. Each row for this array will contain the test scores for each student. For example, Student Names Course 1 Course 2; while scores will be contained in stdscore[0][0], stdscore[0][1] and so on.
In nested for loops, print the names of the students along with their scores. The student names should be left justified and the test scores should be right justified.
//CODE IMPLEMENTATION
#include <iostream>
#include <iomanip> //to handle setw() set width
using namespace std;
int main() {
//declare constant values for the total elements using const keyword
const int numofstd = 4, numofscore = 2;
int stdscore[numofstd][numofscore];
//declare and initialize the array
string stdname[numofstd] = {"dmactutor", "togun oreoluwa", "david nathan", "biola ajala"};
//loop through array using nested for loop for user action to read the score
cout<<"Enter the score of the student:: "<<endl;
for(int xcount = 0; xcount<numofstd; xcount++){
for(int ycount = 0; ycount<numofscore; ycount++){
cin>>stdscore[xcount][ycount];
}
}
//output table headers
cout<<"Student Names"<<"\tCourse 1"<<"\tCourse 2";
cout<<"\n---------------------------------------"<<endl;
//loop through array using nested for loop to ouptut the names and grades in the table
for(int xcount = 0; xcount<numofstd; xcount++){
//cout<<"\n"<<stdname[xcount]<<setw(10);
cout<<"\n"<<stdname[xcount]<<"\t";
for(int ycount = 0; ycount<numofscore; ycount++){
//cout<<stdscore[xcount][ycount]<<setw(15);
cout<<stdscore[xcount][ycount]<<"\t\t";
}
}
return 0;
}
OUTPUT
Phase 7: Work in progress to handle student name and matric number. The table format is not generating what I want yet.
//CODE IMPLEMENTATION
#include <iostream>
#include <iomanip> //to handle setw() set width
using namespace std;
int main() {
//declare constant values for the total elements using const keyword
//it represent 2 rows and 2 columns ## 2*2 = 4 data elements in that table
const int numofrow = 2, numofcol = 2;
string sdetail[numofrow][numofcol];
//loop through array using nested for loop for user action to read the name and matric of students
cout<<"Enter the name and matric of the student:: "<<endl;
for(int xcount = 0; xcount<numofrow; xcount++){
for(int ycount = 0; ycount<numofcol; ycount++){
cin>>sdetail[xcount][ycount];
}
}
//output table headers
cout<<"Student Names"<<"\tMatric Number";
cout<<"\n---------------------------------------"<<endl;
//loop through array using nested for loop to ouptut the names and matric in the table
for(int xcount = 0; xcount<numofrow; xcount++){
for(int ycount = 0; ycount<numofcol; ycount++){
//cout<<sdetail[xcount][ycount]<<setw(15);
cout<<sdetail[xcount][ycount]<<" "<<"\n";
}
}
return 0;
}
PHASE 8: Demonstrating array as a fixed size container
Problem: Write a runnable C++ program using 1D array each to store the score and names of 3 students. Print their names and scores using loop. Then append two (2) student names and scores during the compilation of the program (HINT: to append, you should declare variables that will prompt the user to enter a value of their choice)
//demonstrating array as a fixed sized container
#include<iostream>
#include<string>
using namespace std;
int main(){
//array to store the names and scores of the students
//if you add five elements here and decide to append extra element,
//the new elements will not be added because array is of fixed size
string names[5] = {"dmactutor", "david", "daniel"};
int scores[5] = {90, 91, 96};
//header
cout<<"S/N \t\t Student Names\t Scores"<<endl;
//iterate the array and display first three elements
for(int xcount=0; xcount<3; xcount++){
//format the output
cout<<"Student "<<xcount+1 <<"\t" <<names[xcount]<<"\t\t" <<scores[xcount]<<endl;
}
cout<<"\n\n";
//ask user to enter two extra scores
int s1, s2;
string n1, n2;
cout<<"Enter next name:: ";
cin>>n1;
cout<<"Enter first score:: ";
cin>>s1;
cout<<"Enter next name:: ";
cin>>n2;
cout<<"Enter second score:: ";
cin>>s2;
//append the two scores
names[3] = n1;
names[4] = n2;
scores[3] = s1;
scores[4] = s2;
cout<<"\n\n";
//header
cout<<"Newly Added information"<<endl;
//print the new scores
//header
cout<<"S/N \t\t Student Names\t Scores"<<endl;
//iterate the array
for(int xcount=0; xcount<5; xcount++){
//format the output
cout<<"Student "<<xcount+1 <<"\t" <<names[xcount]<<"\t\t" <<scores[xcount]<<endl;
}
return 0;
}
DS-2 QUEUE
phase 1:
Basic operations that can be performed on queue are insertion, display, deletion etc.
Problem: Write a C++ program using modular programming (modularization) to implement the basic operation of QUEUE such as insert, display and delete element. Also check for overflow and underflow conditions.
top-down analysis (algorithm)
NB: The main() body function will be the first to get executed in any C++ program, that is, that is where execution begins
step 1: import header files and set up C++ boiler plate code
step 2: declare array int queue[150], variables and initialize rear = -1, front = -1 indicate queue is empty just like sum = 0;
step 3: declare method xinsert(), xdisplay(), xdelete()
step 4: within main() function, display the options, declare and create switch statement where each method will be called based on the number selected by the user
step 5: outside the main() function, declare and create the functionalities for functions: xinsert(), xdisplay(), xdelete()
Explanation of functions: xinsert(), xdisplay(), xdelete() are stated below
functionality of xinsert() method (insert element from the rear / back)
declare val variable to store inserted value
check queue is full or not
if queue is full display the message
hence, if queue is empty
pointer goes to first location
display user action and read inserted value into the queue from the rear side
finally, rear point to a location in the queue
functionality of xdisplay() method (print all elements in the queue)
check if queue is empty, if empty, display message that queue is empty
hence, if queue is not empty, use for loop to traverse the elements in the queue for printing
functionality of xdelete() method (delete element at the front)
check if front or rear of the queue is empty, if empty deletion cannot take place
if queue has element, deletion can take place
//CODE IMPLEMENTATION
#include <iostream>
using namespace std;
int queue[150], n=150, front=-1, rear=-1;
void xinsert();
void xdisplay();
void xdelete();
int main() {
int choice;
//display menu option
cout<<"\t_________\n\n";
cout<<"\tWeclcome to the QUEUE PAGE\n\n"<<endl;
cout<<"\t_________ MENU __________\n\n";
cout<<"\t | --Press 1 to INSERT-- | "<<endl;
cout<<"\t | --Press 2 to DISPLAY-- | "<<endl;
cout<<"\t | --Press 3 for DELETE -- | "<<endl;
cout<<"\t | --Press 4 to EXIT APPLICATION-- | "<<endl;
//display user action
cout<<"\n\t --Enter your choice-- | ";
//accept input
cin>>choice;
//menu to select
switch(choice){
case 1:
xinsert();
break;
case 2:
xdisplay();
break;
case 3:
xdelete();
break;
case 4:
cout<<"\t --Thank You-- "<<endl;
break;
default:
system("cls"); //to clear the screen
cout<<"\t --Please check the selected option \n Try again-- "<<endl;
main(); //take control to the main body
}
return 0;
}
void xinsert(){
//insert data
int val;
if(rear == n-1)
cout<<"queue is overflow"<<endl;
else{
if(front==-1)
front=0;
cout<<"Insert the element in queue:: "<<endl;
cin>>val;
rear++;
queue[rear] = val;
}
main();
}
void xdisplay(){
//display data
if(front == -1)
cout<<"queue is empty"<<endl;
else{
cout<<"Inserted elements in the queue are:: "<<endl;
for(int xcount=front; xcount<=rear;xcount++)
cout<<queue[xcount]<<" "<<endl;
}
main();
}
void xdelete(){
//delete data
if(front == -1 || front > rear){
cout<<"queue is underflow";
return;
}
else{
cout<<"Deleted element in the queue is:: "<<endl;
cout<<queue[front]<<endl;
front++;
}
main();
}
CODE OUTPUT
Comments
Post a Comment