Sie sind auf Seite 1von 17

C#

C# for C programmers
C# is an Object Oriented Programming (OOP) Language as opposed to C that is a structured language. However, in this module we will discuss a little on OOPs concepts and more on basic C# features e.g. if-else statement, for, while, do-while loops, switch statements, arrays etc. This module enables the student to satisfy the prerequisites to learn the advanced features in C#.

Structure of C# Program
A collection of classes grouped together is called a Namespace. However, this is only a working definition of a namespace. Consider the program in this slide Console . WriteLine(Hello World!!); In this statement Console is a class and WriteLine() is a method of the class. One can observe that WriteLine() method is analogous to printf() function of C language. Similarly, in the statement L=Console.ReadLine(); ReadLine() is a method (corresponding to scanf() function of C language) of the Console class. Besides these methods Console class has other methods e.g. Read(), ReadKey(), SetCursorPosition() etc. A namespace is a collection of classes, here System is a namespace and Console is a member class. Observe that a namespace is included in a program with help of using directive. The first line in the program is Using System;

C#

If this line is removed then the program will not compile. It is interesting that using directive is similar to include directive of C language. Other classes belonging to System Namespace are Array, Math etc. Finally, observe that this Hello World program does not create objects; because the main() method defined in it is declared as static. To avoid creating objects we will declare all methods as static during this module.

visual studio 2008


The slide shows a snapshot of the Visual Studio 2008 IDE (Integrated Development Environment) which has far more advanced capabilities than Turbo C used for C programming. Visual Studio is a complete suite of tools, which includes an editor with intellisense support, a compiler, debugging features, testing, etc. Visual Studio is available in several editions; a comparative listing of the different editions is available at: http://www.microsoft.com/visualstudio/en-us/products/2010-editions/product-comparison

C#

data types in c#
C# is a strongly typed language and has a rich collection of data types. Observe the differences with C language (a) Decimal which occupies 16 bytes and (b) float that occupies 4 bytes memory

C#

data types in c# cont


Other data types available in C# are (a) Integer that occupies 4 bytes (b) string and (c) Boolean (written as Bool)

example swap values of 2 variables


Here we see an example program to swap two numbers - observe the variable declarations in the example program. The integer variables a and b are declared in line number 8. Line 9 and 10 are commented out but demonstrate declaration of double and float type variables. Placeholders {0} and [1} are used in line 11, these indicate the sequence in which the value of variables are to be printed. Also observe that the placeholders are within quotes and separator is comma operator. Compare this with printf() statement in C language. Further we see that in line 10 floating point number is appended with the letter f.

C#

Double data type


In C# language the double data type occupies 8 bytes and precision is of 15 digits. The example program given here to calculate the square root of a number illustrates two things (i) In line 8 the Console.ReadLine() method returns a string value that needs to be converted to double type using the Convert.ToDouble() method, the method belongs to the Convert class that in turn belongs to the System namespace. (ii) In line 9 we use the Math.Sqrt() method that returns the square root of a given number

C#

Exercises
Here we give some practice exercises for the students.

Overview of predefined data types in c#


C# provides 16 pre-defined data types. They include 13 simple types and 3 complex types. The predefined simple types are: Eleven numeric types, including the following:

C#

1. 2.

Various Lengths of signed and unsigned integer types Floating point types float and double

3. A high precision decimal type called decimal. A Unicode character type called char A Boolean type called bool; which can be either true or false. The predefined complex types are: String, which is an array of Unicode characters Object, which is the type on which all other types are based Dynamic, which is used when using assemblies written in dynamic languages.

Control statements
so now lets see the control statements in c#. C# has all the control structures available in C language. Most common are if, ifelse and switch statements.

C#

Example if statement
So now lets understand this example The example program given here accepts any number and displays its absolute value, the if statement checks if the number is less than zero and multiplies it with minus one in such case (for numbers greater than or equal to zero we do not multiply). Then we print the number.

