0% found this document useful (0 votes)
35 views101 pages

Study Guide

The document outlines the curriculum for the DSI134/INFO134 module at Midlands State University, focusing on principles of programming languages. It covers various programming paradigms, including imperative, logical, functional, and object-oriented programming, alongside essential programming concepts such as data types, control statements, and methods. Additionally, it details assessment methods, recommended resources, and learning outcomes aimed at developing students' programming skills and understanding of language design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views101 pages

Study Guide

The document outlines the curriculum for the DSI134/INFO134 module at Midlands State University, focusing on principles of programming languages. It covers various programming paradigms, including imperative, logical, functional, and object-oriented programming, alongside essential programming concepts such as data types, control statements, and methods. Additionally, it details assessment methods, recommended resources, and learning outcomes aimed at developing students' programming skills and understanding of language design.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 101

MIDLANDS STATE UNIVERSITY

FACULTY OF COMMERCE
Department of Information Systems

DSI134/INFO134: PRINCIPLES OF PROGRAMMING LANGUAGES

Module content

The module content includes the following:

The module content includes the following:

Overview of Programming Languages


● Definition of terms and the Art of Language Design and Problem Solving
● The Programming Language Spectrum/Paradigms
● similarities and differences between the various programming paradigms
(Imperative Programming Paradigm (Procedural Programming Paradigm,
Object Oriented Programming, Parallel Processing Approach); Declarative
Programming Paradigm (Logic Programming Paradigm, Functional
Programming, Database Processing Approach)
● key characteristics, similarities and differences amongst programming
languages (including domain such as web, mobile, enterprise and embedded)
● Why Study Programming Languages?
● Compilation and Interpretation;
● Programming Environments
● An Overview of Compilation

Console Program
 Software Development Phases
 Structure of a program
 Comments
 Data types
 Variables and variable declaration
 Operators (arithmetic, relational, logical, bitwise, conditional)
 Operator precedence
 Basic input/output
- Console Input and Output Applications
- Printing to the Console
- Printing Strings and Numbers
- Reading from the Console
- Reading Characters
- Reading Strings
- Parsing Strings to Numeral Types
- Reading Numeral Types

Control Statements
● Conditional Statements
● Loops
● Jump Statements and Implementation of continue and break Statements in
Loops

Methods
● Method Declaration (Function Prototype), Method Implementation (Definition)
And Invoking Methods in Main Function.
● Concept of Pass by Value and Pass by Reference
● Returning a Result from a Function
● Execution of A Program with More Than One Class

Strings and Regular Expressions


● Declaring and Initializing Strings
● String Operations
● Constructing Strings
● String Formatting and Regular Expressions

Files
● Streams, Reading from A Text File, Writing to A Text File, Io Exception
Handling, Text File Examples.

Demonstrating different Programming Paradigms Using Code

● Functional and Logic Programming (Clojure (LISP), Prolog and Haskell)


● Imperative Programming (FORTRAN, COBOL)
● Procedural Programming using C
● Relationships to object-oriented programming using C♯ and .NET
● Evolution to multi-paradigm languages
● Comparisons of expressiveness
● Benchmark tasks and their relationship to real system performance

Tools to used:
IDEs compatible with Programming Languages used

Recommended books:
1. Grose II, D.M. (2017), Programming in C++ Volume 1, The Foundation of C++.
2. Williams, A. (2019), C++ Concurrency in action 2nd Edition, Manning Publications
3. Murach, J and Delamater, M, (2018), Murach’s C++ Programming, Mike Murach &
Associates
4. Pai, P and Abraham, P (2018), C++ Reactive Programming, Packt Publishing
5. Lospinoso, J, (2019), C++ Crash Course, No Starch Press
6. Bancila , M, (2018), The Modern C++ Challenger, Packt Publishing
7. Stroustrup, B, (2018), A tour of C++ 2nd edition, Addison-Wesley Professional
8. Lippman, S.B, Lajoie, J and Moo, B.E (2012), C++ Primer 5th edition, Addison-Wesley
Professional
9. Eckel, B , (1999), Thinking in C++, MindView Inc
10. Nakov, S., and Company, (2013). Fundamentals of Computer Programming with CSharp.
11. Mueller, J., P., Sempf, B., and Sphar, C., (2018). C# 7.0 All-in-One for Dummies.
Recommended sites:
< https://www.tutorialspoint.com/cplusplus/ > C++ Tutorial (April 12, 2020)
< http://www.cplusplus.com/doc/tutorial/ > Tutorials C++ language (April 12, 2020)
< https://www.programiz.com/cpp-programming > Learn C++ Programming, The Definitive
Guide ( April 12, 2020)
< https://www.learncpp.com/ > Tutorials to help you master C++ and OOP. (April 12, 2020)
< https://www.youtube.com/watch?v=vLnPwxZdW4Y > C++ Full course (April 12, 2020)
< https://www.youtube.com/watch?v=mUQZ1qmKlLY > C++ lecture. (April 13, 2020)
< https://www.youtube.com/watch?v=N5HgK1bTLOg > C++ video tutorial. (April 13, 2020)
www.tutorialspoint.com/csharp
www.planetsourcecode.com
https://www.w3resource.com/csharp-exercises/
http://www.sanfoundry.com/csharp-programming-examples/
https://www.javatpoint.com/c-sharp-tutorial
https://www.edx.org/course/programming-c-microsoft-dev204x-3
www.dotnetperls.com

Assessment

The continuous assessment marks will be in the form of assignments, tests, laboratory
quizzes or tests and constitutes 40% of the final mark. The Examination will constitute 60%
and will include a 2-hour theoretical exam and a 3-hour laboratory based exam.

Module aims

● Introduce different programming language paradigms and their relationship to


different applications
● Describe the design of a selection of programming languages that demonstrates the
differences
● Develop a critical understanding of programming languages through evaluation of
expressiveness and performance trade-offs between different languages
Learning outcomes

● Critically evaluate the appropriateness of different languages for a given problem


space
● Critically evaluate the expressiveness and performance trade-offs between different
languages
● Demonstrate an advanced ability to code algorithms for a selection of target
languages/paradigms
● The student will develop cognitive/analytical skills; subject knowledge; transferable
skills and professional/practical skills

Overall student workload

● Independent Study Hours: 120


● Lecture Hours: 12
● Laboratory Hours: 24

Methods of Teaching / Learning

● The learning and teaching strategy is designed to help students to:


● Critically evaluate the appropriateness of different languages for a given problem
space.
● Critically evaluate the expressiveness and performance trade-offs between different
languages.
● Demonstrate an advanced ability to code algorithms for a selection of target
languages/paradigms.

The learning and teaching methods include:

• Lectures (4 weeks @ 3h) with class discussions to introduce the theoretical background

• Labs (8 weeks @ 3h) to put the theory into practice

Indicated Lecture Hours (which may also include seminars, tutorials, workshops and other
contact time) are approximate and may include in-class tests where one or more of these
are an assessment on the module. In-class tests are scheduled/organised separately to
taught content and will be published on to student personal timetables, where they apply to
taken modules, as soon as they are finalised by central administration. This will usually be
after the initial publication of the teaching timetable for the relevant semester.
INFO 134- PRINCIPLES OF PROGRAMMING LANGUAGES MODULE
NOTES

UNIT 1: OVERVIEW OF PROGRAMMING LANGUAGES


This section introduces basic programming language issues. It defines basic important
terms in programming to give understanding of coding fundamentals to the learner.

Definition of terms; the Art of Language Design and Problem Solving

Definition of Terms
First, we will define the main terms in programming.

Computer Programming - creating a sequence of instructions to enable the computer to


do something. Computer programming involves the process of writing, testing,
debugging/troubleshooting, and maintaining the source code of computer programs. This
source code is written in a programming language like C++, JAVA, Perl etc.

Computer Program -A program is a set of instructions following the rules of the chosen
language. Without programs, computers are useless. A program is like a recipe. It contains
a list of ingredients (called variables) and a list of directions (called statements) that tell the
computer what to do with the variables.

Programming Language - A vocabulary and set of grammatical rules (syntax) for


instructing a computer to perform specific tasks. Programming languages can be used to
create computer programs. The term programming language usually refers to high-level
languages, such as BASIC, C, C++, COBOL, FORTRAN, Ada, C and Pascal.

To expand a bit on programming language,

One eventually needs to convert a program into machine language so that the computer
can understand it. There are two ways to do this:

– Compile the program

– Interpret the program

To compile is to transform a program written in a high-level programming language from


source code into object code. This can be done by using a tool called compiler. A compiler
reads the whole source code and translates it into a complete machine code program to
perform the required tasks which are output as a new file.
Interpreter is a program that executes instructions written in a high-level language. An
interpreter reads the source code one instruction or line at a time, converts this line into
machine code and executes it.

Computer Programmer-A programmer is someone who writes computer programs.


Computer programmers write, test, and maintain programs or software that tell the
computer what to do.

What Skills are Required to Become a Programmer?

The Art of language Design


– Languages are developed around the prevalent computer architecture, known as the von
Neumann architecture

-Programming Methodologies

New software development methodologies (e.g., object oriented software development) led
to new programming paradigms and by extension, new programming languages.

Computer Architecture Influence

•Well-known computer architecture: Von Neumann

• Imperative languages, most dominant, because of von Neumann computers

– Data and programs stored in memory

– Memory is separate from CPU

– Instructions and data are piped from memory to CPU

– Basis for imperative languages

• Variables model memory cells

• Assignment statements model piping

• Iteration is efficient
Problem solving in programming:

Solving problems is the core of computer science. Programmers must first understand how
a human solves a problem, then understand how to translate this "algorithm" into something
a computer can do, and finally how to "write" the specific syntax (required by a computer) to
get the job done. It is sometimes the case that a machine will solve a problem in a
completely different way than a human. A good programmer will "encode" all the "facts"
necessary to represent a problem in variables

Ways of solving problems in programming:

Algorithm

An algorithm is a set of specific steps to solve a problem. For example, a computer can add
two numbers. But if you want to find the average of two numbers, this is beyond the basic
capabilities of a computer. To find the average, you must:

-First: Add the two numbers and save this result in a variable

-Then: Divide this new number the number two, and save this result in a variable.

-Finally: provide this number to the rest of the program (or print it for the user).
Brute Force
Brute force is a technique for solving problems that relies on a computers speed (how fast it
can repeat steps) to solve a problem. For example, if you wanted to know how many times
the number 8 goes into the number 100, you could do the following:

Of course, this is a silly way for a computer (or a human) to solve this problem. The real
way we would do it is:

When in doubt, you can often use "brute force" to solve a problem, but it often saves time
(at least computer time) to think about the problem and solve it in an elegant manner.

Student must research more on other problem-solving techniques in programming

The Programming Language Spectrum/Paradigms

There are several kinds of major programming paradigms: These include Imperative,
Logical, Functional and Object-Oriented.

Imperative
The imperative programming paradigm assumes that the computer can maintain through
environments of variables any changes in a computation process. Computations are
performed through a guided sequence of steps, in which these variables are referred to or
changed. The order of the steps is crucial, because a given step will have different
consequences depending on the current values of variables when the step is executed.
Imperative Languages:
Popular programming languages are imperative more often than they are any other
paradigm studies in this course. There are two reasons for such popularity:
the imperative paradigm most closely resembles the actual machine itself, so the
programmer is much closer to the machine; because of such closeness, the imperative
paradigm was the only one efficient enough for widespread use until recently.
Advantages
efficient;
close to the machine;
popular;
familiar.
Disadvantages
The semantics of a program can be complex to understand or prove, because of referential
transparency does not hold (due to side effects)
Side effects also make debugging harder;
Abstraction is more limited than with some paradigms;
Order is crucial, which doesn't always suit itself to problems.

Logical
The Logical Paradigm takes a declarative approach to problem-solving. Various logical
assertions about a situation are made, establishing all known facts. Then queries are made.
The role of the computer becomes maintaining data and logical deduction.
Logical Paradigm Programming:
A logical program is divided into three sections:
a series of definitions/declarations that define the problem domain statements of relevant
facts
statement of goals in the form of a query
Any deducible solution to a query is returned. The definitions and declarations are
constructed entirely from relations. i.e. X is a member of Y or X is in the internal between a
and b etc.
Advantages
The advantages of logic-oriented programming are bi-fold:
The system solves the problem, so the programming steps themselves are kept to a
minimum;
Proving the validity of a given program is simple.
Sample Code of Logical Paradigm.
domains
being = symbol
predicates
animal(being) % all animals are beings
dog(being) % all dogs are beings
die(being) % all beings die
clauses
animal(X) :- dog(X) % all dogs are animals
dog(fido). % fido is a dog
die(X) :- animal(X) % all animals die

Functional
The Functional Programming paradigm views all subprograms as functions in the
mathematical sense-informally, they take in arguments and return a single solution. The
solution returned is based entirely on the input, and the time at which a function is called
has no relevance. The computational model is therefore one of function application and
reduction.
Languages
Functional languages are created based on the functional paradigm. Such languages
permit functional solutions to problems by permitting a programmer to treat functions as
first-class objects (they can be treated as data, assumed to have the value of what they
return; therefore, they can be passed to other functions as arguments or returned from
functions).

Advantages
The following are desirable properties of a functional language:
-The high level of abstraction, especially when functions are used
- Suppresses many of the details of programming and thus removes the possibility of
committing many classes of errors;
-The lack of dependence on assignment operations, allowing programs to be evaluated in
many different orders. This evaluation order independence makes function-oriented
languages good candidates for programming massively parallel computers;
-The absence of assignment operations makes the function-oriented programs much more
amenable to mathematical proof and analysis than are imperative programs, because
functional programs possess referential transparency.

Disadvantages
Perhaps less efficiency
Problems involving many variables or a lot of sequential activity are sometimes easier to
handle imperatively or with object-oriented programming.

Sample Code of Functional Paradigm.

Function for computing the average of two numbers:

(defun avg(X Y) (/ (+ X Y) 2.0))

Function is called by:

> (avg 10.0 20.0)


Function returns:

15.0

Object-Oriented
Object Oriented Programming (OOP) is a paradigm in which real-world objects are each
viewed as separate entities having their own state which is modified only by built in
procedures, called methods. Because objects operate independently, they are
encapsulated into modules which contain both local environments and methods.
Communication with an object is done by message passing.
Objects are organized into classes, from which they inherit methods and equivalent
variables. The object-oriented paradigm provides key benefits of reusable code and code
extensibility.

Features & Benefits


A new class (called a derived class or subclass) may be derived from another class (called
a base class or superclass) by a mechanism called inheritance. The derived class inherits
all the features of the base class: its structure and behaviour (response to messages). In
addition, the derived class may contain additional state (instance variables), and may
exhibit additional behaviour (new methods to respond to new messages). Significantly, the
derived class can also override behaviour corresponding to some of the methods of the
base class: there would be a different method to respond to the same message. Also, the
inheritance mechanism is allowed even without access to the source code of the base
class.
The ability to use inheritance is the single most distinguishing feature of the OOP paradigm.
Inheritance gives OOP its chief benefit over other programming paradigms - relatively easy
code reuse and extension without the need to change existing source code.
The mechanism of modelling a program as a collection of objects of various classes, and
furthermore describing many classes as extensions or modifications of other classes,
provides a high degree of modularity.
Ideally, the state of an object is manipulated and accessed only by that object's methods.
(Most O-O languages allow direct manipulation of the state, but such access is stylistically
discouraged). In this way, a class' interface (how objects of that class are accessed) is
separate from the class' implementation (the actual code of the class' methods). Thus
encapsulation and information hiding are inherent benefits of OOP.
Sample Code of Object-Oriented Programming Paradigm.

