Archive

Posts Tagged ‘C#’

Programming Tutorial – Lesson 1: Instructions

July 15th, 2008

Programming or coding as some call it, is the backbone of the software industry. It comprises of writing Programs – lines of instructions. These instructions are fed to the computer for processing and output. Sounds simple, doesn’t it? Well, trust me, its no Rocket science. But, I have seen students think of it as such and ultimately scraping the entire idea of learning how to program.

Many courses being taught at the higher levels of education, today, don’t start off at the absolute beginning of Programming. For a person who has no prior experience in programming, knowing the basics is very essential. In these series of tutorials, I will take you on the journey that I did, back at school and learned whatever little of Programming, that I know today. We will begin by using LOGO, the programming language. I believe it will impart good insights into the bare-bones of Programming.

We need to know a few terms before we begin using LOGO. Don’t worry these are no jargons, only the bare minimals.

Instruction

An instruction is a command to the computer which causes a certain action to be performed.

Program

Lines of instruction that are executed or processed by the computer one by one.

We will need the MSWLogo software to go any further. You can get it from here. Once installed, start Microsoft Windows Logo from the start menu. The application is composed of a pair of Windows. The upper one with a white background and a Triangle in the middle is your drawing area.

The lower one titled Commander is where you will write the instructions and feed it to the computer.

LOGO is a programming language that works on turtle graphics. A triangle shaped object (the Turtle) is used to draw lines & curves on the screen. To draw these lines you instruct the turtle to move forward or backward and while doing so, it leaves a line behind. Try typing the instruction given below in the textbox to the right of the Execute button in the Commander window and then press enter or click on Execute.

As you can see, the turtle moved upward, or forward in its own orientation, leaving behind the black line. The instruction we provided is composed of two parts: FORWARD – the command to make the turtle go forward and 50 the distance it moved forward by. Now type in the following command and press enter.

The turtle comes back 100 units drawing over the old line and extending it by 50 at the bottom. Unlike in real life, an overwrite on the same line doesn’t make the line thicker. Let us try some more tricks, type in the following instruction and press enter.

This makes the turtle turn right (clockwise) by 90 degrees allowing us to draw a horizontal line. The RIGHT command is followed by an angle in degrees. The turtle can turn in any direction with this. But, we have a command to make it turn the other way too – the LEFT command. Now execute the following command.

FD command is an alias (another name) for the FORWARD command and it provides the exact same functionality. The Aliases for the commands are given in the table below.

Command Alias
FORWARD FD
BACK BK
RIGHT RT
LEFT LT

Lets complete our diagram by executing these instructions one by one.

There we have it; Mr. Paniter has drawn us our very own Square. The third instruction, RT 270 can be replaced by an equivalent LT 90. You can provide a negative value to the FD and BK commands to make them go the opposite way. You can even give negative angles or angles greater than 360 degrees and make the poor turtle go round and round (apparently, the slow dude turns so fast, we won’t be able to see it spin its head off, or maybe it has some sharp geomerty skills and does only one round).

Drawing dashed lines or discontinous figures

Did I mention how the turtle goes about drawing all those lines? The guy uses a pen! Not your average pen that runs out of ink every second day, though. Just as we raise our pen in between writing two words, you can make the turtle raise its pen and move to some place else. During this movement, it won’t draw a line. We use the PENUP command to raise the pen up. While in this state, moving in no direction will result in a line being drawn. To lower the pen use the PENDOWN command. When the pen has been lowered, lines will again begin to be drawn following an FD OR BK command (unless offcourse if you move it by 0 units).

Note: PENUP & PENDOWN commands are not followed by any numbers. You can also use their aliases PU & PD.

Clear the screen using the CS command and execute the following instruction to draw a dashed line.

Chaining Instuctions in one line

You can write multiple instuctions in one line. For example, the dashed line can be drawn using the following command.

The REPEAT command

The REPEAT command is used to repeat a series of instructions a given number of times. For example, you can use the following code to draw a square.

The dashed line can be drawn with the REPEAT command.

The REPEAT command is followed by a number specifying how many times to repeat the steps and the set of instructions to be repeated. The instructions to be repeated are enclosed between the square brackets [ and ].

Syntax

Syntax is the grammar of instructions. Every command has a syntax. For example, the FD command is followed by a number, whereas the syntax of PU & PD commands don’t contain any numbers following them. We can express these syntax in general forms:-

