Sunday, 22 November 2020

Describe the four clauses in the syntax of a simple SQL retrieval query.

 Question: 4.4. Describe the four clauses in the syntax of a simple SQL retrieval query. Show what type of constructs can be specified in each of the clauses. Which are required and which are optional?

Solution:

  1. SELECT
  2. FROM
  3. WHERE
  4. ORDER BY
  5. Limit

SELECT

List of attribute names to be received by the query

FROM

The tables that these attributes with be retrieved from

WHERE

Conditional boolean expression to identify certain tuples to be retrieved (optional)

ORDER BY

Attribute list to order the result by (optional)

LIMIT BY 

This is used to limit the number of rows (optional)

How does SQL allow implementation of the entity integrity and referential integrity constraints

 Question: 4.3. How does SQL allow implementation of the entity integrity and referential integrity constraints described in Chapter 3? What about referential triggered actions? 

Solution: 

Entity integrity

Referential integrity

Entity integrity constraints

In the entity integrity constraint, it states that no primary key value can be NULL because. Primary key value is used to identify the individual tuples in a relation. And having NULL values for the primary key implies that we cannot identify some tuples.

Referential integrity constraints

It is specified between two relations and is used to maintain the consistency among tuples in the two relations and referential integrity constraints states that, a tuple in one relation that refers to another relation and must refer to an existing tuple in that relation.

Referential triggered actions

Schema designer can specify an alternative action to taken when a referential integrity constraint is violated by attaching a referential triggered action clause to any foreign key constraint.

List the data types that are allowed for SQL attributes.

 Question: 4.2. List the data types that are allowed for SQL attributes. 

Solution:

Numeric data types

Integer numbers

  • INT
  • INTEGER
  • SMALLINT
  • BIGINT

Floating-point (real) numbers

  • REAL
  • DOUBLE
  • FLOAT

Fixed-point numbers

  • DECIMAL(n,m)
  • DEC(n,m)
  • NUMERIC(n,m)
  • NUM(n,m)

Character-string data types

Fixed length

  • CHAR(n)
  • CHARACTER(n)

Varying length

  • VARCHAR(n)
  • CHAR VARYING(n)
  • CHARACTER VARYING(n)

Long varchar

Large object data types

Characters:

CLOB

CHAR LARGE OBJECT

CHARACTER LARGE OBJECT

Bits

BLOB

BINARY LARGE OBJECT

Boolean data type

Values of TRUE or FALSE or NULL

DATE data type

Ten positions

Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD

How do the relations (tables) in SQL differ from the relations defined formally

Questions 4.1. How do the relations (tables) in SQL differ from the relations defined formally in Chapter 3? Discuss the other differences in terminology. Why does SQL allow duplicate tuples in a table or in a query result?

Solution:  SQL allows a table to have more than one tuple that are identical in all their attribute values while others don't

The reasons why SQL allows duplicate tuples are

  • Duplicate elimination is an expensive operation
  • User may want to see duplicate tuples in the result of query

Sunday, 26 July 2020

remove number 12 from the array below

Q: Which of the following represents the method used to remove number 12 from the array below?
var values=[2, 4, 6, 10, 12]
a. values.remove(at: 4)
b. values.remove(at: 12)
c. values.append(12, at: 5)
d. remove("12")

Solution: values.remove(at: 4)

The above statement is used to remove the element 12 from array by using remove(at:index) method. 12 is at the index 4 , therefore at: 4 is used

The output will be 2 4 6 10 after removing 12.

Constant, Private Data Members

Question: Do not use C++ strings (or the string library) anywhere in the Routes application, in this v.1 or in any future versions. Let's get some experience using C strings. Also, the overhead is way less in this application using C strings.

Write Routes.1.cpp, to design and test a class that represents a leg of a route between two adjacent cities. Here are the specifications for the Leg class:

1. Constant, Private Data Members

Write three private data members: the starting city, the ending city, and the distance (in miles) separating the two.

Use constant, read-only pointers to store the city names as C strings. There will be no need to ever make copies of the names -- no strcpy . Names will be declared and stored in the main program, so all that needs to be stored in the Leg object are the memory locations of those C strings.

For the distance, use any numeric data type of your choosing -- you decide on whole numbers vs floating point. It will never change, so it needs to be constant.

2. Constructor Function(s)

Include one constructor with three parameters -- the start and end cities and the distance separating them. Do not include a default constructor! There can be no "generic" or uninitialized Leg. Each Leg is very specific and constant and unchanging.

3. Getter Function(s)

Write two getters -- one to return the distance and another to produce nicely formatted output.
The output getter would have one parameter -- an ostream reference, so that output can be directed to any stream-oriented source. The "nicely formatted output" should look something like this: "Leg: San Francisco to San Jose, 20 miles" but you decide on the exact appearance.

  • The declaration of the Leg class should be like,

4. An Array Of Leg Objects