Class:
class data
{
public:
Date(int mn, int dy, int yr); //Constructor
void display(); //Function to print data
~Date(); //Destructor
Private:
int month, day, year; //Private data members
};

Inheritance:
class Employee
{
public:
Employee();
const char *getName() const;
private:
char name[30];
};
class WageEmployee : public Employee
{
public:
WageEmployee(const char *nm);
void setWage(double wg);
void setHours(double hrs);
private:
double:wage;
double:hours;
};
WageEmployee aWorker("Bill Gates");
const char *str;
aWorker.setHours(40.0); //call WageEmployee::setHours
str = aWorker.getName(); //call Employee::getname

Why Study Programming Languages?

Increased capacity to express ideas:

People can easily express their ideas clearly in any language only when they have a clear
understanding of the natural language. Similarly, if programmers want to simulate the
features of languages. In another language, they should have some ideas regarding the
concepts in other

languages as well.

Improved background for choosing appropriate languages

Many programmers when given a choice of languages for a new project, continue to use
the language with which they are most familiar, even if it is poorly suited to the project. If
these programmers were familiar with a wider range of languages, they would be better
able to choose the language that includes the features that best address the characteristics
of the problem at hand.

Increased ability to learn new languages


In software development, continuous learning is essential. The process of learning a new
programming language can be lengthy and difficult, especially for someone who is
comfortable with only two or more languages. Once a thorough understanding of the
fundamental concepts of languages is acquired, it becomes far easier to see how these
concepts are incorporated into the design of the language being learned.

Better understanding the significance of implementation

An understanding of implementation issues leads to an understanding of why languages


are designed the way they are. This knowledge in turn leads to the ability to use a language
more intelligently, as it was designed to use. We can become better programmers by
understanding the choices among programming language constructs and consequences of
those choices.

Better use of languages that are already know

By studying the concepts of programming languages, programmers can learn about


previously unknown and unused parts of the languages they already use and begin to use
those features.

Overall advancement of computing

There is a global view of computing that can justify the study of programming language
concepts.

For example, many people believe it would have been better if ALGOL 60 had displaced
Fortran in the early 1960s, because it was more elegant and had much better control
statements than Fortran. That it did not is due partly to the programmers and software
development managers of that time, many of whom did not clearly understand the
conceptual design of ALGOL 60. If those who choose languages were better informed,
perhaps, better languages would eventually squeeze out poorer ones.

Compilation and Interpretation

The terms compiler and interpreter were explicitly defined on the definition of terms
section. However, this section will elaborate more on what these two terms stand for and
how they work in programming.

Most programs are written in a high-level language such as C, Perl, or Java. Just as a
human language makes it easy for people to communicate with one another, so computer
languages simplify the job of telling a computer what to do. However, because a computer
only understands numbers, talking to one is like speaking to someone with whom you don't
share a language. You need a translator to properly communicate, and that's what
interpreters and compilers do.

An interpreter produces a result from a program. In an interpreted program, the source


code typically is the program. Programs of this type (often known as scripts) require an
interpreter, which parses the commands in the program and then executes them. Some
interpreters, such as the Unix shells (sh, csh, ksh, etc.), read and then immediately execute
each command, while others, such as Perl, analyze the entire script before sending the
corresponding machine language instructions. The advantage of a script is that it is very
portable. Any computer that has the appropriate interpreter installed may run the program
more or less unchanged. This is a disadvantage as well, because the program will not run
at all if the interpreter is not available. In general, interpreted programs are slower than
compiled programs, but are easier to debug and revise. Other examples of interpreted
languages include JavaScript and Python. See diagram below for clear understanding of
how an interpreter works:

A compiler produces a program written in assembly language. The assembler of


architecture then turns the resulting program into binary code. Assembly language varies
for each individual computer, depending upon its architecture. A compiled program is not
human readable, but instead is in an architecture-specific machine language.
Consequently, compiled programs can only run on computers that have the same
architecture as the computer on which they were compiled. Because different kinds of
computers do not speak each other’s' machine languages, a compiled program will only
work on the platform it was designed for. For example, a program written for HP-
UX normally will not work on a Mac OS computer or a computer running Solaris. At the
highest level of abstraction, the compilation and execution of a program in Pure compilation
a high-level language look something like this:
Compiled and interpreted languages Certain languages (e.g., Smalltalk and Python) are
sometimes referred to as “interpreted languages” because most of their semantic error
checking must be performed at run time. Certain other languages (e.g., Fortran and C) are
sometimes referred to as “compiled languages” because almost all of their semantic error
checking can be performed statically. This terminology isn’t strictly correct: interpreters for
C and Fortran can be built easily, and a compiler can generate code to perform even the
most extensive dynamic semantic checks. That said, language design has a profound effect
on “compatibility.”

While the conceptual difference between compilation and interpretation is Mixing


compilation and interpretation clear, most language implementations include a mixture of
both. They typically look like this:

We generally say that a language is “interpreted” when the initial translator is simple. If the
translator is complicated, we say that the language is “compiled.” The distinction can be
confusing because “simple” and “complicated” are subjective terms, and because it is
possible for a compiler (complicated translator) to produce code that is then executed by a
complicated virtual machine (interpreter); this is in fact precisely what happens by default in
Java. We still say that a language is compiled if the translator analyses it thoroughly (rather
than effecting some “mechanical” transformation), and if the intermediate program does not
bear a strong resemblance to the source. These two characteristics—thorough analysis and
nontrivial transformation—are the hallmarks of compilation.
Programming Environments

Compilers and interpreters do not exist in isolation. Programmers are assisted in their work
by a host of other tools.

-The old way used the console and independent tools – UNIX/Linux.

- Assemblers

-compiler

-debugger

- preprocessors

- linkers

- Editors are familiar to every programmer

-Integrated Development Environments provide a graphical interface to most of the


necessary tools. Popular open-source IDEs include Eclipse and NetBeans. Commercial
systems include the Visual Studio environment from Microsoft and the XCode environment
from Apple.

An Overview of Compilation

Compilers are among the most well-studied computer programs. A detailed description of
compilers and how they operate was highlighted under the compilation and interpretation
section. Each phase discovers information of use to later phases, or transforms the
program into a form that is more useful to the subsequent phase. The first few phases (up
through semantic analysis) serve to figure out the meaning of the source program. They are
sometimes called the front end of the compiler. The last few phases serve to construct an
equivalent target program. They are sometimes called the back end of the compiler.

One will sometimes hear compilation described as a series of passes. A pass is a phase or
set of phases that is serialized with respect to the rest of compilation: it does not start until
previous phases have completed, and it finishes before any subsequent phases start. If
desired, a pass may be written as a separate program, reading its input from a file and
writing its output to a file. Compilers are commonly divided into passes so that the front end
may be shared by compilers.
UNIT 2: INTRODUCTION TO C#
The previous unit 1 introduced the student to programming in general. This section focuses
on C# as a programming language.

Introduction to programming concepts, terms and tools in C#

Programming concepts

C# provides full support for object-oriented programming concepts including abstraction,


encapsulation, inheritance, and polymorphism.

-Abstraction means hiding the unnecessary details from type consumers.

-Encapsulation means that a group of related properties, methods, and other members are
treated as a single unit or object.

-Inheritance describes the ability to create new classes based on an existing class.

-Polymorphism means that you can have multiple classes that can be used
interchangeably, even though each class implements the same properties or methods in
different ways.

Important terms in C#

Classes and objects

The terms class and object describe the type of objects, and the instances of classes,
respectively. So, the act of creating an object is called instantiation. Using the blueprint
analogy, a class is a blueprint, and an object is a building made from that blueprint.

To define a class:

class SampleClass

Class members
Each class can have different class members that include properties that describe class
data, methods that define class behaviour, and events that provide communication between
different classes and objects.

Properties and fields

Fields and properties represent information that an object contains. Fields are like variables
because they can be read or set directly, subject to applicable access modifiers.

Methods

A method is an action that an object can perform.

To define a method of a class:

class SampleClass

public int SampleMethod(string sampleParam)

// Insert code here

Best tools for C# programming include:

● Compilers, Editors & Serializers (command line tools)