Command Syntax
FD FD distance
RT RT angle
REPEAT REPEAT count [ instructions ]

Syntax helps us understand the structure of the command, how its written/used. Every Programming language has its own set of commands, statements & their corresponding syntaxes.

Note: Description of statements is not relevant to the LOGO language. We will go through it in a later tutorial.

In this tutorial we have seen what instructions are and how to write them for the LOGO language. The LOGO language offers more than what we have covered here. But, our aim was only to get familiar with instructions. In the next tutorial we will be continuing our journey into the world of Programming.

partho Tutorials , ,

C# Tutorial : Lesson 02 – Variables & Operators

April 9th, 2007
Variables

A Variable is a named location that stores a value. Although variables are physically stored in the RAM, their actual memory address is not known to the programmer. We can use the variables via the name we give them. These are the rules for naming a variable:-

  • The name must begin with a letter or an underscore & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
  • Special Characters such as ? – * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the variable name.
  • A variable name must not be the same as a reserved keyword such as using, public, etc.
  • The name can contain any number of the allowed characters
  • Variables with the same scope cannot have the same name

Note: C# being a case-sensitive language, two variables such as var1 and Var1 would be different.

Any Variable has a type associated with it, which basically restricts the type of value it can store. The table below shows the Data types available in C#, the size they occupy in the memory and the values they can contain.

Type Size Range of values
char 2 0 and 65536
int 4 -2,147,483,648 and 2,147,483,647
float 4 -3.402823E+38 and -1.401298E-45 (For Negative Values)
1.401298E-45 and 3.402823E+38 (For Positive values Values)
double 8 -1.79769313486232E308 and 4.94065645841247E-324 (For Negative Values)
4.94065645841247E-324 and 1.79769313486232E308 (For Positive values Values)
bool 1 true or false
string Depends on length of the string 0-2 million Unicode Characters


Variable Declaration

Before we can use a variable, we need to declare it. Declaration of variables are done using the syntax:-
<Data Type> <Variable Name>;

For Example:-

1
2
3
4
int Age;
char Sex;
string Name;
bool IsMarried;

Variables of the same data type can also be declared using the syntax:-
<Data Type> <Variable 1>, <Variable 2>, .. and so on;

Example:-

1
int Age, RollNum;
Initialization

While declaring a variable, it is possible to assign an initial value to it. This operation is called Initialization and it has the following syntax:-
<Data Type> <Variable Name> = <Value>;

Example:-

1
2
3
4
int Age = 20;
char Sex = 'M';
string Name = 'Max Steel';
bool IsMarried = false;

Multiple variables of the same data type can also be initialized in a single line of code using the syntax:-
<data type> <variable 1> = <value>, <variable 2> = <value>;

1
int Age = 20, RollNum = 69;
Value Types

Values can be stored in variables by two methods which are: by value and by reference. Value types store the supplied value directly in the memory whereas reference types store a reference to the memory where the actual value is located. The benefit of the reference type is that changes made to any alias of the variable will reflect across all of its aliases.

Accepting Values in Variables

To input values from the user at runtime, we use the Console.ReadLine() function. For Example:- string FirstName = Console.ReadLine(); The above statement would declare a string variable FirstName and store the value retrieved from the user in it.

Note: Console.ReadLine() returns value as a string. Therefore, one must use type casting to convert the value to the required type. We use the member functions of the Convert class to do this. For Example: int Age = Convert.ToInt32(Console.ReadLine());. Similarly, there are other functions such as ToChar(), ToString, etc for conversion to other data types.

Operators

Similar to mathematics, every programming language has its own set of operators, be it arithmetic or logical. Operators enable us to perform operations on 1 or more values (operands) and calculate the result.

Usage

Depending on the number of operands they take, operators can be either unary or binary.
The use of an operator takes one of the following form:-

Unary Usage

  • <Operator> <Operand>
    Example: ++A;
  • <Operand> <Operator>
    Example: A++;

Binary Usage

  • <Operand 1> <Operator> <Operand 2>
    Example: A + B;
Classification

The operators in C# can be classified as follows:-

Arithmetic operators – Just what the name suggests, these operators are used to perform arithmetic operations.

Operator Usage Utility Type
+ A + B Add two numbers Binary
- A – B Subtract a number from another Binary
* A * B Multiply two numbers Binary
/ A / B Divide a number with another Binary
% A % B Remainder of the operation A / B Binary

