CSS326 Database Programming Laboratory: (Laboratory #1) Introduction to Database Programming
School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University
CSS326 Database Programming Laboratory
Laboratory #1: Introduction to Database Programming
Objectives:
- To introduce the basic components of database applications.
- To introduce necessary applications/software to learn databases.
- To introduce OOP concepts in C#.
1. Introduction to Database Management Systems (DBMS)
The DBMS comprises numerous components, each assigned a crucial role. The database environment encompasses a set of components responsible for governing data usage, management, and data groups. These components include individuals, database handling techniques, data, hardware, software, and more. Among the various components of the DBMS, we will now elaborate on six key aspects of the database.
1.1 Hardware
The hardware component of a DBMS refers to its physical elements. This includes output devices such as printers and monitors, as well as storage devices like hard disks. In a DBMS, the information hardware is the most prominent and visible part. It encompasses equipment like printers, computers, and scanners, which are utilized to capture data and present output to users. Hardware enables the DBMS to access and update the database. A server is capable of storing vast amounts of data, which can be shared using the user's own system. The database can be implemented on a wide range of systems, from microcomputers to mainframe computers. Additionally, the database acts as an interface between the real world and the database itself. When running a database software like MySQL, we can input commands using our keyboards, while components like RAM, ROM, and the processor are integral parts of our computer system.
1.2 Software
The main component of the DBMS is the software, which encompasses a collection of programs used to instruct the computer in its tasks. This software consists of procedures, programs, and routines that govern the operation and performance of the computer system. It acts as a set of instructions for the computer hardware, allowing it to function effectively. Within the DBMS context, the software includes various types such as network software and operating software. Specifically, the database software is responsible for accessing the database, while the database application performs specific tasks. This software possesses the ability to interpret the language used to access databases, converting it into actual commands that can be executed by the database. It is considered the central component as the entire functioning of the database relies on it. In a sense, the database software acts as a wrapper that encapsulates the physical database, providing users with a user-friendly interface for managing data operations like storage, updating, and deletion. Examples of DBMS software include MySQL, Oracle, SQL Server, dBase, FileMaker, Clipper, Foxpro, and Microsoft Access, among others.
1.3 Data
Data refers to the gathering of raw facts that are stored in a database. This encompasses various types of raw materials from which meaningful information can be derived. The database has the capacity to store different forms of data, including structured data, non-structural data, and logical data. Structured data follows a specific format within the database, while non-structural data comprises diverse types of data stored in their original formats. The database is often referred to as the foundation of the database management system (DBMS) since it enables the creation and construction of the DBMS. Once the database is established, it allows for the creation, access, and updating of the stored data. The primary purpose of implementing a database is to effectively create and manage the data contained within it. Within the database, both the actual data and metadata can be found. Metadata refers to data about the data, such as the size, name, and user-related information associated with the stored data. These metadata elements are stored alongside the actual data when a user saves information in the database.
1.4 Procedure
A procedure in the context of a DBMS refers to a set of general instructions or guidelines for its utilization. These instructions encompass various tasks such as database setup, installation, login and logout procedures, database management, backup creation, and report generation. By adhering to the procedure, users can validate data, control access, and minimize traffic between the server and clients, thereby enhancing the performance of the DBMS, particularly when dealing with complex business logic. The primary objective of the procedure is to provide users with guidance during the management and operation of the database. It shares similarities with the function of a database. However, a significant distinction lies in the fact that a database function behaves similarly to an SQL statement, while a database procedure is invoked using the CALL statement of the DBMS. In the enterprise architecture, there are two approaches for creating database procedures: the individual object or default object, and the operations within a container.
1.5 Database Access Language
The Database Access Language is a straightforward language that empowers users to compose commands and execute operations on the stored data within a database. It serves as a means to access, update, and delete data within the database. Users can formulate commands or queries in the Database Access Language prior to submitting them for execution in the database. By utilizing this language, users can create new databases and tables, as well as insert or delete data. Examples of database languages include SQL (Structured Query Language), My Access, Oracle, among others. A database language typically consists of two distinct languages.
1.5.1 Data Definition Language
DDL (Data Definition Language) is employed in the creation of a database, enabling the implementation of the database schema at various levels such as physical, logical, and external. The fundamental DDL commands serve as the foundation for all other DDL operations. These commands include ALTER, COMMENT, CREATE, DESCRIBE, DROP, SHOW, and USE, each playing a significant role in defining and modifying objects within the database. We will discuss it later in the coming labs.
1.5.2 Data Manipulation Language
DML (Data Manipulation Language) is employed for the purpose of interacting with a database by accessing and manipulating its data. This language offers a range of statements to retrieve, modify, insert, and delete data stored within the database. The fundamental DML commands serve as the foundation for all other DML operations, and they include INSERT, UPDATE, DELETE, LOCK, and CALL. These commands play a crucial role in managing and manipulating data within the database. This topic will be discussed further during the next few labs as well.
1.6 People
The individuals responsible for overseeing and managing databases, as well as performing various operations within the database in the DBMS, are known as database users. This group includes the database administrator, software developer, and end-user. The database administrator (DBA) assumes overall responsibility for the management of the entire database management system. This involves ensuring the security and availability of the DBMS, managing license keys, overseeing user accounts and access, and other related tasks. Software developers, on the other hand, are involved in the development and design aspects of the DBMS. They possess the ability to handle large volumes of data, make modifications and edits to databases, design and develop new databases, and troubleshoot database issues. Lastly, end-users are crucial in today's world where modern web and mobile applications rely on database systems to store user data. End-users actively engage with the applications, storing, retrieving, updating, and deleting data as needed. The user base of a database can further be categorized into distinct groups, such as native users, online users, sophisticated users, specialized users, application users, and, of course, the database administrator (DBA).
2. Desktop or Web Applications
When deciding between a web app and a desktop app for a SQL application, there are several factors to consider. Let's explore the advantages and considerations for each option:
Web App:
-
Accessibility: Web apps are accessible from any device with a web browser and an internet connection. Users can access the application from different platforms and operating systems, including desktops, laptops, tablets, and smartphones.
-
Cross-platform compatibility: Web apps are typically developed using web technologies such as HTML, CSS, and JavaScript. They can run on different operating systems, including Windows, macOS, Linux, and mobile platforms like iOS and Android, without requiring any platform-specific modifications.
-
Easy updates and maintenance: Web apps can be updated centrally on the server, ensuring that all users have access to the latest version instantly. This eliminates the need for users to manually update their local installations, making maintenance and bug fixing more efficient.
-
Collaboration and sharing: Web apps facilitate collaborative features and sharing capabilities, allowing multiple users to access and work on the same data simultaneously. This can be beneficial for scenarios where multiple users need to interact with the SQL application simultaneously.
-
Scalability: Web apps can be easily scaled to accommodate a growing user base by adding more server resources or employing cloud-based solutions.
Desktop App:
-
Performance: Desktop apps typically have direct access to system resources, enabling them to deliver high-performance capabilities. This can be advantageous for SQL applications that require intensive computations or deal with large datasets.
-
Offline functionality: Desktop apps can function independently of an internet connection. They can store data locally, allowing users to continue working even when they are not connected to the internet. This can be crucial in environments with limited or unreliable internet access.
-
Rich user interface: Desktop apps have more flexibility in terms of UI design and can provide a richer user experience compared to web apps. They can take advantage of native UI components and features specific to the operating system.
-
Enhanced security: Desktop apps can offer an additional layer of security by storing data locally and allowing users to control access to their systems. This can be important for SQL applications dealing with sensitive data.
In summary, a web app is generally a good choice if you prioritize accessibility, cross-platform compatibility, collaboration, and easy maintenance. On the other hand, a desktop app may be preferable if you require high performance, offline functionality, rich user interface, or enhanced security. Ultimately, the decision should be based on the specific requirements and constraints of your SQL application and the needs of your users.
However, in this course our main priority is to broaden your knowledge on database programming. Therefore, we will continue with developing a Desktop application.
Basic Architecture of a Web Application (** for your knowledge)
The basic architecture of a web application typically follows a client-server model, where clients (usually web browsers) interact with a server to access and interact with the application's resources and functionality. Here's a general overview of the basic architecture:
1. Client-Side (Front-end):
The client-side refers to the part of the web application that runs on the user's device (e.g., web browser). It is responsible for presenting the user interface and handling user interactions. Common technologies used on the client-side include HTML (for content), CSS (for styling), and JavaScript (for interactivity).
- HTML (Hypertext Markup Language): Provides the structure and content of the web page.
- CSS (Cascading Style Sheets): Determines the presentation and styling of the HTML elements.
- JavaScript: Enables dynamic and interactive elements on the web page, allowing for user input and communication with the server.
Modern front-end frameworks and libraries (e.g., React, Angular, Vue.js) simplify the development process by providing tools and abstractions to build complex user interfaces efficiently.
2. Server-Side (Back-end):
The server-side is the part of the web application that runs on the server and handles requests from clients, processes data, and manages application logic. It interacts with databases, external services, and performs the necessary computations to fulfill client requests.
Common server-side technologies and programming languages include:
- Programming languages: JavaScript (Node.js), Python (Django, Flask), Ruby (Ruby on Rails), Java (Spring Boot), PHP, etc.
- Web servers: Apache, Nginx, Microsoft IIS.
The server-side communicates with the client-side through APIs (Application Programming Interfaces). APIs define the rules and data formats for communication, enabling the client and server to interact seamlessly.
3. Database:
The database is used to store and manage the application's data persistently. The server-side communicates with the database to retrieve, store, and modify data as required. Common types of databases used in web applications include relational databases (e.g., MySQL, PostgreSQL) and NoSQL databases (e.g., MongoDB, Redis).
4. Communication:
Communication between the client-side and server-side typically occurs via HTTP (Hypertext Transfer Protocol). When a user interacts with the web application, the client-side sends HTTP requests to the server, and the server processes these requests and sends back HTTP responses with the necessary data or actions.
5. Deployment:
Once the web application is developed, it needs to be deployed on a web server or cloud infrastructure so that users can access it over the internet. Common deployment platforms include AWS, Azure, Google Cloud Platform, and others.
It's important to note that modern web applications often follow a more complex architecture, employing various design patterns and additional technologies to handle scalability, security, and performance requirements. These may include caching mechanisms, load balancers, microservices architecture, and more, depending on the specific needs of the application.
3. SQL Servers
SQL servers refer to database management systems (DBMS) that use SQL (Structured Query Language) as the standard language for accessing and manipulating data stored in relational databases. These servers provide a platform for creating, managing, and interacting with databases, as well as executing SQL queries to perform various operations on the data.
Some popular SQL servers include:
-
MySQL: An open-source relational database management system known for its performance, reliability, and ease of use. It is widely used in web applications and is compatible with various operating systems.
-
Microsoft SQL Server (MS SQL Server): A relational database management system developed by Microsoft. It is commonly used in enterprise-level applications, especially in the Windows ecosystem.
-
PostgreSQL: An open-source relational database management system known for its advanced features, extensibility, and support for complex queries.
-
Oracle Database: A commercial, robust, and widely used relational database management system developed by Oracle Corporation, known for its scalability and reliability.
-
SQLite: A lightweight, file-based, self-contained SQL server that is often used in mobile applications, embedded systems, and small-scale projects.
-
MariaDB: An open-source fork of MySQL, created by the original developers of MySQL. It aims to remain compatible with MySQL while offering additional features and performance improvements.
-
IBM Db2: A family of data management products, including Db2 for Linux, UNIX, and Windows, as well as Db2 for z/OS (mainframe).
-
Microsoft Azure SQL Database: A cloud-based relational database service provided by Microsoft Azure, built on MS SQL Server.
Each SQL server has its strengths and is suitable for different use cases and environments. When choosing an SQL server, factors such as performance, scalability, cost, licensing, and compatibility with existing systems should be considered. Additionally, the specific features offered by each SQL server can influence the decision, depending on the requirements of the project.
We will select MySQL server as our DBMS from here onwards due to its popularity and open-source nature.
4. Desktop Applications with C#
C# is a powerful programming language commonly used for developing desktop applications on the Windows platform. With C# and the .NET framework, you can create a wide variety of desktop applications, including:
1. Windows Forms Applications:
Windows Forms (WinForms) is a traditional technology used to create desktop applications with a graphical user interface (GUI). You can design the user interface using drag-and-drop controls and event-driven programming in Visual Studio or other C# IDEs. WinForms applications are well-suited for simple to moderately complex applications.
2. WPF (Windows Presentation Foundation) Applications:
WPF is a more modern technology for creating Windows desktop applications. It provides more advanced UI capabilities, including animations, styles, and data binding. WPF applications are best suited for more complex applications that require a visually rich and highly interactive user interface.
3. Console Applications:
Console applications run in a command-line interface, making them suitable for text-based programs, batch processing, or system utilities.
4. Universal Windows Platform (UWP) Applications:
UWP allows you to create applications that run on multiple Windows devices, such as PCs, tablets, Xbox, and HoloLens. UWP applications are designed to be adaptive and support various device form factors.
5. Windows Service Applications:
Windows services are background processes that run without a user interface. They are used for tasks that need to be performed continuously or at scheduled intervals, such as server-side processing, data synchronization, or system maintenance.
6. .NET MAUI (Multi-platform App UI):
.NET MAUI is a cross-platform framework built on top of .NET, which allows you to create desktop applications that run on multiple platforms, including Windows, macOS, iOS, and Android.
To create desktop applications with C#, you'll need to have the following:
- A C# development environment, such as Visual Studio or Visual Studio Code, with the .NET framework installed.
- Familiarity with C# programming language fundamentals.
- Understanding of GUI design and event-driven programming (for WinForms and WPF applications).
Once you have the necessary tools and knowledge, you can start building desktop applications with C# by creating projects of the desired type and using the appropriate libraries and controls to develop the user interface and implement application logic.
5. Recommended Software Packages
MySQL server
| OS | Software | Installation |
|---|---|---|
| Windows | MAMP | 1. Download the installation file from https://www.mamp.info/en/downloads/ 2. Execute the downloaded file and follow the installation steps. |
| Mac OS | MAMP | 1. Download the installation file from (According to your OS type) https://www.mamp.info/en/downloads/ 2. Once the download has completed, go to your Downloads folder and double-click on the package file to start the installation, then follow the installation steps. |
Document root & configuration file
Basically, web server does not share all the files on the hard disk, but it shares only the files stored under the document root. The document roots are different in each platform.
| OS | Software | Document Root | Configuration File |
|---|---|---|---|
| Windows | XAMPP | c:\MAMP\htdocs | C:\Users\Public\Public Documents\Appsolute\MAMP\conf\my.ini |
| Mac OS | MAMP | /Applications/MAMP/htdocs | /Applications/MAMP/tmp/mysql/my.cnf |
Visual Studio IDE for C# and .Net Framework
| OS | IDE | Installation |
|---|---|---|
| Windows | Visual Studio (Community 2022) | 1. Download the installation file from https://visualstudio.microsoft.com/vs/ 2. Execute the downloaded file and follow the installation steps. |
| Mac OS | Visual Studio (Community 2022) | 1. Download the installation file from (According to your OS type) https://visualstudio.microsoft.com/ 2. Execute the downloaded file and follow the installation steps. |
***In the Visual Studio Installer, choose the .NET desktop development workload.
6. Introduction to C# Programming
Before we dive into creating our DBMS applications, Let's see how to start programming in C# using Visual Studio console application. So, Visual Studio console application in C# allows developers to build text-based programs. It provides a simple, command-line interface, making it easy to execute code, display output, and interact with users, making it ideal for learning, testing, and quick development tasks.
How to get started:
To start, create a C# application project. The project type comes with all the template files you need.
-
Open Visual Studio and choose Create a new project in the Start window.
-
In the Create a new project window, select All languages, and then choose C# from the dropdown list. Choose Windows from the All-platforms list, and choose Console from the All project types list.
-
After you apply the language, platform, and project type filters, choose the Console App template, and then select Next.
***If you don't see the Console App template, select Install more tools and features.
-
In the Configure your new project window, type or enter Calculator in the Project name box, and then select Next.
-
In the Additional information window, select .NET 7.0 for your target framework, then select Create.
Visual Studio opens your new project, which includes default "Hello World" code. To view it in the editor, select the code file "Program.cs" in the Solution Explorer window, which is typically on the right-hand side of Visual Studio.
6.1 First application in C#
// This is your first application in C#
using System;
/* Don't worry if you do not understand about namespaces
and classes yet, you will learn later about it */
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
// output: Hello World!The "Hello, World" program starts with a using directive that references the System namespace. Namespaces provide a hierarchical means of organizing C# programs and libraries. Namespaces contain types and other namespaces—for example, the System namespace contains a number of types, such as the Console class referenced in the program, and many other namespaces, such as IO and Collections. A using directive that references a given namespace enables unqualified use of the types that are members of that namespace. Because of the using directive, the program can use Console.WriteLine as shorthand for System.Console.WriteLine. The Hello class declared by the "Hello, World" program has a single member, the method named Main. The Main method is declared with the static modifier. While instance methods can reference a particular enclosing object instance using the keyword this, static methods operate without reference to a particular object. By convention, a static method named Main serves as the entry point of a C# program. The line starting with // is a single line comment. C# single line comments start with // continue to the end of the current line. C# also supports multi-line comments. Multi-line comments start with /* and end with */. The output of the program is produced by the WriteLine method of the Console class in the System namespace. This class is provided by the standard class libraries, which, by default, are automatically referenced by the compiler.
6.2 Types & Variables
A type defines the structure and behavior of any data in C#. The declaration of a type may include its members, base type, interfaces it implements, and operations permitted for that type. A variable is a label that refers to an instance of a specific type. As an example, look at the following:
• int - stores integers (whole numbers), without decimals, such as 123 or -123 • double - stores floating point numbers, with decimals, such as 19.99 or -19.99 • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes • string - stores text, such as "Hello World". String values are surrounded by double quotes • bool - stores values with two states: true or false
***To create a variable, you must specify the type and assign it a value:
Examples:
string name = "John";
int myNum = 5;
double myDoubleNum = 5.99D;
char myLetter = 'D';
bool myBool = true;
string myText = "Hello";It is also possible to declare a variable without assigning the value and assign the value later as below.
Example:
int myNum;
myNum = 12;
Console.WriteLine(myNum); // output: 12It is possible to overwrite a variable value by just declaring the same variable with the new value. The only exception would be that if the variable is defined as a constant.
Example:
int myNum;
myNum = 12;
mynum=23; // no error
const int myNum = 12;
myNum = 20; // errorThe WriteLine() method is often used to display variable values to the console window. To combine both text and a variable, use the + character:
Example:
string name = "Mike";
Console.WriteLine("Hello " + name); // output: Hello MikeTo declare more than one variable of the same type, use a comma-separated list. Also, you can assign the same value to multiple variables at the same line.
Example:
int x = 6, y = 7, z = 50;
Console.WriteLine(x + y + z); // output: 63
int x, y, z;
x = y = z = 30;
Console.WriteLine(x + y + z); // output: 90In C#, every variable needs to be associated with a distinct name known as an identifier. These identifiers can be short and concise, such as 'x' and 'y,' or they can be more descriptive and meaningful, like 'age,' 'sum,' or 'totalVolume.' However, it is highly advisable to opt for descriptive names when declaring variables, as this practice enhances the overall clarity and maintainability of the codebase. By using meaningful identifiers, developers can better understand the purpose and functionality of each variable, making it easier to read and modify the code in the future. Employing descriptive names also promotes collaboration among team members and facilitates code comprehension, which is crucial for building efficient and robust software solutions. Therefore, adhering to this recommended approach contributes to the creation of well-structured and easily maintainable C# code.
The general rules for naming variables are: • Names can contain letters, digits and the underscore character (_) • Names must begin with a letter • Names should start with a lowercase letter and it cannot contain whitespace • Names are case sensitive ("myVar" and "myvar" are different variables) • Reserved words (like C# keywords, such as int or double) cannot be used as names
6.3 Data Types
A data type defines both the size and the type of values that a variable can hold.
Using the appropriate data type for each variable is crucial as it prevents errors, conserves time and memory, and enhances the maintainability and readability of your code. The predominant data types include:
| Data type | Description | Example |
|---|---|---|
| int | Stores whole numbers from -2,147,483,648 to 2,147,483,647 | int age = 30; |
| float (4 bytes) | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits | float pi = 3.14; |
| Double (8 bytes) | Stores fractional numbers. Sufficient for storing 15 decimal digits | double salary = 50000.75; |
| decimal | Precise decimal type | decimal price = 19.99m; |
| bool | Stores true or false values | bool isDone = true; |
| char | Stores a single character/letter, surrounded by single quotes | char grade = 'A'; |
| string | Stores a sequence of characters, surrounded by double quotes | string name = "John"; |
| long | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | long population = 7896541230; |
6.4 Type Casting
Type casting refers to the process of assigning a value from one data type to another.
In C#, there exist two types of casting:
-
Implicit Casting (automatic) - This involves converting a smaller data type to a larger one, which is done automatically by the compiler. Example sequence: char -> int -> long -> float -> double
-
Explicit Casting (manual) - Here, a larger data type is converted to a smaller one, and this conversion requires manual intervention in the code. Example sequence: double -> float -> long -> int -> char
These casting mechanisms are essential for managing data type conversions while ensuring the integrity and accuracy of the data being manipulated.
Example:
int myInt = 10;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt); // Outputs 10
Console.WriteLine(myDouble); // Outputs 10Example:
double myDouble = 10.7;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myDouble); // Outputs 10.7
Console.WriteLine(myInt); // Outputs 10*One can also perform explicit data type conversions using built-in methods like Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int), and Convert.ToInt64 (long).
Exercise 1:
Try the following code & check the outputs!
int myInt = 8;
double myDouble = 7.89;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // convert double to int
Console.WriteLine(Convert.ToString(myBool)); // convert bool to string6.5 User Inputs
Having acquired knowledge of using Console.WriteLine() to display values, we will now employ Console.ReadLine() to obtain user input. In the given illustration, the user has the opportunity to enter their username, and this input will be stored in the variable userName. Subsequently, we print the value of userName.
// Type your username and press enter
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();
// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);Due to the fact that the Console.ReadLine() method exclusively returns a string, attempting to retrieve information from another data type like int will result in an error. The subsequent program will encounter an issue in this context.
Console.WriteLine("Enter your age:");
int age = Console.ReadLine(); // need to change to int by Convert.ToInt32
Console.WriteLine("Your age is: " + age);6.6 Operators
In C#, operators are symbols or keywords used to perform various operations on variables and values. C# supports a wide range of operators, and here are some of the most commonly used ones along with examples:
1. Arithmetic Operators:
-
Addition (+): Used to add two values together. Example:
int num1 = 10; int num2 = 5; int result = num1 + num2; // result will be 15 -
Subtraction (-): Used to subtract one value from another. Example:
int num1 = 10; int num2 = 5; int result = num1 - num2; // result will be 5 -
Multiplication (*): Used to multiply two values. Example:
int num1 = 10; int num2 = 5; int result = num1 * num2; // result will be 50 -
Division (/): Used to divide one value by another. Example:
int num1 = 10; int num2 = 5; int result = num1 / num2; // result will be 2 -
Modulus (%): Used to get the remainder of a division operation. Example:
int num1 = 10; int num2 = 3; int result = num1 % num2; // result will be 1 (remainder of 10/3)
2. Assignment Operators:
-
Assignment (=): Used to assign a value to a variable. Example:
int num = 10; // num is assigned the value 10 -
Addition and Assignment (+=): Used to add a value to the variable and update its value. Example:
int num = 5; num += 3; // equivalent to num = num + 3; num will be 8Similar to
+=, there are other compound assignment operators like-=for subtraction,*=for multiplication,/=for division, and%=for modulus.
3. Comparison Operators:
-
Equal to (==): Used to check if two values are equal. Example:
int num1 = 5; int num2 = 5; bool isEqual = num1 == num2; // isEqual will be true -
Not equal to (!=): Used to check if two values are not equal. Example:
int num1 = 5; int num2 = 10; bool isNotEqual = num1 != num2; // isNotEqual will be true -
Greater than (>): Used to check if the left value is greater than the right value. Example:
int num1 = 10; int num2 = 5; bool isGreater = num1 > num2; // isGreater will be true -
Less than (<): Used to check if the left value is less than the right value. Example:
int num1 = 5; int num2 = 10; bool isLess = num1 < num2; // isLess will be true -
Greater than or equal to (>=): Used to check if the left value is greater than or equal to the right value. Example:
int num1 = 10; int num2 = 10; bool isGreaterOrEqual = num1 >= num2; // isGreaterOrEqual will be true -
Less than or equal to (<=): Used to check if the left value is less than or equal to the right value. Example:
int num1 = 5; int num2 = 10; bool isLessOrEqual = num1 <= num2; // isLessOrEqual will be true
4. Logical Operators:
-
Logical AND (&&): Used to check if both conditions are true. Example:
bool condition1 = true; bool condition2 = false; bool result = condition1 && condition2; // result will be false -
Logical OR (||): Used to check if at least one condition is true. Example:
bool condition1 = true; bool condition2 = false; bool result = condition1 || condition2; // result will be true -
Logical NOT (!): Used to reverse the truth value of a condition. Example:
bool condition = true; bool result = !condition; // result will be false
These are just some of the most commonly used operators in C#. The language also supports other operators like bitwise operators, shift operators, ternary operator, etc.
6.7 Math class
In C#, the Math class is part of the System namespace and provides a collection of static methods and constants for performing various mathematical operations. It contains methods for common mathematical functions like trigonometry, logarithms, exponents, rounding, and more. Here's an explanation of some commonly used methods in the Math class along with exercises and answers:
-
Math.Abs(): Returns the absolute value of a number. Example:
int num = -5; int absoluteValue = Math.Abs(num); // absoluteValue will be 5 -
Math.Sqrt(): Returns the square root of a number. Example:
double num = 25; double squareRoot = Math.Sqrt(num); // squareRoot will be 5 -
Math.Pow(): Returns a specified number raised to the power of another number. Example:
double baseNumber = 2; double exponent = 3; double result = Math.Pow(baseNumber, exponent); // result will be 8 (2^3) -
Math.Round(): Rounds a decimal value to the nearest integer. Example:
double num = 3.7; double roundedValue = Math.Round(num); // roundedValue will be 4 -
Math.Floor(): Rounds down a decimal value to the nearest integer. Example:
double num = 3.7; double floorValue = Math.Floor(num); // floorValue will be 3 -
Math.Ceiling(): Rounds up a decimal value to the nearest integer. Example:
double num = 3.2; double ceilingValue = Math.Ceiling(num); // ceilingValue will be 4 -
Math.Max(): Returns the greater of two values. Example:
int num1 = 10; int num2 = 20; int maxValue = Math.Max(num1, num2); // maxValue will be 20 -
Math.Min(): Returns the smaller of two values. Example:
int num1 = 10; int num2 = 20; int minValue = Math.Min(num1, num2); // minValue will be 10
Exercise 2:
Since, you have an understanding of the math class, let's try the following exercises.
-
Absolute Sum Write a C# program that takes three integer inputs from the user and calculates the sum of their absolute values.
-
Hypotenuse Calculator Write a C# program that takes the lengths of two sides of a right-angled triangle (a and b) as input from the user and calculates the length of the hypotenuse using the Pythagorean theorem (c = sqrt(a^2 + b^2)).
6.8 String class
In C#, strings are sequences of characters represented using the string data type. They are used to store and manipulate textual data. Here's an explanation of some commonly used string methods in C# along with exercises and answers:
-
string.Length: Returns the number of characters in a string. Example:string text = "Hello, World!"; int length = text.Length; // length will be 13 -
string.ToUpper(): Converts all characters in the string to uppercase. Example:string text = "Hello, World!"; string upperText = text.ToUpper(); // upperText will be "HELLO, WORLD!" -
string.ToLower(): Converts all characters in the string to lowercase. Example:string text = "Hello, World!"; string lowerText = text.ToLower(); // lowerText will be "hello, world!" -
string.Substring(startIndex): Extracts a substring from the original string starting from the specified index. Example:string text = "Hello, World!"; string subText = text.Substring(7); // subText will be "World!" -
string.Substring(startIndex, length): Extracts a substring from the original string starting from the specified index and having the specified length. Example:string text = "Hello, World!"; string subText = text.Substring(0, 5); // subText will be "Hello" -
string.Contains(substring): Checks if the string contains a specific substring and returns a boolean value. Example:string text = "Hello, World!"; bool containsHello = text.Contains("Hello"); // containsHello will be true -
string.Replace(oldValue, newValue): Replaces occurrences of a substring with a new value. Example:string text = "Hello, World!"; string newText = text.Replace("Hello", "Hi"); // newText will be "Hi, World!" -
string.IsNullOrEmpty(): Checks if the string is null or empty and returns a boolean value. Example:string text = ""; bool isEmpty = string.IsNullOrEmpty(text); // isEmpty will be true -
String Concatenation: The + operator can be used between strings to combine them. Example:
string firstName = "John "; string lastName = "Doe"; string name = firstName + lastName; Console.WriteLine(name); // prints John Doe- you can use string.Concat(firstName, lastName) to combine them as well.
-
Access strings: You can access the characters in a string by referring to its index number inside square brackets []. Example:
string myString = "Hello"; Console.WriteLine(myString[0]); // Outputs "H"
*** Escape characters:
In C#, escape characters are special sequences of characters that are used to represent characters that cannot be directly represented or typed in a string. Escape characters are denoted by a backslash \ followed by a specific character. Here are some common escape characters in C#:
\': Single quote\": Double quote\\: Backslash\n: Newline (line feed)\r: Carriage return\t: Tab\b: Backspace\f: Form feed\v: Vertical tab\0: Null character
6.9 if statements in C#
In C#, the if-else statement is used for conditional branching, allowing you to execute different blocks of code based on whether a given condition is true or false. It follows the syntax:
if (condition)
{
// Code block to execute if the condition is true
}
else
{
// Code block to execute if the condition is false
}Here's an explanation with exercises and answers:
Explanation:
-
Basic
if-elsestatement:int num = 10; if (num > 0) { Console.WriteLine("The number is positive."); } else { Console.WriteLine("The number is non-positive."); }In this example, if the
numvariable is greater than 0, it will print "The number is positive." Otherwise, it will print "The number is non-positive." -
if-elsewith multiple conditions:int age = 25; if (age < 18) { Console.WriteLine("You are a minor."); } else if (age >= 18 && age < 65) { Console.WriteLine("You are an adult."); } else { Console.WriteLine("You are a senior citizen."); }Here, the code checks the value of the
agevariable and prints the corresponding message based on the age group.
Exercises:
- Write a C# program that checks if a given number is even or odd.
- Create a C# program that takes a user's age as input and outputs whether the person is eligible to vote (age 18 or older) or not.
- Write a C# program that determines whether a year is a leap year or not. (A leap year is divisible by 4 but not by 100, or it is divisible by 400.)
***The ternary operator, considered a shorthand if-else, involves three operands and allows condensing multiple lines of code into a single line. It serves as a convenient replacement for straightforward if-else statements.
Syntax: variable = (condition) ? expressionTrue : expressionFalse;
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
// instead you can get the same result by following
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
Console.WriteLine(result);6.10 switch statements in C#
In C#, the switch statement is a control flow statement that allows you to make decisions based on the value of a single expression. It is often used as a replacement for multiple if statements when you have many possible conditions to check.
The basic syntax of the switch statement is as follows:
switch (expression)
{
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// Add more cases as needed
default:
// Code to execute if expression does not match any case
break;
}Here's an explanation of each part of the switch statement:
-
expression: The value you want to evaluate. This can be an integral type (byte, short, int, long) or a character, string, or an enumeration. -
case: Eachcaserepresents a possible value that theexpressioncan take. If theexpressionmatches the value after thecasekeyword, the corresponding block of code will be executed. -
break: After executing the code inside a matchedcase, thebreakstatement is used to exit theswitchblock and prevent the execution of subsequent cases. If you omit thebreak, the control flow will "fall through" to the next case, and its code will be executed as well. -
default: If none of thecasevalues match theexpression, thedefaultblock will be executed (optional).
Now, let's go through a exercise with answer to practice using the switch statement.
Example:
Write a C# program that takes an integer input (1 to 7) representing the day of the week and prints the corresponding day's name.
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number (1-7): ");
int dayOfWeek = int.Parse(Console.ReadLine());
string dayName;
switch (dayOfWeek)
{
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid input";
break;
}
Console.WriteLine("Day of the week: " + dayName);
}
}6.11 while loop in C#
In C#, a while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. The basic syntax of a while loop is as follows:
while (condition)
{
// Code to be executed as long as the condition is true
}Here's how the while loop works:
The condition is evaluated before entering the loop. If the condition is true, the code inside the loop is executed.
After executing the code inside the loop, the condition is re-evaluated. If the condition is still true, the loop continues to execute.
This process continues until the condition becomes false. Once the condition is false, the loop terminates, and the program continues with the next statement after the while loop.
Now, let's look at an exercise to practice using while loops in C#.
Example: Print numbers from 1 to 10 (line by line).
using System;
class Program
{
static void Main()
{
int number = 1;
while (number <= 10)
{
Console.WriteLine(number);
number++;
}
}
}6.12 for loop in C#
In C#, a for loop is a control flow statement that allows you to execute a block of code repeatedly based on a specific condition. The for loop consists of three parts:
- Initialization: Initializing a counter variable before the loop starts.
- Condition: The loop will continue executing as long as this condition is true.
- Iteration: Updating the counter variable after each iteration of the loop.
The general syntax of a for loop in C# is as follows:
for (initialization; condition; iteration)
{
// Code block to be executed repeatedly
}Here's a step-by-step explanation of how the for loop works:
-
Initialization: This part is executed only once at the beginning of the loop. It initializes the counter variable.
-
Condition: The condition is evaluated before each iteration. If the condition is true, the loop's code block is executed; otherwise, the loop terminates.
-
Code block: This is the block of code that will be executed repeatedly as long as the condition is true.
-
Iteration: After each execution of the code block, the iteration part is executed, which typically updates the counter variable.
-
Repeat: The loop continues to execute the code block as long as the condition remains true. Once the condition becomes false, the loop exits, and the program continues with the code following the loop.
Now, let's go through an exercise to practice using for loops in C#:
Example:
Write a C# program that prints the numbers from 1 to 10.
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
}
}***Another type of loop is the foreach loop, specifically designed for iterating through elements within an array.
foreach (type variableName in arrayName)
{
// code block to be executed
}Example:
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}6.13 Array in C#
Arrays are data structures used in C# to store multiple elements of the same type. They provide a way to store and access multiple values in a single variable. Each value in an array is called an element, and elements are accessed using an index, which starts from 0.
Declaring an array in C#:
// Syntax: dataType[] arrayName = new dataType[arraySize];
int[] numbers = new int[5]; // Declares an array of integers with a size of 5Initializing an array with values:
// Syntax: dataType[] arrayName = { value1, value2, ..., valueN };
int[] numbers = { 1, 2, 3, 4, 5 }; // Initializes an array of integers with values 1, 2, 3, 4, and 5Accessing elements in an array:
int[] numbers = { 1, 2, 3, 4, 5 };
int firstElement = numbers[0]; // Accesses the first element (index 0) of the array, which is 1
int thirdElement = numbers[2]; // Accesses the third element (index 2) of the array, which is 3Modifying elements in an array:
int[] numbers = { 1, 2, 3, 4, 5 };
numbers[2] = 10; // Changes the third element (index 2) of the array to 10Iterating through an array using a loop:
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
// Output: 1 2 3 4 56.14 Break & continue in C#
In C#, break and continue are control flow statements used within loops (e.g., for, while, do-while) to alter the normal flow of execution. They are used to make the loop more flexible and to control which parts of the loop should be executed or skipped based on specific conditions.
1. break statement:
- The
breakstatement is used to terminate the loop immediately when a certain condition is met, even if the loop's condition hasn't been fully satisfied. - When encountered, the loop will stop executing, and the program will continue with the code following the loop.
Here's an example of using break in a for loop:
using System;
public class BreakExample
{
public static void Main()
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
Console.WriteLine("Found 5. Exiting the loop.");
break;
}
Console.WriteLine($"Current number: {i}");
}
}
}Output:
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Found 5. Exiting the loop.
2. continue statement:
- The
continuestatement is used to skip the rest of the loop's body for the current iteration when a particular condition is met. The loop then proceeds to the next iteration. - This statement allows you to avoid executing specific code within the loop for certain cases.
Here's an example of using continue in a while loop:
using System;
public class ContinueExample
{
public static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach (int number in numbers)
{
if (number % 2 == 0)
{
Console.WriteLine($"{number} is even.");
continue;
}
Console.WriteLine($"{number} is odd.");
}
}
}Output:
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.
6 is even.
7 is odd.
8 is even.
9 is odd.
10 is even.
Exercises:
-
Write a C# program that uses a
forloop to find the first multiple of 7 within the range of 1 to 50. When found, print the result and exit the loop usingbreak. -
Write a C# program that uses a
whileloop to print all even numbers from 0 to 20, skipping the number 10 usingcontinue.
6.15 Methods in C#
In C#, a method is a block of code that performs a specific task. Methods are used to encapsulate functionality and make the code more organized, reusable, and maintainable. They help in breaking down complex tasks into smaller, manageable pieces.
A method has a signature that includes the following components:
-
Access Modifier: It defines the visibility of the method from other parts of the code. Common access modifiers are public, private, protected, internal, etc.
-
Return Type: It specifies the type of data that the method will return after performing its task. If the method doesn't return any value, you can use the void keyword.
-
Method Name: It is the unique identifier of the method.
-
Parameters: These are variables that you can pass to the method for it to work with. Parameters are enclosed in parentheses.
-
Method Body: It contains the statements that define the functionality of the method.
Here's the general syntax of a method in C#:
<Access Modifier> <Return Type> <Method Name>(<Parameters>)
{
// Method Body
// Perform tasks
// Optionally return a value
}Exercise:
Create a C# method called GreetUser that takes a string parameter name and displays a greeting message with the user's name.
using System;
public class Program
{
public static void GreetUser(string name)
{
Console.WriteLine($"Hello, {name}! Welcome!");
}
public static void Main()
{
string userName = "John";
GreetUser(userName);
}
}Exercise:
Create a C# method called Sum that takes two integers as parameters and returns their sum.
using System;
public class Program
{
public static int Sum(int num1, int num2)
{
return num1 + num2;
}
public static void Main()
{
int result = Sum(10, 20);
Console.WriteLine($"The sum is: {result}");
}
}6.16 Classes & objects in C#
In C#, classes and objects are fundamental concepts of object-oriented programming (OOP). A class is a blueprint for creating objects, and an object is an instance of a class. Classes define the properties (attributes) and behaviors (methods) that objects of that class can have. Let's explain these concepts in more detail and provide some exercises with answers to practice.
Explanation of Classes and Objects:
Classes:
In C#, a class is defined using the class keyword. It contains data members (fields) and member functions (methods). Here's a simple example of a C# class:
public class Person
{
// Data members (fields)
public string Name;
public int Age;
// Member functions (methods)
public void SayHello()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}In this example, we have defined a class named Person with two data members (Name and Age) and one member function (SayHello()).
Objects:
An object is an instance of a class. To create an object, you use the new keyword followed by the class name and optional constructor arguments. Here's how you create objects of the Person class:
Person person1 = new Person();
person1.Name = "Alice";
person1.Age = 30;
Person person2 = new Person();
person2.Name = "Bob";
person2.Age = 25;In this example, we have created two objects of the Person class, person1 and person2, and set their Name and Age properties.
Exercises:
Exercise 1:
Create a C# class named Rectangle with data members width and height, and a member function CalculateArea() that calculates and returns the area of the rectangle (area = width * height).
public class Rectangle
{
// Data members (fields)
public double width;
public double height;
// Member function (method)
public double CalculateArea()
{
return width * height;
}
}Exercise 2:
Create two objects of the Rectangle class, set their width and height properties, and calculate their areas using the CalculateArea() method.
Rectangle rectangle1 = new Rectangle();
rectangle1.width = 5.0;
rectangle1.height = 3.0;
Rectangle rectangle2 = new Rectangle();
rectangle2.width = 8.0;
rectangle2.height = 4.5;
double area1 = rectangle1.CalculateArea();
double area2 = rectangle2.CalculateArea();
Console.WriteLine($"Area of rectangle 1: {area1}");
Console.WriteLine($"Area of rectangle 2: {area2}");Output:
Area of rectangle 1: 15
Area of rectangle 2: 36
In this exercise, we've created a class Rectangle with width and height data members and a method CalculateArea() to find the area of the rectangle. Then, we've created two objects, set their properties, and calculated and printed their respective areas.
7. References
[1]. Silberschatz, A., Korth, H. F., & Sudarshan, S. (2020). Database system concepts. New York: McGraw-Hill Education.
[2]. Oracle. (n.d.). Retrieved from https://www.mysql.com/why-mysql/
[3]. Anandmeg. (n.d.). Retrieved from https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2022
[4]. (N.d.). Retrieved from https://www.w3schools.com/cs/index.php
Revised on 01/Aug/2023