if else example currency conversion


So now lets look into ifelse example This program converts dollars to rupees or vice versa depending on the choice of user. The assumption is that one dollar equals to 48 rupees (the variable drate stores the dollar conversion
8

C#

rate). The user enters 1 to convert rupee to dollar and 2 for conversion from dollar to rupee. Observe that if block converts rupee to dollar and else block converts dollar to rupee.

Switch statement-example
So now lets look into this example now This slide has two programs, in the first program we demonstrate use of case statement that closely resembles to C language counterpart. There is a switch argument followed by case clause. The case clause ends with a break statement. If a break statement is missing then compiler signals an error. A default clause can be included at the end. In the second program (switch 2 program ) we can see that break statement can be avoided if the case clause is empty. Also we note that in C# the switch variable can be a string, this is not allowed in C language.

C#

for loop
For statement is similar in C and C# languages. It contains an index variable, initial condition, final condition and increment condition. The loop is executed as long as condition is true else the loop exits.

Example-series summation
We see two programs here

10

C#

(i) Series summation (1+ 2 + 3 + 4 + .. + 99 + 100) using for loop. Observe that the index variable i is declared within for block. Initially integer variable sum is zero and finally it holds the summation of the series from 1 to 100. The series can easily be modified to compute the sum of the square of the numbers from 1 to 100. Please take this as an exercise.

(ii) The same program is rewritten using while loop. Rewrite this program to do the summation of numbers from 150 down to 100 i.e. calculate 150 + 149 + 148 + ..+ 100.

while loop
Coming to the While loop we see that it is used when we do not know how many times the loop needs to execute, we only know the condition when the loop should terminate. In the previous example the terminating condition was i equal to or greater than hundred. Just like for loop the while loop executes as long as condition is true. As soon as condition is false the loop terminates.

11

C#

Do-While Loop
Another construct in C# is the Do While loop. Do while loop executes only when the given condition is true. As soon as condition is false the loop exits. This is just like the while looping however, the difference is in while loop the condition is checked before the loop begins to execute. The do while loop enters the loop without any check and the condition is checked in the end of the block before the second iteration. A while loop will not execute at all if the condition is false in the beginning. But in do while loop condition is checked in the end hence it will execute at least once even when the condition is false in the beginning.

Example for do while loop


The program in this slide calculates the sum of the squares of the numbers from 1 to 100. Rewrite the program using for loop.

12

C#

Exercises
Here we give a few practice exercises to the students.

Arrays exercises
Just like C language C# supports the array data structure. However the syntax differs from that used in C language. Arrays are declared using the new keyword. Arrays may be initialized and declared together. Further an array may be declared and initialized without using the new keyword as show in the examples.

13

C#

Program to store and print numbers in an array


The first program in the slide demonstrates the array syntax. The array is assigned values and then the values are printed. In the second program the array is initialized without using the new keyword. Also observer l=num.Length is used to find the length of the array. Here length is not a method of the num class but a special type of variable called a property.

14

C#

Program to sort an array


Here we give an example program to sort an array using the predefined sort() method. This method belongs to the Array class. The array class belongs to the System namespace.

Foreach loop in c#
The foreach loop is a special type of loop not available in C language. It works on arrays (also on arraylist, a data structure similar to arrays) by iterating through each element of the array and on completion the loop terminates. The foreach variable takes values of each element of the array one by one. The foreach variable may be printed but should not be modified otherwise compiler will give an error.

15

C#

Program using foreach loop


These example programs show the use of foreach loop. In the first program the loop is used to display all the elements of the array. In the second one the foreach loop is used to find the largest element of the array.

Loop examples
The example program finds out the largest number in an array using a for loop. In the second program the largest number in an array num is computed using the num.Max() method. The loop is not required. Similarly, num.Min() method can be used to calculate the minimum element of the array num.

16

C#

Exercises
Some practice exercises for the students.

17

Das könnte Ihnen auch gefallen