Arithmetic Assignment Operators – These can be considered as shortcuts as they are used to perform both arithmetic and assignment operations in a single step.

Operator Usage Utility Type
= A = 69 Store the value 69 into A Binary
+= A += B Equivalent to A = A + B Binary
-= A -= B Equivalent to A = A – B Binary
*= A *= B Equivalent to A = A * B Binary
/= A /= B Equivalent to A = A / B Binary
%= A %= B Equivalent to A = A % B Binary

Increment / Decrement Operators – These operators are used to increment or decrement the value of an operand by 1.

Operator Usage Utility Type
++ ++A or A++

Increments the value of A by 1

Unary
--
--A or A--
Decrements the value of A by 1 Unary

Difference between Pre & Post Increment/Decrement
Consider the following code snippet:-

1
2
3
int A = 0;
int B = A++;
int C = ++A;

At the very first line, we have used the Arithmetic Assignment operator, = to assign the value of 0 to A. In the proceeding lines we have used both Pre & Post increment. At line 2 int B = A++; the operation being post increment, the value of A i.e 0 is assigned to B followed by the increment of A’s value. At line 3 int C = ++A; the current value of A, i.e. 1 is incremented by 1 following which the new value of A is assigned to C. Therefore, the value of A = 2, B = 0 and C = 2.

What will be the output of the following code?

1
2
3
int A = 5;
int B = (A++) + (--A);
Console.WriteLine("Value of B = {0}", B);

At line, 1, A gets initialized to 5. The next line is a bit tricky. Here, The RHS should be evaluated like 5 + 4 because A++ is post increment and this operation should occur after the line of statement. But, this is not the case, instead it takes place in the same line but after the evaluation of the sub-expression (A++). Hence, the expression will be evaluated as 5 + 5 and the output will be 10.

Comparison Operators – These operators are to compare two values and return the result as either ‘true’ or ‘false’.

Operator Usage Utility Type
< A < B

Compares if A is less than B

Binary
> A > B Compares if B is less than A Binary
<= A <= B Compares if A is less than or equal to B Binary
>= A >= B Compares if A is greater than or equal to B Binary
== A == B Compares if A is equal to B Binary
!= A != B Compares if A is not equal to B Binary

Logical Operators – These operators are used to perform logical operations and return the result as either ‘true’ or ‘false’.

Operator Usage Utility Type
&& A && B

Returns true if Both A and B are true

Binary
|| A || B Return true if either A or B are true Binary
! !A Returns True if A is false Unary
^ A ^ B Returns true when A and B do not match i.e one is true and the other is false Binary


Displaying Variables

We us the WriteLine method to display the value stored in variables.

Displaying Single Variable

1
2
int A = 6;
Console.WriteLine(A);

Displaying Multiple Variables

1
2
int A = 6, B = 9;
Console.WriteLine("{0},{1}", A, B);

Notice the code “{0},{1}”. This is the format for the output to be generated by WriteLine. Since, we are displaying two variables, we need to specify the format accordingly. Here {0} and {1} represent where the proceeding variables A & B will be displayed. Now take a look at the following code snippet:-

1
2
int A = 6, B = 9;
Console.WriteLine("The value of A = {0} and B = {1}", A, B);

The output of these lines would be: The value of A = 6 and B = 9. As you can see, the {0} and {1} are replaced by the variables A and B. 0 and 1 correspond to the index of the variables following the format, starting from 0.

Comments

Software applications are made by a group of coders. Each one of them handles various aspects of the application. Its important to write descriptive texts in order to help other coders understand, the mechanism of the codes you have written. We use comments denoted by // or /* and */ for this very purpose. Example usage:-

1
2
3
// This is a comment
/* These are two lines
of comments */

Note: The compiler ignores all comment entries. // is used for single line of comment while /* and */ are used for multiple lines.

What’s in a Semicolon?

Whitespace except when used inside quotes, is ignored in C#. All statements in C# are terminated by using the semicolon. This allow spanning of codes across multiple lines.

The following lines of code are functionally equivalent.

1
int A = 6, B = 9; Console.WriteLine("A   B = {0}", A   B); Console.ReadLine();
1
2
3
int A = 6, B = 9;
Console.WriteLine("The sum of {0} and {1} = {2}", A, B, A   B);
Console.ReadLine();

partho C# , ,