● IDEs (Integrated Development Environment)
● Decompilers & Code Conversion Tools
● Build Automation & Merge Tools
● Version Control
● Testing Tools & Visual Studio Extensions
● Profilers
● Deployment Automation
● Containerization
● SDK (Software Development Kit"
● Visual Studio, .NET Framework SDK
● Set of useful standard classes
● Microsoft .NET Framework FCL
● Help documentation
● MSDN Library

The standard and history of C#; including C# characteristics- modern,


type safe, versionable, interoperable language etc.)

Standard and history of C#


C# is a modern, general-purpose, object-oriented programming language developed by
Microsoft and approved by European Computer Manufacturers Association (ECMA) and
International Standards Organization (ISO). C# was developed by Anders Hejlsberg and his
team during the development of .Net Framework. C# is designed for Common Language
Infrastructure (CLI), which consists of the executable code and runtime environment that
allows use of various high-level languages on different computer platforms and
architectures. It came out around the year 2000 for the .NET platform. Microsoft’s Anders
Hejlsberg is the principal designer of C#. The “#” comes from the musical notation meaning
C# is higher than C.

First version of C# is 1.0 with .NET framework 1.0 and Visual Studio is 2002.
C# version with .NET framework and CLR version with Visual Studio.
● C# 1.0.NET framework 1.0,1.1 , CLR version 1.0, Visual Studio 2002.
● C# 2.0 .NET framework 2.0 , CLR version 2.0, Visual Studio 2005.
● C# 3.0 .NET framework 3.0,3.5 , CLR version 2.0, Visual Studio 2008.
● C# 4.0 .NET framework 4.0 , CLR version 4.0, Visual Studio 2010.
● C# 5.0 .NET framework 4.5 , CLR version 4.0, Visual Studio 2012,2013.
● C# 6.0 .NET framework 4.6 , CLR version 4.0 ,Visual Studio 2013,2015.
● C# 7.0 .NET framework 4.6,4.6.1,4.6.2 , CLR version 4.0, Visual Studio 2015, 2017
RC.

Why is C# widely used as a professional language?


- It is a modern, general-purpose programming language

- It is object oriented.

- It is component oriented.

-It is easy to learn.

- It is a structured language.

- It produces efficient programs.

- It can be compiled on a variety of computer platforms.

-It is a part of .Net Framework.

Strong Programming Features of C#


Although C# constructs closely follow traditional high-level languages, C and C++ and
being an object-oriented programming language. It has strong resemblance with Java, it
has numerous strong programming features that make it endearing to a number of
programmers worldwide.

Following list shows some important features of C#:

- Boolean Conditions

-Automatic Garbage Collection

-Standard Library

-Assembly Versioning

- Properties and Events

-Delegates and Events Management


-Easy-to-use Generics

- Indexers Conditional Compilation

-Simple Multithreading

-LINQ and Lambda Expressions

-Integration with Windows

The .NET Strategy and or Framework and its Benefits

In the year 2000, Microsoft launched its new development environment, calling it Microsoft

Visual Studio .Net. Microsoft .Net, at its core, is very much similar to J2EE (Java 2

Enterprise Edition), but offered more of a compromise between the traditional 'un-managed'

and the newer 'managed' style of programming. The .Net framework is a revolutionary
platform that helps you to write the following types of applications:

-Windows applications

-Web applications

-Web services

The .Net framework applications are multi-platform applications. The framework has

been designed in such a way that it can be used from any of the following languages:

C#, C++, Visual Basic, Jscript, COBOL, etc. All these languages can access the

framework as well as communicate with each other. The .Net framework consists of an
enormous library of codes used by the client languages such as C#. Following are some of
the components of the .Net framework:

-Common Language Runtime (CLR)

-The .Net Framework Class Library

-Common Language Specification

-Common Type System

-Metadata and Assemblies

-Windows Forms
-ASP.Net and ASP.Net AJAX

-ADO.Net

-Windows Workflow Foundation (WF)

-Windows Presentation Foundation

-Windows Communication Foundation (WCF)

-LINQ

One of the biggest advantages of the .NET Framework is the built-in automatic memory
management. It protects the programmers from the complex task of manually allocating
memory for objects and then waiting for a suitable moment to release it.

Common Language Runtime and its role in .NET framework

The most important concept of the .Net Framework is the existence and functionality of
the .Net Common Language Runtime (CLR), also called .Net Runtime in short. It is a
framework layer that resides above the OS and handles the execution of all the .Net
applications. our programs don't directly communicate with the OS but go through the CLR
as shown in the diagram below:

Benefits of CLR

▪ Managed execution environment (virtual machine)

▪ Executes .NET applications


▪ Controls the execution process

▪ Automatic memory management (garbage collection)

▪ Programming languages integration

▪ Multiple versions support for assemblies

▪ Integrated type safety and security


UNIT 3. C# CONSOLE PROGRAM (SIMPLE C# PROGRAMS)

Software Development Phases

▪ Define a task / problem = Specification

▪ Plan your solution = Architecture /Design

▪ Find suitable algorithm / data structures to use =

▪ Find suitable libraries / platforms / frameworks

▪ Write source code (step by step) = Implementation

▪ Fix program errors (bugs) = testing and debugging

▪ Install, configure and run the software = deployment

▪ Fix / improve the software over the time = maintenance

Console Input and Output Applications

The Console Class

▪ Provides methods for console input and output

▪ Input

▪ Read(…) – reads a single character

▪ ReadKey(…) – reads a combination of keys

▪ ReadLine(…) – reads a single line of characters

▪ Output

▪ Write(…) – prints the specified argument on the console

▪ WriteLine(…) – prints specified data to the console and moves to the


next line

Printing to the Console


▪ The console (terminal window) is used to read / display text-based information in a
virtual terminal window

▪ Can display different values:

▪ Strings

▪ Numeral types

▪ All primitive data types

▪ To print to the console use the Console class (System.Console)

Console.Write(…)

▪ Printing an integer variable

int a = 15;

Console.Write(a); // 15

▪ Printing more than one variable using a formatting string:

double a = 15.5;

int b = 14;

Console.Write("{0} + {1} = {2}", a, b, a + b);

// 15.5 + 14 = 29.5

▪ The next print operation will start from the same line

Printing a string variable + new line (\r\n):

string str = "Hello C#!";

Console.WriteLine(str);

▪ Printing more than one variable using a formatting string:


string name = "Marry";
int year = 1987;
...
Console.WriteLine("{0} was born in {1}.", name, year);
// Marry was born in 1987.
// Interpolated Strings – from C#6 (VS 2015)
Console.WriteLine("{name} was born in {year}.");
Next printing will start from the new line

Printing to the console example


static void Main()
{
string name = "Peter";
int age = 18;
string town = "Sofia";
Console.Write("{0} is {1} years old from {2}.",
name, age, town);
// Result: Peter is 18 years old from Sofia.
Console.Write("This is on the same line!");
Console.WriteLine("Next sentence will be on a new line.");
Console.WriteLine("Bye, bye, {0} from {1}.", name, town);
}

Printing Strings and Numbers

Formatting Strings

{index[,alignment][:formatString]}

index

The zero-based index of the argument whose string representation is to be included at this
position in the string alignment. A signed integer that indicates the total length of the field
into which the argument is inserted

a positive integer – right-aligned

a negative integer – left-aligned

formatString -Specifies the format of the corresponding argument's result string, e.g. "X",
"C", "0.00", e.g.

static void Main()

{
double pi = 1.234;

Console.WriteLine("{0:0.000000}", pi);

// 1.234000

Formatting Strings – Examples

static void Main()

int a = 2, b = 3;

Console.Write("{0} + {1} =", a, b);

Console.WriteLine(" {0}", a + b);

// 2 + 3 = 5

Console.WriteLine("{0} * {1} = {2}", a, b, a * b);

// 2 * 3 = 6

float pi = 3.14159206f;

Console.WriteLine("{0:F2}", pi); // 3,14 or 3.14

Console.WriteLine("Bye – Bye!");

Printing a Menu – Example


double colaPrice = 1.20;

string cola = "Coca Cola";

double fantaPrice = 1.20;

string fanta = "Fanta Dizzy";

double zagorkaPrice = 1.50;

string zagorka = "Zagorka";

Console.WriteLine("Menu:");
Console.WriteLine("1. {0} – {1}", cola, colaPrice);

Console.WriteLine("2. {0} – {1}", fanta, fantaPrice);

Console.WriteLine("3. {0} – {1}", zagorka, zagorkaPrice);

Console.WriteLine("Have a nice day!");

Reading from the Console

We use the Console to read information from the command line.Usually the data is entered
from the keyboard. We can read:

Characters

Strings

Numeral types (after conversion)

To read from the console we use the methods Console.Read() and Console.ReadLine()

Console.Read()

Gets a single character from the console (after [Enter] is pressed)

Returns a result of type int

Returns -1 if there aren’t more symbols

To get the actually read character we need to cast it to char

int i = Console.Read();

char ch = (char) i; // Cast the int to char

// Gets the code of the entered symbol

Console.WriteLine("The code of '{0}' is {1}.", ch, i);

Reading Characters

Console.ReadKey()

Waits until a combination of keys is pressed. Reads a single character from console or a
combination of keys. Returns a result of type ConsoleKeyInfo

KeyChar – holds the entered character


Modifiers – holds the state of [Ctrl], [Alt],

ConsoleKeyInfo key = Console.ReadKey();

Console.WriteLine();

Console.WriteLine("Character entered: " + key.KeyChar);

Console.WriteLine("Special keys: " + key.Modifiers);

Reading Strings

Reading Numeral Types

Numeral types cannot be read directly from the console. To read a numeral type do the
following:

Read a string value

Convert (parse) it to the required numeral type

int.Parse(string)

Parses (converts) a string to int

string str = Console.ReadLine()

int number = int.Parse(str);

Console.WriteLine("You entered: {0}", number);

Parsing Strings to Numeral Types

Numeral types have a method Parse (…) for extracting the numeral value from a string

int.Parse(string) – string int

long.Parse(string) – string long

float.Parse(string) – string float

Causes FormatException in case of error

string s = "123";
int i = int.Parse(s); // i = 123

long l = long.Parse(s); // l = 123L

string invalid = "xxx1845";

int value = int.Parse(invalid); // FormatException

Reading Numeral Types

Reading Numbers from the Console – Example

static void Main()

int a = int.Parse(Console.ReadLine());

int b = int.Parse(Console.ReadLine());

Console.WriteLine("{0} + {1} = {2}", a, b, a+b);

Console.WriteLine("{0} * {1} = {2}", a, b, a*b);

float f = float.Parse(Console.ReadLine());

Console.WriteLine("{0} * {1} / {2} = {3}", a, b, f, a*b/f);

}
LECTURE 4. OPERATORS, TYPES AND VARIABLES
Operator is an operation performed over data at runtime. Takes one or more arguments
(operands) and produces a new value

Example of operators: a= b+c .in this case = and + are operators

Operators have precedence

Precedence defines which will be evaluated first. Expressions are sequences of operators
and operands that are evaluated to a single value, e.g. (a + b) / 2

Explain Types of Operators.

Types of Operators in C#

Define Mixed Mode Arithmetic Expression and How Is It Evaluated?

If operands in an expression contain both INTEGER and REAL constants or variables, this
is a mixed mode arithmetic expression. In mixed mode arithmetic expressions, INTEGER
operands are always converted to REAL before carrying out any computations. As a result,
the result of a mixed mode expression is of REAL type. The following is a table showing this
fact:

Operator INTEGER REAL


INTEGER INTEGER REAL
REAL REAL REAL

The rules for evaluating mixed mode arithmetic expressions are simple:

● Use the rules for evaluating single mode arithmetic expressions for scanning.
● After locating an operator for evaluation, do the following:

-if the operands of this operator are of the same type, compute the result of this
operator.

-otherwise, one of the operands is an integer while the other is a real number. In this
case, convert the integer to a real (i.e., adding .0 at the end of the integer operand)
and compute the result. Note that since both operands are real numbers, the result is
a real number.

● There is an exception, though. In a**n, where a is a real and n is a positive


integer, the result is computed by multiplying n copies of a. For example, 3.5**3 is
computed as 3.5*3.5*3.5

Simple Examples:

