Study Guide
Study Guide
FACULTY OF COMMERCE
Department of Information Systems
Module content
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
Files
● Streams, Reading from A Text File, Writing to A Text File, Io Exception
Handling, Text File Examples.
●
Demonstrating different Programming Paradigms Using Code
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
• Lectures (4 weeks @ 3h) with class discussions to introduce the theoretical background
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
Definition of Terms
First, we will define the main terms in programming.
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.
One eventually needs to convert a program into machine language so that the computer
can understand it. There are two ways to do this:
-Programming Methodologies
New software development methodologies (e.g., object oriented software development) led
to new programming paradigms and by extension, new programming languages.
• 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
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.
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.
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.
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
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.
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.
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.
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.
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
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.
Programming concepts
-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#
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.
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
class SampleClass
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.
- It is object oriented.
- It is component oriented.
- It is a structured language.
- Boolean Conditions
-Standard Library
-Assembly Versioning
-Simple Multithreading
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:
-Windows Forms
-ASP.Net and ASP.Net AJAX
-ADO.Net
-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.
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
▪ Input
▪ Output
▪ Strings
▪ Numeral types
Console.Write(…)
int a = 15;
Console.Write(a); // 15
double a = 15.5;
int b = 14;
// 15.5 + 14 = 29.5
▪ The next print operation will start from the same line
Console.WriteLine(str);
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
formatString -Specifies the format of the corresponding argument's result string, e.g. "X",
"C", "0.00", e.g.
{
double pi = 1.234;
Console.WriteLine("{0:0.000000}", pi);
// 1.234000
int a = 2, b = 3;
// 2 + 3 = 5
// 2 * 3 = 6
float pi = 3.14159206f;
Console.WriteLine("Bye – Bye!");
Console.WriteLine("Menu:");
Console.WriteLine("1. {0} – {1}", cola, colaPrice);
We use the Console to read information from the command line.Usually the data is entered
from the keyboard. We can read:
Characters
Strings
To read from the console we use the methods Console.Read() and Console.ReadLine()
Console.Read()
int i = Console.Read();
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
Console.WriteLine();
Reading Strings
Numeral types cannot be read directly from the console. To read a numeral type do the
following:
int.Parse(string)
Numeral types have a method Parse (…) for extracting the numeral value from a string
string s = "123";
int i = int.Parse(s); // i = 123
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
float f = float.Parse(Console.ReadLine());
}
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
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
Types of Operators in C#
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:
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.
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
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.
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;
object o = i;
The object o can then be unboxed and assigned to integer variable i:
o = 123;
i = (int)o; // unboxing
Jagged Arrays-A Jagged array is an array of arrays. You can declare a jagged array named
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.
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:
● 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.
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;
}
If we start the example and enter the numbers 4 and 5 we will get the following result:
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!
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.
Let’s take a look at the next example and illustrate how the if-else statement works:
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:
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:
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");
}
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.
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.
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
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.
Number :50
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.
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
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.
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.
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.
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.
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
Method Declaration
To declare a method means to register the method in our program. This is shown with the
following declaration:
- 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:
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:
- 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.
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:
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 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.
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:
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:
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
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).
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
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:
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.
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).
In this example we created the variable website with value the above stated string literal.
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(…):
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:
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:
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
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
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.
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.
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(…):
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.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
1 System.IO.IOException
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
5 System.DivideByZeroException
6 System.InvalidCastException
7 System.OutOfMemoryException
8 System.StackOverflowException
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:
Console.WriteLine(myNumbers[10]); // error!
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:
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
C# User-Defined Exceptions
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:
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.
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.
using System;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
checked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Output:
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
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:
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.
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
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 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
Returns the next available character but does not consume it.
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:
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.
Clears all buffers for the current writer and causes any buffered data to be
written to the underlying stream.
Writes the text representation of a decimal value to the text string or stream.
Writes the text representation of a 4-byte signed integer to the text string or
stream.
Many of the operations that relate to files, have the potential of causing exceptional
situations.
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.
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?
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.
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:
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.
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