In the main program declare an array of 40 or more Leg objects, each connecting two cities of your choice. They can be any pairs of cities that you choose, but follow these rules:

  • Do not make 40 legs where each new leg starts where the preceding leg ends. That is, do not make one long list of legs following Interstate 80 from San Francisco to New York City. Instead choose major cities across the United States, connecting adjacent cities.
  • Do include at least one set of 5 legs that do form a "route" when taken end-to-end. For this to happen you'll need to spell and case the end city of one leg exactly the same as the start city for some other leg so that they "connect".
  • Use sizeof to get the size of the Leg Objects array

It's okay to estimate the distances between cities -- exactness of your numbers will not be checked. But be reasonable!

5. Sort By Distance

In the main program write a nested-for-loop sorting code block, sorting the Leg objects in the array from shortest distance to longest. This will require swapping of objects, which will require an assignment operator function in the Leg class. Because there are constant data members, you should write an assignment operator function just because it's good programming practice -- but in this case, it's required because of the swapping.

6. Output

In a loop in the main program, call the output getter on each object in the array. The output should be arranged shortest to longest, because the sorting code block should be before the output code block in the main program. Refer to sample output from Files, Assignment5Part1.pdf

Actions

7. Do Not Add To The Public Interface As Specified

Do not add getters, setters, constructors, destructors, friends, or statics to a class, other than the ones specified. If a public function name is given in the specification, spell and case it exactly. If parameters are specified, write them exactly as specified -- do not add or remove parameters or change their type.

Do not add public data members unless specified. Public variables will never be specified, although public constants might be (in a future lab assignment). If that happens, name and case them exactly as specified.

Private members don't matter -- unless specifically told not to, you may add private functions and data.

My code:

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

class Leg
{
	const char* const startCity;
	const char* const endCity;
	const double distance;
	
	public:
	Leg(const char* const, const char* const, const double);
	Leg& operator=(const Leg&);
	double getDistance() const;
	void output(ostream&) const;
};

int main() 
{
	double arr[40];
	for(int i = 0; i < 40; i++)
	{
		arr[i] = rand() % 39 + 1.45;
	}
	Leg a[ ]={
		Leg("Aberdeen","Abilene", arr[1]),Leg("Akron","Albany", arr[2]),Leg("Albuquerque","Alexandria", arr[3]),
		Leg("Allentown","Amarillo", arr[4]),Leg("Anaheim","Anchorage", arr[5]),Leg("Ann Arbor","Antioch", arr[6]),
		Leg("Apple Valley","Appleton", arr[7]),Leg("Arlington","Arvada", arr[8]),Leg("Asheville","Athens", arr[9]),
		Leg("Atlanta","Atlantic City", arr[10]),Leg("Augusta","Aurora", arr[12]),Leg("Austin","Bakersfield", arr[12]),
		Leg("Baltimore","Barnstable", arr[13]),Leg("Baton Rouge","Beaumont", arr[14]),Leg("Bel Air","Bellevue", arr[15]),
		Leg("Berkeley","Bethlehem", arr[16]),Leg("Billings","Birmingham", arr[17]),Leg("Bloomington","Boise", arr[18]),
		Leg("Boise City","Bonita Springs", arr[19]),Leg("Boston","Boulder", arr[20]),Leg("Bremerton","Brighton", arr[21]),
		Leg("Brownsville","Bryan", arr[22]),Leg("Buffalo","Burbank", arr[23]),Leg("Cambridge","Canton", arr[24]),
		Leg("Cape Coral","Carrollton", arr[25]),Leg("Cary","Cathedral City", arr[26]),Leg("Cedar Rapids","Champaign", arr[27]),
		/*Leg("Aberdeen","Abilene", arr[1]),Leg("Akron","Albany", arr[1]),Leg("Albuquerque","Alexandria", arr[1]),
		 * Leg("Aberdeen","Abilene", arr[1]),Leg("Akron","Albany", arr[1]),Leg("Albuquerque","Alexandria", arr[1]),
		 * Leg("Aberdeen","Abilene", arr[1]),Leg("Akron","Albany", arr[1]),Leg("Albuquerque","Alexandria", arr[1]),
		 * Leg("Aberdeen","Abilene", arr[1]),Leg("Akron","Albany", arr[1]),Leg("Albuquerque","Alexandria", arr[1]),
		 * Leg("Aberdeen","Abilene", arr[1])*/
		 };
		 const int SIZE = sizeof(a) / sizeof(a[0]);
		 for (int i = 0; i < SIZE; i++)
		 {
			 for (int j = i + 1; j < SIZE; j++)
			 {
				 if (arr[j] < arr[i])
				 swap(arr[j], arr[i]);
			 }
		}
}

double getDistance()
{
	return distance;
}

Leg& Leg::operator=(const Leg& copyThis) 
{
	if (this != &copyThis) 
	{
		const_cast<double&>(this->distance) = copyThis.distance;
		const_cast<const char* &>(this->startCity) = copyThis.startCity;
		const_cast<const char* &>(this->endCity) = copyThis.endCity;
	}
	return *this;
}

Solution:

#include <iostream>
#include <iomanip>
#include <cstdlib>

using namespace std;

class Leg
{
	const char* const startCity;
	const char* const endCity;
	const double distance;
	public:
	Leg(const char* const, const char* const, const double);
	Leg& operator=(const Leg&);
	double getDistance() const;
	void output(ostream&) const;
};