● 1 + 2.5 is 3.5
● 1/2.0 is 0.5
● 2.0/8 is 0.25
● -3**2.0 is -9.0
● 4.0**(1/2) is first converted to 4.0**0 since 1/2 is a single mode expression whose
result is 0. Then, 4.0**0 is 1.0

Illustrate Shorthand Assignment and Its Advantages

C# supports a short variant of assignment operator called compound assignment or


shorthand assignment. Shorthand assignment operator combines one of
the arithmetic or bitwise operators with assignment operator.
Advantages of Shorthand assignment operators

Firstly, they produce more compact code; they are often called shorthand operators for this
reason. Secondly, the variable being operated upon, or operand, will only be evaluated
once in the compiled application. This can make the code more efficient.

Define Boxing and Unboxing

Boxing is the process of converting a value type to the type object or to any interface type
implemented by this value type. When the common language runtime (CLR) boxes a value
type, it wraps the value inside a System. Object instance and stores it on the managed
heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is
explicit. The concept of boxing and unboxing underlies the C# unified view of the type
system in which a value of any type can be treated as an object.

In the following example, the integer variable i is boxed and assigned to object o.

int i = 123;

// The following line boxes i.

object o = i;
The object o can then be unboxed and assigned to integer variable i:

o = 123;

i = (int)o; // unboxing

Define Jagged and Rectangular Arrays(Distinguish)

Jagged Arrays-A Jagged array is an array of arrays. You can declare a jagged array named

scores of type int as: int [][] scores;

To create the jagged array example below:

int[][] scores = new int[5][];

for (int i = 0; i < scores.Length; i++)

scores[i] = new int[4];

initialize a jagged array as:

int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};

Truncate to Specified Decimal Places

This method is used to get the integral digits of the specified Decimal by discarding any
fractional digits. This method rounds the specified value to the nearest whole number by
removing the digits after the decimal point.

Syntax: public static decimal Truncate (decimal d);


Here, d is the decimal number which is to be truncated.

Return Value: It returns the result of d rounded toward zero, to the nearest whole number.

Example:
filter_none
edit
play_arrow
brightness_4
// C# program to demonstrate the
// Decimal.Truncate(Decimal) Method
using System;
class GFG {
// Main Method
public static void Main()
{
try {
// Taking decimal variables
// having fractional part
Decimal dec1 = 214748.78549M;
Decimal dec2 = 21458565.2996m;
// using Decimal.Truncate(Decimal) Method
Decimal val1 = Decimal.Truncate(dec1);
// using Decimal.Truncate(Decimal) Method
Decimal val2 = Decimal.Truncate(dec2);
// Printing the Integral part only
Console.WriteLine("The integral part of "+
"dec1 is: {0}", val1);
Console.WriteLine("The integral part of "+
"dec2 is: {0}", val2);
}
catch (OverflowException e) {
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
Output:

The integral part of dec1 is: 214748


The integral part of dec2 is: 21458565
UNIT 5 CONTROL STATEMENTS

● Conditional Statements,
● Loops, Jump Statements
● Implementation of Continue and Break Statements in Loops

Control Statements

In C#, Control structures are used to alter the flow of execution of the program. Why do we
need to alter the program flow? The reason is “decision making “! In life, we may be given
a set of options like doing “Computer Science” or “Information System”. We do make a
decision by analyzing certain conditions (like our personal interest, scope of job
opportunities etc.). With the decision we make, we alter the flow of our life’s direction. This
is exactly what happens in a C# program. We use control structures to make decisions and
alter the direction of program flow in one or the other path(s) available.

Types of Control Structures in C#

● Sequence structure (straight line paths)


● Selection structure (one or many branches)
● Loop structure (repetition of a set of activities)

Conditional statements

● If statement;
● else if statement;
● else statement

Conditional Statement if
The main format of the conditional statements if is as follows:

if (Boolean expression)
{
body of the conditional statement;
}

It includes: if-clause, Boolean expression and body of the conditional statement.

● The Boolean expression can be a Boolean variable or Boolean logical expression.


Boolean expressions cannot be integer (unlike other programming languages like C and
C++).
● The body of the statement is the part locked between the curly brackets: {}. It may
consist of one or more operations (statements). When there are several operations, we
have a complex block operator, i.e. series of commands that follow one after the other,
enclosed in curly brackets.
● The expression in the brackets which follows the keyword if must return the Boolean
value true or false. If the expression is calculated to the value true, then the body of a
conditional statement is executed. If the result is false, then the operators in the body
will be skipped.

CONDITIONAL STATEMENT "IF" – EXAMPLE

Let’s take a look at an example of using a conditional statement if statement:

static void Main()


{
console.writeLine ("Enter two numbers.");
console.write("Enter first number: ");
int firstNumber = int.Parse(Console.ReadLine());
console.write("Enter second number: ");
int secondNumber = int.Parse(Console.ReadLine());
int biggerNumber = firstNumber;
if (secondNumber > firstNumber)
{
biggerNumber = secondNumber;
}
console.writeLine("The bigger number is: {0}", biggerNumber);
}

If we start the example and enter the numbers 4 and 5 we will get the following result:

Enter two numbers.


Enter first number: 4
Enter second number:5
The bigger number is:5
Conditional Statement "if" and Curly Brackets

If we have only one operator in the body of the if-statement, the curly brackets denoting the
body of the conditional operator may be omitted, as shown below. However, it is a good
practice to use them even if we have only one operator. This will make the code is more
readable.
Here is an example of omitting the curly brackets which leading to confusion:

int a = 6;
if (a > 5)
console.writeLine ("The variable is greater than 5.");
console.writeLine ("This code will always execute!");
// Bad practice: misleading code

In this example the code is misleadingly formatted and creates the impression that both
printing statements are part of the body of the if-block. In fact, this is true only for the first
one.

Always put curly brackets { } for the body of “if” blocks even if they consist of only one
operator!

Conditional Statement "if-else"


In C#, as in most of the programming languages there is a conditional statement with else
clause: the if-else statement. Its format is the following:
Syntax format for If.. Else statement is shown below.
if(expression 1)// Expression 1 is evaluated. If TRUE,
statements inside the curly braces are executed. { //If FALSE
program control is transferred to immediate else if statement.
statement 1; statement 2; }else if(expression 2)// If expression
1 is FALSE, expression 2 is evaluated. {Statement 1;
statement 2; }else if(expression 3) // If expression 2 is FALSE,
expression 3 is evaluated {statement 1; statement 2; }else // If
all expressions (1, 2 and 3) are FALSE, the statements that
follow this else (inside curly braces) is executed. {statement 1;
statement 2; }

Comments:

The format of the if-else structure consists of the reserved word if, Boolean expression,
body of a conditional statement, reserved word else and else-body statement. The body of
else-structure may consist of one or more operators, enclosed in curly brackets, same as
the body of a conditional statement.
This statement works as follows: the expression in the brackets (a Boolean expression) is
calculated. The calculation result must be Boolean – true or false. Depending on the result
there are two possible outcomes. If the Boolean expression is calculated to true, the body
of the conditional statement is executed and the else-statement is omitted and its
operators do not execute. Otherwise, if the Boolean expression is calculated to false, the
else-body is executed, the main body of the conditional statement is omitted and the
operators in it are not executed.

Conditional Statement "if-else" – Example

Let’s take a look at the next example and illustrate how the if-else statement works:

static void Main()


{
int x = 2;
if (x > 3)
{
Console.WriteLine("x is greater than 3");
}
else
{
Console.WriteLine("x is not greater than 3");
}
}

The program code can be interpreted as follows: if x>3, the result at the end is: "x is
greater than 3", otherwise (else) the result is: "x is not greater than 3". In this case, since
x=2, after the calculation of the Boolean expression the operator of the else structure will
be executed. The result of the example is:

x is not greater than 3

The following scheme illustrates the process flow of this example:


Nested "if" Statements
Sometimes the programming logic in a program or an application needs to be represented
by multiple if-structures contained in each other. We call them nested if or nested if-else
structures.
We call nesting the placement of an if or if-else structure in the body of another if or else
structure. In such situations every else clause corresponds to the closest previous if
clause. This is how we understand which else clause relates to which if clause.

Nested "if" Statements – Example


Here is an example of using nested if structures:

int first = 5;
int second = 3;
if (first == second)
{
console.writeLine ("These two numbers are equal.");
}
else
{
if (first > second)
{
console.writeLine ("The first number is greater.");
}
else
{
console.writeLine ("The second number is greater.");
}
}

In the example above we have two numbers and compare them in two steps: first we
compare whether they are equal and if not, we compare again, to determine which one is
the greater. Here is the result of the execution of the code above:

The first number is greater.


SEQUENCES OF "IF-ELSE-IF-ELSE-…"

Sometimes we need to use a sequence of if structures, where the else clause is a new if
structure. If we use nested if structures, the code would be pushed too far to the right.
That’s why in such situations it is allowed to use a new if right after the else. It’s even
considered a good practice. Here is an example:
char ch = 'X';
if (ch == 'A' || ch == 'a')
{
Console.WriteLine("Vowel [ei]");
}
else if (ch == 'E' || ch == 'e')
{
Console.WriteLine("Vowel [i:]");
}
else if (ch == 'I' || ch == 'i')
{
Console.WriteLine("Vowel [ai]");
}
else if (ch == 'O' || ch == 'o')
{
Console.WriteLine("Vowel [ou]");
}
else if (ch == 'U' || ch == 'u')
{
Console.WriteLine("Vowel [ju:]");
}
else
{
Console.WriteLine("Consonant");
}

The program in the example makes a series of comparisons of a variable to check if it is


one of the vowels from the English alphabet. Every following comparison is done only in
case that the previous comparison was not true. In the end, if none of the if-conditions is
not fulfilled, the last else clause is executed. Thus, the result of the example is as follows:
Consonant

CONDITIONAL "IF" STATEMENTS – GOOD PRACTICES

Here are some guidelines, which we recommend for writing if, structures:

● Use blocks, surrounded by curly brackets {} after if and else in order to avoid ambiguity

● Always format the code correctly by offsetting it with one tab inwards after if and else,
for readability and avoiding ambiguity.

Exercises

1. Write an if-statement that takes two integer variables and exchanges their values if the
first one is greater than the second one.
2. Write a program that shows the sign (+ or -) of the product of three real numbers, without
calculating it. Use a sequence of if operators.

3. Write a program that finds the biggest of three integers, using nested if statements.

4. Sort 3 real numbers in descending order. Use nested if statements.

5. Write a program that asks for a digit (0-9), and depending on the input, shows the digit
as a word (in English). Use a switch statement.

6. Write a program that gets the coefficients a, b and c of a quadratic equation: ax2 + bx +
c, calculates and prints its real roots (if they exist). Quadratic equations may have 0, 1 or 2
real roots.

7. Write a program that finds the greatest of given 5 numbers.

8. Write a program that, depending on the user’s choice, inputs int, double or string
variable. If the variable is int or double, the program increases it by 1. If the variable is a
string, the program appends "*" at the end. Print the result at the console. Use switch
statement.

LOOP STATEMENTS

● Loops are structures that control repeated executions of a block of statements.


● Part of the loop that contains the statements to be repeated is called the loop body.
● A one-time execution of a loop body is referred to as an iteration of the loop.
● Each loop contains a loop-continuation-condition, a Boolean expression that controls the
execution of the body.
● After each iteration, the loop-continuation-condition is revaluated. If the condition is
true, the execution of the loop body is repeated. If the condition is false, the loop
terminates.
● Loops that never end are called infinite loops. Using an infinite loop is rarely needed
except in cases where somewhere in the body of the loop a break operator is used to
terminate its execution prematurely. We will cover this later but now let’s look how to
create a loop in the C# language

The While Loop


One of the simplest and most commonly used loops is while.
􀂃 The syntax for the while loop is as follows:

while (condition) {
// loop-body
statement(s);
}

In the syntax above example, condition is any expression that returns a Boolean result
– true or false. It determines how long the loop body will be repeated and is called the loop
condition. In this example the loop body is the programming code executed at each
iteration of the loop, i.e. whenever the input condition is true.

In the while loop, first of all the Boolean expression is calculated and if it is true the
sequence of operations in the body of the loop is executed. Then again the input condition
is checked and if it is true again the body of the loop is executed. All this is repeated again
and again until at some point the conditional expression returns value false. At this
point the loop stops and the program continues to the next line, immediately after the body
of the loop.
The body of the while loop may not be executed even once if in the beginning the condition
of the cycle returns false. If the condition of the cycle is never broken the loop will be
executed indefinitely.

Example of While Loops


Let’s consider a very simple example of using the while loop. The purpose of the loop is to
print on the console the numbers in the range from 50 to 60 in ascending order:

// Initialize the counter


int counter = 50;
// Execute the loop body while the loop condition holds
while (counter <= 60)
{
// Print the counter value
Console.WriteLine("Number : " + counter);
// Increment the counter
counter++;
}

When executing the sample code, we obtain the following result:

Number :50

When executing the above program, the output will be:

Number: 50
Number: 51
Number: 52
Number: 53
Number: 54
Number: 55
Number: 56
Number: 57
Number: 58
Number: 59
Number: 60

Do-While Loops
The do-while loop is similar to the while loop, but it checks the condition after each
execution of its loop body. This type of loops is called loops with condition at the end (post-
test loop). A do-while loop looks like this:

do

{executable code;
}
while (condition);

Initially the loop body is executed. Then its condition is checked. If it is true, the loop’s
body is repeated, otherwise the loop ends. This logic is repeated until the condition of the
loop is broken. The body of the loop is executed at least once. If the loop’s condition is
constantly true, the loop never ends.

The do-while loop is used when we want to guarantee that the sequence of operations in it
will be executed repeatedly and at least once in the beginning of the loop.

Example of the do .. while loop statement


In this example we will again calculate the factorial of a given number n, but this time
instead of an infinite while loop we will use a do-while. The logic is similar to that in the
previous example:

Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
decimal factorial = 1;
do
{
factorial *= n;
n--;
} while (n > 0);
Console.WriteLine("n! = " + factorial);

At the beginning we start with a result of 1 and multiply consecutively the result at each iteration by n, and red

Here is the result of the above example’s execution for n=5:

n=5
n!=120

For Loops
For-loops are a slightly more complicated than while and do-while loops but on the other
hand they can solve more complicated tasks with less code. Here is the scheme describing
for-loops:
Syntax is: for (initialization; condition; increase) statement;

its main function is to repeat statement while condition remains true, like the while loop. But
in addition, the for loop provides specific locations to contain an initialization statement and
an increase statement. So this loop is specially designed to perform a repetitive action with
a counter which is initialized and increased on each iteration.

It works in the following way:

1. initialization is executed. Generally, it is an initial value setting for a counter variable. This
is executed only once.
2. condition is checked. If it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).
3. statement is executed. As usual, it can be either a single statement or a block enclosed
in braces { }.
4. Finally, whatever is specified in the increase field is executed and the loop gets back to
step 2.

Here is an example of countdown using a for loop:

for (int i = 10; i >= 0; i++)


{
Console.Write(i + " ");
}
Foreach Loops
The foreach loop (extended for-loop) is new for the C/C++/C# family of languages, but is
well known for the VB and PHP programmers. This programming construct serves to
iterate over all elements of an array, list or other collection of elements (IEnumerable). It
passes through all the elements of the specified collection even if the collection is not
indexed.

foreach (type variable in collection)


{
statements;
}

Exercises
1. Write a program that prints on the console the numbers from 1 to N. The number N
should be read from the standard input.

2. Write a program that prints on the console the numbers from 1 to N, which are not
divisible by 3 and 7 simultaneously. The number N should be read from the standard
input.

3. Write a program that reads from the console a series of integers and prints the smallest
and largest of them.
4. Write a program that reads from the console number N and print the sum of the first N
members of the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,

5. Write a program that by a given integer N prints the numbers from 1 to N in random
order
UNIT 6 METHODS
● Introduction to Methods
● Method Declaration (Function Prototype), Method Implementation (Definition) And
Invoking Methods in Main Function.
● Concept of Pass by Value and Pass by Reference
● Returning a Result from a Function
● Execution of A Program with More Than One Class

Introduction to methods

A method is a group of statements that together perform a task. Every program has at least
one class with a method named Main. Methods are extremely useful because they allow
you to separate your logic into different units. You can pass information to methods, have it
perform one or more statements, and retrieve a return value. The capability to pass
parameters and return values is optional and depends on what you want the method to do.

To Use a method, you need to:


● Define a method
● Call the method

Defining Methods in C#

When you define a method, you basically declare the elements of its structure. A method
consists of the following 5 elements:
❖ Access Specifier
❖ Return Type
❖ Method Name
❖ Parameter List
❖ Method Body

❖ Access Specifier
This determines the visibility of a variable or a method from another class.

❖ Return Type
A method may return a value. The return type is the data type of the value the method
returns. If the method is not returning any values, then the retype is void.

❖ Method Name
The method name is a unique identifier and it is case sensitive. It cannot be the same as
any other identifier declared in the class,

❖ Parameter List
Enclosed between parentheses, the parameters are used to pass and receive data from a
method. The parameters list refers to the type, order, and number of the parameters of a
method. Parameters are optional; that is, a method may contain no parameters.

❖ Method Body
This contains the set of instructions needed to complete required activity.
Method Declaration (Function Prototype), Method Implementation (Definition) And
Invoking Methods in Main Function

This section outlines how to distinguish three different actions related to existing of a
method:
i) Declaring;
ii) Implementation (creation);
iii) Calling of a method.

Declaring a method
We call method registration in the program, so it can be successfully identified in the rest of
the program. Before we learn how to declare a method, it is important to know where we
are allowed to do it.

Where Is Method Declaration Allowed?


● Although we still haven’t explained how to declare a class. We know that every class
has opening and closing curly brackets – "{" and "}", between which the program
code is placed. A method exists only if it is declared between the opening and
closing brackets of a class – "{" and "}".
● In addition, a method cannot be declared inside another method's body (this will be
clarified later).
● In the C# language, a method can be declared only between the opening "{"
and the closing "}" brackets of a class.

A typical example for a method is the already known method Main (…) – that is always
declared between the opening and the closing curly brackets of our class. An example for
this is shown below: HelloStudents.cs
public class HelloStudents
{ // Opening brace of the class

// declaring our method between the class' body braces


static void Main(string[] args)
{
console.writeLine ("Welcome to Information System Department!");
}
} // Closing brace of the class

Method Declaration
To declare a method means to register the method in our program. This is shown with the
following declaration:

[static] <return_type> <method_name>([<param_list>])

There are some mandatory elements to declare method:


- Type of the result, returned by the method – <return_type>.

- Method’s name – <method_name>.

- List of parameters to the method – <param_list> – it can be empty list or it can consist of
a sequence of parameters declarations.

To clarify the elements of method’s declaration, we can use the Main(…) method from
the example HelloStudents show in the previous block:

static void Main(string[] args)


As can be seen the type of returned value is void (i.e. that method does not return a
result), the method’s name is Main, followed by round brackets, between which is a list with
the method’s parameters. In the particular example it is actually only one parameter – the
array string[] args.
The sequence, in which the elements of a method are written, is strictly defined. Always, at
the very first place, is the type of the value that method returns <return_type>, followed by
the method’s name <method_name> and list of parameters at the end <param_list>
placed between in round brackets – "(" and ")". Optionally the declarations can have
access modifiers (as public and static).

NB:
● When a method is declared keep the sequence of its elements description: first is the
type of the value that the method returns, then is the method’s name, and at the end
is a list of parameters placed in round brackets.

● The list with parameters is allowed to be void (empty). In that case the only thing we
have to do is to type "()" after the method’s name. Although the method has not
parameters the round brackets must follow its name in the declaration.

● The round brackets – "(" and ")", are always placed after the method’s name, no matter
whether it has or has not any parameters.

For now, we will not focus on what <return_type> is. For now, we will use void, which
means the method will not return anything. Later, we will see how that can be changed
The keyword static in the description of the declaration above is not mandatory but should
be used in small simple programs. It has a special purpose that will be explained later in
this chapter. Now the methods that we will use for example, will include the keyword static
in their declaration. More about methods that are not declared as static will be discussed in
the chapter "Defining Classes", section "Static Members".

Method Signature
Before we go on with the basic elements from the method’s declaration, we must pay
attention to something more important. In object-oriented programming a method is
identified by a pair of elements of its declaration: name of the method, and list of
parameters. These two elements define the so-called method specification (often can be
found as a method signature).
C#, as a language used for object oriented programming, also distinguishes the methods
using their specification (signature) – method’s name <method_name> and the list with
parameters – <param_list>.
Here we must note that the type of returned value of a method is only part of its declaration,
not of its signature.

NB:
What identifies a method is its signature. The return type is not part of the method signature. The
reason is that if two methods differ only by their return value types, for the program is not clear
enough which of them must be called.

Method Names
Every method solves a particular task from the whole problem that our program solves.
Method’s name is used when method is called. Whenever we call (start) a particular
method, we type its name and if necessary we pass values (if there are any).
In the example below, the name of our method is PrintLogo:

static void PrintLogo()


{
console.WriteLine("Microsoft");
console.WriteLine("www.microsoft.com");
}

Rules to Name a Method


It is recommended, when declare a method, to follow the rules for method naming
suggested by Microsoft:
- The name of a method must start with a capital letter.

- The PascalCase rule must be applied, i.e. each new word that concatenates so to form
the method name, must start with capital letter.

- It is recommended that the method name must consist of verb, or verb and noun.
Note that these rules are not mandatory, but recommendable. If we aim our C# code to
follow the style of all good programmers over the globe, we must use Microsoft’s code
convention. A more detailed recommendation about method naming will be given in the
chapter "High-Quality Code", section "Naming Methods".
Here some examples for well named methods:

● Print
● GetName
● PlayMusic
● SetUserName
And some examples for bad named methods:

Abc11
Yellow___Black
foo
_Bar

It is very important that the method name describes the method’s purpose. All behind this
idea is that when a person that is not familiar with our program reads the method name,
they can easily understand what that method does, without the need to look at the method’s
source code.

NB: To name a method it is good to follow these rules:


- Method name must describe the method’s purpose.
- Method name must begin with capital letter.
The PascalCase rule must be applied.
- The method name must consist of verb, or verb and noun.

Modifiers
A modifier is a keyword in C#, which gives additional information to the compiler for a
certain code.
We have already met some modifiers – public and static. Now we will briefly describe what
modifiers are actually. Detailed description will be given later in the chapter "Defining
Classes", section "Access Modifiers". So let’s begin with an example:

public static void PrintLogo()


{
Console.WriteLine("Microsoft");
Console.WriteLine("www.microsoft.com");
}

With this example we define a public method by the modifier public. It is a special type
modifier, called also access modifier and is used to show that method can be called by
any C# class, no matter where it is. Public modifiers are not restricted in the meaning of
“who” can call them.
Another example for an access modifier, that we can meet, is the private modifier. Its
function is opposite to that of the public, i.e. if a method is declared by access modifier
private, it cannot be called from anywhere, except from the class in which it is declared.
If a method is declared without an access modifier (either public or private), it is
accessible from all classes in the current assembly, but not accessible for any other
assemblies (let say from other projects in Visual Studio). For the same reason, when we
are writing small programs, like those in this chapter, we will not specify access modifiers.
For now, the only thing that has to be learned is that in method declaration there cannot be
more than one access modifier.
When a method has a keyword static, in its declaration, this method is called static. To call
a static method there is no need to have an instance of a class in which the static method is
declared. For now the reader can accept that, the methods must be static. Dealing with
non-static methods will be explained in the chapter "Defining Classes", section "Methods".

IMPLEMENTATION (CREATION) OF OWN METHOD