// constructor
Leg::Leg(const char* startCity, const char* endCity, const double distance): startCity(startCity), endCity(endCity), distance(distance)
{
}

// return the distance
double Leg:: getDistance() const
{
	return distance;
}

// assignment operator
Leg& Leg::operator=(const Leg& copyThis) 
{
	// avoid self assignment
	if (this != &copyThis) 
	{
		const_cast<double&>(this->distance) = copyThis.distance;
		const_cast<const char* &>(this->startCity) = copyThis.startCity;
		const_cast<const char* &>(this->endCity) = copyThis.endCity;
	}
	return *this;
}

// output the Leg object details to out
void Leg:: output(ostream& out) const
{
	out<<"Leg: "<<startCity<<" to "<<endCity<<", "<<fixed<<setprecision(2)<<distance<<" miles"<<endl;
}

int main()
{
	double arr[40];
	// create an array of random distances
	for(int i = 0; i < 40; i++)
	{
		arr[i] = rand() % 39 + 1.45;
	}
	// create an array of Leg objects
	Leg a[]={
		Leg("Aberdeen","Abilene", arr[1]),
		Leg("Akron","Albany", arr[2]),
		Leg("Albuquerque","Alexandria", arr[3]),
		Leg("Allentown","Amarillo", arr[4]),
		Leg("Anaheim","Anchorage", arr[5]),
		Leg("Ann Arbor","Antioch", arr[6]),
		Leg("Apple Valley","Appleton", arr[7]),
		Leg("Arlington","Arvada", arr[8]),
		Leg("Asheville","Athens", arr[9]),
		Leg("Atlanta","Atlantic City", arr[10]),
		Leg("Augusta","Aurora", arr[12]),
		Leg("Austin","Bakersfield", arr[12]),
		Leg("Baltimore","Barnstable", arr[13]),
		Leg("Baton Rouge","Beaumont", arr[14]),
		Leg("Bel Air","Bellevue", arr[15]),
		Leg("Berkeley","Bethlehem", arr[16]),
		Leg("Billings","Birmingham", arr[17]),
		Leg("Bloomington","Boise", arr[18]),
		Leg("Boise City","Bonita Springs", arr[19]),
		Leg("Boston","Boulder", arr[20]),
		Leg("Bremerton","Brighton", arr[21]),
		Leg("Brownsville","Bryan", arr[22]),
		Leg("Buffalo","Burbank", arr[23]),
		Leg("Cambridge","Canton", arr[24]),
		Leg("Cape Coral","Carrollton", arr[25]),
		Leg("Cary","Cathedral City", arr[26]),
		Leg("Cedar Rapids","Champaign", arr[27])
		/*Leg("Aberdeen","Abilene", arr[1]),Leg("Akron","Albany", arr[1]),Leg("Albuquerque","Alexandria", arr[1]),
		 * Leg("Aberdeen","Abilene", arr[1]),Leg("Akron","Albany", arr[1]),Leg("Albuquerque","Alexandria", arr[1]),
		 * Leg("Aberdeen","Abilene", arr[1]),Leg("Akron","Albany", arr[1]),Leg("Albuquerque","Alexandria", arr[1]),
		 * Leg("Aberdeen","Abilene", arr[1]),Leg("Akron","Albany", arr[1]),Leg("Albuquerque","Alexandria", arr[1]),
		 * Leg("Aberdeen","Abilene", arr[1])*/
	};
	const int SIZE = sizeof(a) / sizeof(a[0]);
	// sort the leg objects in ascending order based on their distance
	int min;
	for(int i=0;i<SIZE-1;i++)
	{
		 min = i;
		 for(int j=i+1;j<SIZE;j++)
		 {
			 if(a[j].getDistance() < a[min].getDistance())
			 min = j;
		 }
		 if(min != i)
		 {
			 Leg temp = a[i];
			 a[i] = a[min];
			 a[min] = temp;
		 }
	}
	// display the sorted order of Leg objects
	for(int i=0;i<SIZE;i++)
		a[i].output(cout);
	return 0;
}
//end of program


Output:


Tuesday, 14 July 2020

Compute the sum of odd numbers

Q: Compute the sum of odd numbers up to a given odd number n.
Input: n
Function: oddsum(n) = 1 + 3 + ...+ (n-2) + n.
Output: oddsum (n)
Examples: oddsum(3) = 4, oddsum(5)=9; oddsum(7)=16.
You may assume the number n is odd.
Use the iterative algoithm such as;
      sum = 0;
      counter = 1;
      while (counter <= n) {
          sum =sum + counter;
          counter= counter + 2;
      }

Solution:

#include <iostream>
using namespace std;

void oddsum(int n)
{
	int sum = 0; // variable initialized to compute the sum
	int counter = 1; // variable to counter loop
	while (counter <= n)
	{
		sum = sum + counter;
		counter = counter + 2;
	}
	cout << "The sum is " << sum;
}

int main()
{
	int n;
	cout << "Enter a number: ";
	cin >> n;
	oddsum(n);

	return 0;
}

Screenshot