Implementation (creation) of a method is the process of typing the code that resolves a
particular task. This code is in the method itself and represents its logic.
Method call is the process that invokes the already declared method, from a part of the
code, where a problem, that the method resolves, must be solved.
After a method has been declared, we must write its implementation. As we already
explained above, implementation (body) of the method consists of the code, which will be
executed by calling the method. That code must be placed in the method’s body and it
represents the method’s logic.
The Body of a Method
Method body we call the piece of code, that is placed in between the curly brackets "{" and
"}", that directly follow the method declaration.

static <return_type> <method_name>(<parameters_list>)


{
// … code goes here – in the method's body …
}

The real job, done by the method, is placed exactly in the method body. So, the algorithm
used in the method to solve the particular task is placed in the method body.
So far we have seen many examples of method body however, we will show one more with
the code below:

static void PrintLogo()


{ // Method's body starts here
Console.WriteLine("Microsoft");
Console.WriteLine("www.microsoft.com");
} // … And finishes here

Local Variables
Whenever we declare a variable inside the body of a method, we call that local variable for
the method. To name a variable we should follow the identifiers rules in C# (refer to chapter
"Primitive Types and Variables").
The area where a local variable exists, and can be used, begins from the line where the
variable is declared and ends at the closing curly bracket "}" of the method body. This is the
so-called area of visibility of the variable (variable scope). If we try to declare a variable,
after we have already declared a variable with the same name, the code will not compile
due to an error. Let’s look at the example below:

static void Main()


{
int x = 3;
int x = 4;
}
Compiler will not let’s use the name x for two different variables, and will return a message
similar to the one below:

A local variable named 'x' is already defined in this scope.


<method_name>();

Later will see an example for when the invoked method has a parameter list (in the case
here the method has no parameters).
To clarify how method invocation works, the next fragment shows how the method
PrintLogo() will be called

PrintLogo()
;
Result of method’s execution is:

Microsoft
www.microsoft.com

WHO TAKES CONTROL OVER THE PROGRAM WHEN WE INVOKE A


METHOD?

When a method executes it takes control over the program. If in the caller method,
however, we call another one, the caller will give the control to the called method. The
called method will return back the control to the caller right after its execution finishes. The
execution of the caller will continue from that line, where it was before calling the other
method.
For example, let’s call PrintLogo() from the Main() method:
First the code of method Main(), that is marked with (1) will be executed, then the control of
the program will be given to the method PrintLogo() – the dotted arrow (2). This will cause
the execution of the code in method PrintLogo(), numbered with (3). When the method
PrintLogo() work is done, the control over the program is returned back to the method
Main() – dotted arrow (4). Execution of Main() will continue from the line after PrintLogo()
call – marked with (5).

Where a Method Can Be Invoked From?


A method can be invoked from the following places:
- From the main program method – Main():
static void Main()
{
PrintLogo();
}

From some other method:

static void PrintLogo()


{
Console.WriteLine("Microsoft");
Console.WriteLine("www.microsoft.com");
}
static void PrintCompanyInformation()
{
// Invoking the PrintLogo() method
PrintLogo();
Console.WriteLine("Address: One, Microsoft
Way");

Exercise
1. Write a code that by given name prints on the console "Hi, <Surname>!" (for example:
"Hi, Chitova!").

2. Create a method GetMax() with two integer (int) parameters, that returns the maximal of
the two numbers. Write a program that reads three numbers from the console and prints the
biggest of them. Use the GetMax() method you just created. Write a test program that
validates that the methods work correctly.

3. Write a method that returns the English name of the last digit of a given number.
Example: for 512 prints "two"; for 1024  "four".

4. Write a program that calculates and prints the n! for any n in the range [1…100].
UNIT 7 STRINGS AND REGULAR EXPRESSIONS
● Introduction to String
● Declaring and Initializing Strings
● String Operations
● Constructing Strings
● String Formatting and Regular Expressions

Introduction Strings

A string is a sequence of characters stored in a certain address in memory. Remember


the type char? In the variable of type char we can record only one character. Where it is
necessary to process more than one character then strings come to our aid. In C#, you can
use strings as arrays of characters. However, more common practice is the use of the string
keyword to declare a string variable. The string keyword is an alias for the System.String
class.
The System.String Class

The class System.String enables us to handle strings in C#. For declaring the strings we
will continue using the keyword string, which is an alias in C# of the System.String class
from .NET Framework. The work with string facilitates us in manipulating the text content:
construction of texts, text search and many other operations.
Example of declaring a string:

String greeting = “Hello, C#”;


We have just declared the variable greeting of type string whose content is the text phrase
"Hello, C#". The representation of the content in the string looks closely to this:

H e l l o, C #
The internal representation of the class is quite simple – an array of characters. We can
avoid the usage of the class by declaring a variable of type char[] and fill in the array’s
elements character by character. However, there are some disadvantages too:
1. Filling in the array happens character by character, not at once.
2. We should know the length of the text in order to be aware whether it will fit into the
already allocated space for the array.

3. The text processing is manual.

The String Class: Universal Solution?


The usage of the system. string is not the ideal and universal solution – sometimes it is
appropriate to use different character structures.
In C# we there are other classes for text processing – we will become familiar with some of
them later in this chapter.
The type string is more special from other data types. It is a class and as such it complies
with the principles of object-oriented programming. Its values are stored in the dynamic
memory (managed heap), and the variables of type string keep a reference to an object
in the heap.

Strings are Immutable


The string class has an important feature – the character sequences stored in a variable of
the class are never changing (immutable). After being assigned once, the content of the
variable does not change directly – if we try to change the value, it will be saved to a new
location in the dynamic memory and the variable will point to it. Since this is an important
feature, it will be illustrated later.
Strings and Char Arrays
Strings are very similar to the char arrays (char[]), but unlike them, they cannot be
modified. Like the arrays, they have properties such as Length, which returns the length of
the string and allows access by index. Indexing, as it is used in arrays, takes indices from 0
to Length-1. Access to the character of a certain position in a string is done with the
operator [] (indexer), but it is allowed only to read characters (and not to write to them):

string str = "abcde";


char ch = str[1]; // ch == 'b'
str[1] = 'a'; // Compilation error!
ch = str[50]; // IndexOutOfRangeException

Strings – Simple Example


Let’s give an example for using variables from the type string:
string message = "This is a sample string message.";
Console.WriteLine("message = {0}", message);
Console.WriteLine("message.Length = {0}", message.Length);
for (int i = 0; i < message.Length; i++)
{
Console.WriteLine("message[{0}] = {1}", i, message[i]);
}
// Console output:
// message = This is a sample string message.
// message.Length = 31
// message[0] = T
// message[1] = h
// message[2] = i
// message[3] = s
//

Please note the string value – the quotes are not part of the text, they are enclosing its
value. The example demonstrates how to print a string, how to extract its length and how to
extract the character from which it is composed.

Declaring a String

We can declare variables from the type string by the following rule:

string str;

Declaring a string represents a variable declaration of type string. This is not equivalent
to setting a variable and allocating memory for it! With the declaration we inform the
compiler that the variable str will be used and the expected type for it is string. We do not
create a variable in the memory and it is not available for processing yet (value is null,
which means no value).

Creating and Initializing a String


In order to process the declared string variable, we must create it and initialize it. Creating a
variable of a certain class (also known as instantiating) is a process associated with the
allocation of the dynamic memory area (the heap). Before setting a specific value to the
string, its value is null. This can be confusing to the beginner programmers: uninitialized
variables of type string do not contain empty values, it contains the special value null –
and each attempt for manipulating such a string will generate an error (exception for access
to a missing value NullReferenceException)!
We can initialize variables in the following three ways:
1. By assigning a string literal.

2. By assigning the value of another string.

3. By passing the value of an operation which returns a string.

Setting a String Literal


Setting a string literal means to assign a predefined textual content to a variable of type
string. We use this type of initialization, when we know the value that must be stored in the
variable. Example for setting a string literal:
String website= “http://ww5.msu.ac.zw”;

In this example we created the variable website with value the above stated string literal.

OPERATIONS FOR MANIPULATING STRINGS

Once we got familiar with the fundamentals of strings and their structure, the next thing to
explore are the tools for their processing. We will review string concatenation, searching
in a string, extracting substrings, changing the character casing, splitting a string by
separator and other string operations that will help us solve various problems from the
everyday practice.

It is possible to process strings without creating new objects in the memory every time a
modification is made but for this purpose the class StringBuilder should be used.

Strings Concatenation
Joining two strings and obtaining a new one as a result is called concatenation. It could be
done in several ways: through the method Concat(…) or with the operators + and +=.
Example of using the method Concat(…):

string Name = “Bothell,”;


string Surname=”Gumbo!, “;
string Result = string.concat (Name, Surname);

By calling the method, we will concatenate the string variable name, which is passed as an
argument, to the string variable surname. The result string will be the text Bothell,
Gumbo!".
The second way for concatenation is via the operators + and +=. Then the above example
can be implemented in the following way:

string Name = “Bothell,”;


string Surname=”Gumbo!, “;
string Result = Name + Surname;

Please note that string concatenation does not change the existing strings but returns a
new string as a result. If we try to concatenate two strings without storing them in a variable,
the changes would not be saved. Here is a typical mistake:

string Name = “Bothell,”;


string Surname=”Gumbo!, “;
string Result = string.concat (Name, Surname);

In the given example the two variables are concatenated but the result of it has not been
saved anywhere, so it is lost:
If we want to add a value to an existing variable, for example the variable result, we can do
it with the well-known code:
string Result = Result + “God Bless you”;

In order to avoid the double writing of the above declared variable, we can use the operator
+=:
Result +=”God Bless you”;
The result will be the same in both cases: "Bothell, Gumbo! God Bless you".
We can concatenate other data with strings. Any data, which can be presented in a text
form, can be appended to a string. Concatenation is possible with numbers, characters,
dates, etc. Here is an example:
String message = “The number of modules is: “;
Int Modules = 30;
String Result = message + Modules;
// The number of the modules is : 30
As we understood from the above example, there is no problem in concatenating strings
with other data, which is not from a string type. Let’s have another full example for string
concatenation:
public Class DisplayUserInfo
{
Static void Main ()
{
String firstnameName = “Mary”;
String LastName=”Jones”;
String FullName = firstName + “ ” ++ LastName;
int age = 35;
String nameAndAge = “ Name: “+ fullName + “\nAge: “ + age

Console. Write (nameAndAge);


}
}
//Console output:
//Name: Peter Sibanda
// Age: 35

CONSTRUCTING STRINGS: THE STRINGBUILDER CLASS

As explained above, strings in C# are immutable. This means that any adjustments applied
to an existing string do not change it but return a new string. For example, using methods
like Replace (…), ToUpper(…), Trim(…) do not change the string, which they are called
for. They allocate a new area in the memory where the new content is saved. This
behavior has many advantages but in some cases can cause performance problems

Strings Concatenation in a Loop: Never Do This!


Serious performance problems may be encountered when trying to concatenate strings in
a loop. The problem is directly related to the strings handling and dynamic memory, which
is used to store them. To understand why we have poor performance when
concatenating strings in a loop, we must first consider what happens when using
operator "+" for strings.

How Does the String Concatenation Works?


We already got familiar with the ways to do string concatenation in C#. Let’s now examine
what happens in memory when concatenating strings. Consider two variables str1 and
str2 of type string, which have values of "Super" and "Star". There are two areas in the
heap (dynamic memory) in which the values are stored. The task of str1 and str2 is to keep
a reference to the memory addresses where our data is stored. Let’s create a variable
result and give it a value of the other two strings by concatenation. A code fragment for
creating and defining the three variables would look like this:

string str1 = “Super”;


string str2 = “Star”;
string Result = str1 + str2;

What will happen with the memory? Creating the variable result will allocate a new area in
dynamic memory, which will record the outcome of the str1 + str2, which is "SuperStar".
Then the variable itself will keep the address of the allocated area. As a result we will have
three areas in memory and three references to them. This is convenient, but allocating a
new area, recording a value, creating a new variable and referencing it in the memory is a
time-consuming process that would be a problem when repeated many times, typically
inside a loop.

REVERSING A STRING – EXAMPLE


Consider another example: we want to reverse an existing string (backwards). For example,
if we have the string "abcd", the returned result should be "dcba". We get the original
string, iterate it backwards character by character and add each character to a variable of
type StringBuilder:

public class WordReverser


{
static void Main ()
{
String text = “EM edit “;
String reversed = ReverseText (text);
Console.Writeline (reversed);
//Console out:
//tide ME
static string reverseText(string text)
{ stringBuilder sb = new StringBuilder();
for (int I = text.Length – 1; i>0; i--)
{ sb.Append(text[i]);
}
return sb.ToString();
}
}

In this example we have a variable text, which contains the value "EM edit". We pass the
variable to the ReverseText(…) method and set the new value in a variable named
reversed. The method, in turn, iterates the characters of the variable in reverse order and
stores them in a new variable of type StringBuilder, but now back ordered. Ultimately, the
result is "tide ME".

String Formatting
C# provides the developer with mechanisms for formatting strings, numbers and dates.

The ToString(…) Method

One of the interesting concepts C# is that practically every object of a class and primitive
variables can be presented as text. This is done by the method ToString(…), which is
present in all .NET objects. It is implicit in the definition of the object class – the base class
that all .NET data types inherit directly or indirectly. Thus the definition of the method
appears in each class and we can use it to bring the content of each object in some text
form.

The method ToString(…) is called automatically when we print objects from different
classes to the console. For example, when printing dates the submitted date is converted to
text by calling the ToString(…):

DateTime currentDate = DateTime.Now;


Console.WriteLine (CurrentDate);
//Output: 08.09.2020 13:34:27 (depends on the culture settings

When we pass currentDate as a parameter of the WriteLine(…) method, we don’t have an


accurate statement that handles dates. The method has a particular implementation for all
primitive types and strings. For all other objects WriteLine(…) calls their ToString(…)
method, which first converts them to text and then displays the resulting text content. In
fact, the sample code above is equivalent to the following:
DateTime CurrentDate = DateTime.Now
Console.WriteLine (currentDate.ToString ());
The default implementation of the ToString(…) method in the object class returns the full
name of the class. All classes that do not explicitly redefine the behavior of the
ToString(…) are using this implementation. Most classes in C# have their own
implementation of the method, which represents readable and understandable content in
text form. For example, converting a number to text is using the standard format for
numbers in the current culture. Converting a date to text is also using the standard format
for dates in the current culture.
Using String.Format(…)
String.Format (…) is a static method by which we can format text and other data
through a template (formatting string). The templates contain text and declared
parameters (placeholders) and are used to obtain formatted text after replacing the
parameters with specific values. You can make a direct association with the
console.writeLine (…) method, which also formats a string through a template:

Console.WriteLine (“This is a template from {0}; “Johnson”);


How to use the String.Format (…) method? Consider an example in order to clarify this:
DateTime Date = DateTime.Now;
String name = “Leonard Senderayi”;
String task = “Principles of Software design language”;
String location = “commerce Block Office”;
String formattedText = String.Format (“Today is {0: MM/dd/yyyy} and {1} is working on {2} in
{3}” ;
date, name, task, location);
console.writeline(formattedText);
//output: today is 08.09.2020 and Leonard Senderayi is working on
// Principles of Programming Language in the commerce block office.
As it is seen from the example, formatting with String.Format () uses placeholders
(parameters like {0}, {1}, etc.) and accepts formatting strings (such as: dd.MM.yyyy). It
accepts as first parameter a formatting string containing text with parameters, followed by
values for each parameter and returns the formatted text as a result.
Exercises
1. Describe the strings in C#. What is typical for the string type? Explain which the most
important methods of the string class are.

2. Write a program that reads a string, reverse it and prints it to the console. For example:
"introduction"  "noitcudortni".

3. How many backslashes you must specify as an argument to the method Split(…) in
order to split the text by a backslash?
Example: one\two\three.
Note: In C# backslash is an escaping character
4. Write a program that reads a string from the console (20 characters maximum) and if
shorter complements it right with "*" to 20 characters.
5. Write a program that reverses the words in a given sentence without changing
punctuation and spaces. For example: "C# is not C++ and PHP is not Delphi"  "Delphi
not is PHP and C++ not is C#".
6. Write a program that reads the date and time entered in the format "day.month.year
hour:minutes:seconds" and prints the date and time after 6 hours and 30 minutes in the
same format.
UNIT 8 – EXCEPTION HANDLING
C# Exception Handling

Exceptions

When executing C# code, different errors can occur which might include coding errors
made by the programmer, errors due to wrong input, or other unforeseeable things. When
an error occurs, C# will normally stop and generate an error message. The technical term
for this is: C# will throw an exception (throw an error).

Exception Classes in C#

C# exceptions are represented by classes. The exception classes in C# are mainly directly
or indirectly derived from the System.Exception class. Some of the exception classes
derived from the System.Exception class are
the System.ApplicationException and System.SystemException classes.

The System.ApplicationException class supports exceptions generated by application


programs. Hence the exceptions defined by the programmers should derive from this
class.

The System.SystemException class is the base class for all predefined system
exceptions.

The following table provides some of the predefined exception classes derived from the Sytem.SystemExcept

Sr.No. Exception Class & Description

1 System.IO.IOException

Handles I/O errors.

2 System.IndexOutOfRangeException

Handles errors generated when a method refers to an array index out of range.

3 System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array type.

4 System.NullReferenceException

Handles errors generated from referencing a null object.

5 System.DivideByZeroException

Handles errors generated from dividing a dividend with zero.

6 System.InvalidCastException

Handles errors generated during typecasting.

7 System.OutOfMemoryException

Handles errors generated from insufficient free memory.

8 System.StackOverflowException

Handles errors generated from stack overflow.

Try and catch

The try statement allows you to define a block of code to be tested for errors while it is
being executed. The catch statement allows you to define a block of code to be executed, if
an error occurs in the try block. The try and catch keywords come in pairs:

Syntax

try
{
// Block of code to try
}
catch (Exception e)
{
` // Block of code to handle errors
}
Consider the following example, where we create an array of three integers:

This will generate an error, because myNumbers[10] does not exist.

int[ ] myNumbers = {1, 2, 3};

Console.WriteLine(myNumbers[10]); // error!

The error message will be something like this:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' If an error


occurs, we can use try...catch to catch the error and execute some code to handle it. In
the following example, we use the variable inside the catch block (e) together with the built-
in Message property, which outputs a message that describes the exception:

Example

try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
You can also output your own error message:

Example

try
{
int[ ] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
The output will be:
Something went wrong.

Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

Example

try
{
int[ ] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
finally
{
Console.WriteLine("The 'try catch' is finished.");
}
The output will be:

Something went wrong.


The 'try catch' is finished.

The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception class. There are many exception
classes available in
C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutEx
ception, etc:

Example

static void checkAge(int age)


{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at
least 18 years old.");
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}
}
static void Main(string[ ] args)
{
checkAge(15);
}
The error message displayed in the program will be:

System.ArithmeticException: 'Access denied - You must be at least 18 years old.'

C# User-Defined Exceptions

C# allows programmers to create user-defined or custom exception. It is used to make the


meaningful exception. To do this, programmers need to inherit Exception class.

C# user-defined exception example

using System;
public class InvalidAgeException : Exception
{
public InvalidAgeException(String message)
: base(message)
{

}
}
public class TestUserDefinedException
{
static void checkAge(int age)
{
if (age < 20)
{
throw new InvalidAgeException("Sorry, Age must be greater than 20
years");
}
}
public static void Main(string[] args)
{
try
{
checkAge (12);
}
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}

Output:

InvalidAgeException: Sorry, Age must be greater than 20 years


Rest of the code

C# Checked and Unchecked

C# offers checked and unchecked keyword to handle integral type exceptions. Checked
and unchecked keywords specify checked context and unchecked context respectively. In
checked context, arithmetic overflow raises an exception whereas, in an unchecked
context, arithmetic overflow is overlooked and outcome is truncated.

C# Checked

The checked keyword is used to explicitly check overflow and conversion of integral type
values at compile time.

Let's first look at an example that does not use checked keyword.

C# Checked Example without using checked

using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}

Output:

-2147483647

Appreciate, the above program yields the incorrect outcome and does not throw any
overflow exception.

C# Checked Example using checked

This program throws an exception and stops program execution.

using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
checked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}

Output:

Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an


overflow.
C# Unchecked

The Unchecked keyword disregards the integral type arithmetic exceptions. It does not
check openly and yield result that may be truncated or wrong.

Example

using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
unchecked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}

Output:

-2147483647

Exercise

1. Discover all the exceptions in the System .IO.IOException hierarchy.


2. Find out all standard exceptions that are part of the hierarchy holding the class
System.IO.FileNotFoundException.
3. Find out all standard exceptions from the System.AplicationException hierarchy
4. Explain the concept of exceptions and exception handling, when they are used and
how to catch exceptions
5. Expound when the statement try-finally is used.
6. What benefits are realised when using exceptions?
7. Write a program that accepts a positive whole number from the console, computes
and displays its square root. If the captured number is negative or invalid the
program should print the expression “Invalid Number” in the console. Without
considering any case it should print “Farewell to you”
UNIT 9 – FILES

FILES

A file is a collection of data stored in a disk with a specific name and a directory path. When
a file is opened for reading or writing, it becomes a stream.

A stream is basically the sequence of bytes passing through the communication path.
There are two main streams: the input stream and the output stream. The input stream is
used for reading data from a file i.e. the read operation and the output stream is used for
writing into the file i.e. the write operation.

At one point we might need to create files, read files, delete files, write to files, and or
append to files. In order to be able to work with files in C#, we use
the System.IO and System.Text namespaces.

I/O Classes

The System.IO namespace has different classes that are used for carrying out
numerous tasks with files, such as creating and deleting files, reading from or writing to
a file, closing a file etc.

Presented below are some commonly used non-abstract classes in the System.IO
namespace:

I/O Class Descriptio


n

BinaryReader Reads primitive data from a binary stream.

BinaryWriter Writes primitive data in binary format.

BufferedStream A temporary storage for a stream of bytes.

Directory Helps in manipulating a directory structure.


DirectoryInfo Used for performing operations on directories.

DriveInfo Provides information for the drives.

File Helps in manipulating files.

FileInfo Used for performing operations on files.

FileStream Used to read from and write to any location in a file.


MemoryStream Used for random access to streamed data stored in memory.

Path Performs operations on path information.

StreamReader Used for reading characters from a byte stream.

StreamWriter Is used for writing characters to a stream.

StringReader Is used for reading from a string buffer.

StringWriter Is used for writing into a string buffer.

The FileStream Class

It is in the System.IO namespace and it supports in reading from, writing to and closing
files. This class derives from the abstract class Stream. One need to create a FileStream
object inorder to create a new file or open an existing one. The syntax for creating a
FileStream object is as illustrated below:
FileStream <object_name> = new FileStream( <filename>,
<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);
As an example, we can create a FileStream object f for reading a file named
TextFiles.txt as shown:
FileStream f = new FileStream("TextFiles.txt", FileMode.Open,
FileAccess.Read, FileShare.Read);
Parameter Descriptio
n
FileMode The FileMode enumerator defines various methods for opening
files. The members of the FileMode enumerator are:
● Append: It opens an existing file and puts cursor at the end of
file, or creates the file, if the file does not exist.

● Create: It creates a new file.

● CreateNew: It specifies to the operating system, that it should


create a new file.

● Open: It opens an existing file.


● OpenOrCreate: It specifies to the operating system that it
should open a file if it exists, otherwise it should create a new
file.

● Truncate: It opens an existing file and truncates its size to


zero bytes.

FileAccess FileAccess enumerators have members: Read, ReadWrite and


Write.

FileShare FileShare enumerators have the following members:


● Inheritable: It allows a file handle to pass inheritance to the
child processes

● None: It declines sharing of the current file

● Read: It allows opening the file for reading

● ReadWrite: It allows opening the file for reading and writing

● Write: It allows opening the file for writing

Example
The following program exhibits use of the FileStream class:
using System;
using System.IO;
namespace FileIOApplication
{
class Program
{
static void Main(string[] args)
{
FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate,
FileAccess.ReadWrite);
for (int i = 11; i <= 30; i++)
{
F.WriteByte((byte)i);
}
F.Position = 0;
for (int i = 0; i <= 20; i++)
{
Console.Write(F.ReadByte() + " ");
}
F.Close(); Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 -1

READING AND WRITING TO TEXT FILES

In order to read from and to write data to text files, StreamReader and StreamWriter
classes are used. These two (2) classes inherit from the abstract base class Stream, which
supports reading and writing bytes into a file stream.

The StreamReader Class

The StreamReader class as pointed out in the section above, also inherits from the
abstract base class TextReader that represents a reader for reading chain of characters.
The following table describes some of the commonly used methods of the
StreamReader class:

No. Method
s

1 public override void Close()

It closes the StreamReader object and the underlying stream, and


releases any system resources associated with the reader.

2 public override int Peek()

Returns the next available character but does not consume it.

3 public override int Read()

Reads the next character from the input stream and advances the
character position by one.

Example
The following example shows reading a text file named Exceptions.txt. The file reads:

Exception Handling in C# is a process to handle runtime errors.

In C#, exception is an event or object which is thrown at runtime.

All exceptions the derived from System.Exception class.

It is a runtime error which can be handled.

using System;
using System.IO;
namespace TextFileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
/*Create an instance of StreamReader to read from a file.
The using statement also closes the StreamReader.*/
using (StreamReader sr = new StreamReader("c:/Exceptions.txt"))
{
string line;
/* Read and display lines from the file until
the end of the file is reached. */
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}

catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
The StreamWriter Class

The StreamWriter class inherits from the abstract class TextWriter that represents a
writer, which can write a series of character. The table below defines the most frequently
used methods of this class:

N Methods
o.

1 public override void Close()

Closes the current StreamWriter object and the underlying stream.

2 public override void Flush()

Clears all buffers for the current writer and causes any buffered data to be
written to the underlying stream.

3 public virtual void Write(bool value)

Writes the text representation of a Boolean value to the text string or


stream. (Inherited from TextWriter.)

4 public override void Write( char value )

Writes a character to the stream.

5 public virtual void Write( decimal value )

Writes the text representation of a decimal value to the text string or stream.

6 public virtual void Write( double value )

Writes the text representation of an 8-byte floating-point value to the text


string or stream.

7 public virtual void Write( int value )

Writes the text representation of a 4-byte signed integer to the text string or
stream.

8 public override void Write( string value )

Writes a string to the stream.

9 public virtual void WriteLine()

Writes a line terminator to the text string or stream.


Example
The following example reveals writing text data into a file using the
StreamWriter class:
using System;
using System.IO;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[] {"Moyo Tinashe", "Muhamed Ali"};
using (StreamWriter sw = new StreamWriter("nameList.txt"))
{

foreach (string s in names)


{
sw.WriteLine(s);
}
}
// Read and show each line from the file. string line = "";
using (StreamReader sr = new StreamReader("nameList.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}
Input / Output Exception Handling

Many of the operations that relate to files, have the potential of causing exceptional
situations.

Intercepting Exceptions when Working with Files

Possibly the most common exception when working with files is the
FileNotFoundException (its name supposes that the desired file was not found). It can
occur when creating a StreamReader. When setting a specified encoding by the creation
of a StreamReader or a StreamWriter object, an ArgumentException can be thrown.
This means that the encoding we have chosen is not supported. Another common
mistake is IOException. This is the base class for all IO errors when working with streams.

The standard approach for handling exceptions when working with files is the following:
- Declare variables of class StreamReader or StreamWriter in try- catch block.
- Initialize them with the necessary values in the block and handle the potential exceptions
properly.
- To close the stream, we use the structure using.

Catching an Exception when Opening a File – Example

Here’s how we can catch exceptions that occur when working with files:

class HandlingExceptions
{
static void Main()
{
string fileName = @"Myedir\Myfile.txt";
try
{
StreamReader reader = new StreamReader(fileName);
Console.WriteLine(
"File {0} successfully opened.", fileName);
Console.WriteLine("File contents:");
using (reader)
{
Console.WriteLine(reader.ReadToEnd());
}
}
catch (FileNotFoundException)
{
Console.Error.WriteLine(
"Can not find file {0}.", fileName);
}
catch (DirectoryNotFoundException)
{
Console.Error.WriteLine(
"Invalid directory in the file path.");
}
catch (IOException)
{
Console.Error.WriteLine(
"Can not open the file {0}", fileName);
}
}
}
The example above demonstrates reading a file and printing its contents to the console. If
the name was accidentally confused or have been deleted, an exception of type
FileNotFoundException was going to be thrown. In the catch block this sort of exception
was intercepted and if such an error occurs, it will be processed properly and a message
will be printed to the console, narrating that this file cannot be found. The same will
happen if there were no directory named "MyDir". Finally, for better security, also added
was a catch block for IOExceptions. All other IO exceptions, that might occur when
working with files, will be intercepted.

Exercise

1. Write a program that reads text from a text file and only prints odd numbered lines
on the console.
2. Write a program that reads the contents of a text file and inserts the line numbers at
the beginning of each line, then rewrites the file contents.
UNIT 10

Functional programming
It is based on the notion that a program implements a function. Computation is earned out entirely
through the evaluation of expressions. Examples of functional languages are ML and Miranda.
Logic Programming
Programs are written in the language of some logic. Execution of a logic program is a theorem
proving. The execution of a logic program is a theorem proving process and this implies that
computation is done by logic process and logic inferences. Prolog (PROgramming PROgramming in
LOGic) is a representative logic language.
It’s History
It was formulated in 1974 by a professor at University of Edinburgh. The First system written in logic
was implemented in 1995 by a research group in France and also the first compiler was built in
1997 by a PhD student also in Edinburgh. Its efficiency has improved in recent years and interfaces
with other languages such as C/Java.
Why Prolog is not as popular as C/Java
Prolog was incorrectly at first as some universal computer language.
Not yet as proficient as C and Java.
Support to Prolog takes effort, resources and companies are not willing to pay for it.
Its value not recognized by industry

What is a logic
Logic is a language that has syntax and semantics and more than a language, it has inference rules.
Syntax is the rules about how to form formulas and this is usually the easy part of a logic. Semantics
is about the meaning carried by the formulas, mainly in terms of logical consequences. Inference
rules describe correct ways to derive conclusions.
Use logic to do reasoning
Example:
Given information about fatherhood and motherhood, determine grandparent relationship.
E.g. Given the information called facts
John is father of Felly
Kathy is mother of Felly
Felly is mother of Bob
Ken is father of Karen
Who are grandparents of Bob?
Who are grandparents of Karen?

Example of Prolog program


In Prolog, we write the following for the given facts:
father(john, Felly).
mother(kathy, Felly).
mother(Felly,Bob).
father(ken, karen).
In logic, words like father, mother are called predicates. A statement like father(john, Felly) is
called an atomic formula, stating a true fact.
Programs as logic formulas
Express the grandparent relationship:
grandparent(X,Z) :- parent(X,Y), parent(Y,Z).
parent(X,Y) :- father(X,Y).
parent(X,Y) :- mother(X,Y).
These are called conditional statements. Capital letters denote variables, meaning “for any”.
E.g., the first formula above reads:
For any X,Y,Z,
if X is a parent of Y, and Y is a parent of Z,
then X is a grandparent of Z.

A complete program
Depositing all together, we have the following Prolog program:
grandparent(X,Z) :- parent(X,Y), parent(Y,Z).
parent(X,Y) :- father(X,Y).
parent(X,Y) :- mother(X,Y).

father(john, Felly).
mother(kathy, Felly).
mother(Felly,Bob).
father(ken, karen).
Another Example
Given a list of integers, get the sum.
We will define a predicate
sum(L,R)
Where L is a given list, and R will be used to hold the result.
Prolog program for sum
The program consists of two clauses
sum([ ],0).
sum([A|L], R) :-R is A+R1, sum(L,R1).

R is A+R1 is Prolog’s way of saying “R is the result of A+R1 and the [A|L] is a notation for a list
whose first element is A and the rest of the list is L.

The two clauses read:


the first: : the sum of an empty list is 0.
the second: the sum of the list [A|L] is the result of adding A with the sum of L.

Procedure Oriented Programming (POP):

POP comprises of set of instructions to be followed which in turn are divided into smaller portions
known as functions in order for the computer to perform. C, VB, FORTRAN, Pascal are few examples
of POP.

Features of POP:

Mainly focused on writing the algorithms.


Most function uses Global data for sharing which are accessed freely from function to
function in the system.
They follow top down approach in program design.
Does not have data hiding options.
Functions transform data from one form to another.
Data can be moved openly from one function to another around the system.
Sub-division of large program into smaller programs called functions.
Overloading process is not applicable in POP.
Procedure Oriented Programming Features in C:

C language uses the set of instruction to inform/guide computer what to do step by


step.
It depends on the procedures, more specifically routines or subroutines.
As it follows the procedures, hence it adopts the top-down approach.
Apart from other languages like C++, C language is very much focused on the
procedure that relates to the data.
C language is much focused on the data hence on functions.
It is also well known as the structured programming language.

Imperative programming

Imperative programming (from Latin imperare = command) is the oldest programming paradigm. In
this paradigm, a program is made up of a clearly-defined sequence of instructions to a computer.

The source code for imperative languages is therefore, a series of commands, which lay down what
the computer has to do – and when – in order to accomplish a desired result. Values used in
variables are changed at program runtime. To control the commands, control structures such as
loops or branches are integrated into the code.

Imperative programming languages are very specific, and operation is system-oriented. On the one
hand, the code is easy to understand; on the other hand, many lines of source text are required to
describe what can be achieved with a fraction of the commands using declarative programming
languages. Best known imperative languages are Fortran, Java, Pascal, ALGOL, C, C#, C++,
Assembler, BASIC, COBOL, Python and Ruby among others.

The different imperative programming languages can, in turn, be assigned to three further
subordinate programming styles – structured, procedural, and modular.

The structured programming style extends the basic imperative principle with specific control
structures: sequences, selection, and iteration. This approach is based on a desire to limit or
completely avoid jump statements that make imperatively designed code unnecessarily
complicated.

The procedural approach divides the task a program is supposed to perform into smaller sub-tasks,
which are individually described in the code. This results in programming modules which can also
be used in other programs. The modular programming model goes one step further by designing,
developing, and testing the individual program components independently of one another. The
individual modules are then combined to create the actual software.

Multi-paradigm programming language

A multi-paradigm programming language is a programming language that supports more than one
programming paradigm. The idea of a multiparadigm language is to provide a framework in which
programmers can work in a variety of styles, freely intermixing constructs from different paradigms.
The design goal of such languages is to allow programmers to use the best tool for a job, admitting
that no one paradigm solves all problems in the easiest or most efficient way.
All these languages follow the procedural paradigm. That is, they describe, step by step, exactly the
procedure that should, according to the particular programmer at least, be followed to solve a
specific problem. The efficacy and efficiency of any such solution are both therefore entirely
subjective and highly dependent on that programmer’s experience, inventiveness and ability.

Comparisons of expressiveness
The expressive power also called expressiveness or expressivity of a programming language is the
breadth of ideas that can be represented and communicated in that language. The more expressive
a language is, the greater the variety and quantity of ideas it can be used to represent.
It is possible to compare programming languages by their efficiency, or expressiveness. One
proxy for this is how many lines of code change in each commit. This would provide a view into
how expressive each language enables you to be in the same amount of space. Because the
number of bugs in code is proportional to the number of source lines, not the number of ideas
expressed, a more expressive language is always worth considering for that reason alone.
REFERENCES

Nakov, S., and Company, (2013). Fundamentals of Computer Programming with CSharp,
Chapter 6 pp 223- 230, Chapter

You might also like