0% found this document useful (0 votes)
9 views

CH2

Uploaded by

eyob daggy Girma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

CH2

Uploaded by

eyob daggy Girma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 60

Chapter 2

Introducing C# Programming

Compiled By Mezgebu A. 1
Contents

• What is C#.Net
• Variable types and identifiers
• Constants
• Number types, strings
• Operators and operator precedence
• Type Conversion/ Casting

2
Introduction
• Visual Basic won great acclaim for providing programmers
with tools for creating highly detailed user interfaces via an
intuitive form designer, along with an easy to learn
programming language that together produced probably the best
environment out there for rapid application development
(RAD).
• One of the advantages offered by RAD tools such as Visual
Basic is that they provide access to a number of prefabricated
controls that can be used to quickly build the user interface for
an application.
• application development is now available to C# developers
through Visual Studio.
3
What is C#.Net
• The .Net Framework is a key Microsoft offering and it provides a
Multilanguage environment that enables you to develop , deploy, and
run Windows applications, Web applications as well as Web services.
• C#.Net is the most powerful programming language among all
programming language in .Net , because C#.Net will contain all the
feature of C++, VB6.0 and Java and additional features
• In C#.net , the symbol # must should be pronounced by “sharp” only
because Microsoft has taken the symbol from musical note, whose
name is “sharp” 4

• C# is a modern object-oriented, general-purpose programming


language, created and developed by Microsoft together with
the .NET platform.
• We can say that C#.Net=c++ + VB6.0+Java
Types of C# Applications
• C# helps developers build diverse types of applications, which is
why the popularity of this programming language went high.
• Different types of applications that can be developed using C# are:
 Web applications.
 Window applications.
 Other Desktop software.
 Database programs.
 GUI based applications.
 And much, much more!

5
Features of C#
• There are various features of C#, which makes the programming
language different and widely used. These are:
 Learning C# is very easy.
 It is a general-purpose, easy integrating programming language.
 It is a highly structured programming language.
 Object-oriented concepts can be implemented efficiently using this
language.
 It is platform-independent, which means the programs written in C# can
be executed in a variety of computing environments.
 Efficient programming can be done using this language.
 It is a high-level programming language.
 GUI applications can be developed very easily using this language.
6
What is Microsoft Visual studio?

• It is an IDE(Integrated Development
Environment)
• It is just an editor tools used to
write .Net code (develop application
using .net framework)

7
Installation of Microsoft Visual studio

8
Type of application that can be crated using
Microsoft Visual studio
1. Console application
2. Window form application
3. Web application
4. Mobile application
5. Web application
6. Windows service
7. Crystal report application
8. Setup and deployment application
9. WPF application
10. Web service application
11. Device application
12. AJAX enable web application
e.t.c

9
Creating console application
• Click Microsoft Visual studio->click on
file-> click on new-> click on project-
>select console application

10
Structure of C#.Net program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
}
}
}
11
Cont...
Your first line of code
The only thing we’ll do with the code is to write some text to the screen. But
here’s the code that Visual C# prepares for you when you first create a
Console Application:

12
Running your Program

13
Working with Console class

• Console is a class used to work with input


and output
• Console class is present in system
Namespace

14
Method/Function with console
• Write(“message”)
– This is used to display any message to the user
in the out put stream
– E.g Console.Write(“Welcome”).
• WriteLine(Message”)
– This is used to display any message to the user
in the out put stream
– After displaying the message blinking cursor
moves to a new line
– E.g Console.WriteLine(“welcome”).
15
Cont…
• Read()
– This method is used to read a single character
from the input stream
• ReadLine()
– This method is used to read a group of character
from the input stream
• Console.ReadKey()
- The method Console.ReadKey() waits for key pressing
on the console and reads its character equivalent
without the need of pressing [Enter].
16
Variable types and identifiers
• Identifier: is a name given to variables, class, function, constants
and others that identifies the items from others in the computer
program.
• All identifiers must obey the following rules
– An identifier is a sequence of characters that consists of letters,
digits, underscores (_), and dollar signs ($)
– An identifier must start with a letter, an underscore (_), or a dollar
sign ($). It cannot start with a digit.
– An identifier cannot be a reserved word.
– An identifier cannot be true, false, or null.
– An identifier can be of any length

17
Cont…
• Variables : In C#, Variables will represent storage locations and each
variable has a particular type that determines what type of values can be
stored in the variable.
• Variables are for representing data of a certain type. To use a variable, you
declare it by telling the compiler its name as well as what type of data it can
store.
• The variable declaration tells the compiler to allocate appropriate memory
space for the variable based on its data type. The syntax for declaring a
variable is:
datatype variableName;
• Here are some examples of variable declarations:
int count; // Declare count to be an integer variable;
double radius; // Declare radius to be a double variable;
double interestRate; // Declare interestRate to be a double variable;
18
Constants
• The value of a variable may change during the execution
of a program, but a named constant
or simply constant represents permanent data that never
changes.
• For example PI is a constant 3.14159;
• Syntax for declaring a constant:
const datatype CONSTANTNAME = VALUE;
const float PI=3.14159;

19
Data Type in C#.Net

• A data type is a classification of the type of


data that a variable or object can hold(store)

20
Cont…

21
Cont…

22
String type
• The string type enables you to assign string
value to the variable of string type.

23
Declaring of variable

• In C#.Net all variables must be declared


before the can use
– Syntax
– Data_type valid_identifer

24
Key word in C#.net

• Keywords are predefined reserved identifiers


that have special meaning to the compiler
• Keywords can’t be used as variable in your
programming.

25
Cont…

26
Data type conversion in C#.net
• There are two methods available for type
conversion
1. Target data type.parse(“value”)
E.g int.parse(“10”).=>10
double.parse(“10.5”)=>10.5
 The operation of converting a string into another type is
called parsing.

2. Convert.to target data type class(“value”).


E.G Convert.ToInt32(“10”).=>10
convert.toDouble(“10.5”).=>10.5

27
Cont…
• Console.Write("a = ");
• int a = int.Parse(Console.ReadLine());
• Console.Write("b = ");
• int b = int.Parse(Console.ReadLine());
• Console.WriteLine("{0} + {1} = {2}", a, b, a + b);
• Console.WriteLine("{0} * {1} = {2}", a, b, a * b);
• When parsing a string to a number using the method
Int32.Parse(string) or by Convert.ToInt32(string) if the
submitted string is not a number we get an exception.

28
Operators
• Arithmetic Operators

+ addition
- subtraction
* multiplication
/ Division
% modulo
29
Cont…

30
Cont…

= Assignment
++ Increase operator
-- decreasing

31
Cont…
• Compound assignment
expression Is equivalent to

x+=y x=x+y
x-=y x=x-y

x/=y x=x/y
X*=y x=x*y

x++ x=x+1
y-- y=y-1
32
Cont…
• int a = 5;
• int b = 4;
• Console.WriteLine(a + b);
• Console.WriteLine(a + (b++));
• Console.WriteLine(a + b);
• Console.WriteLine(a + (++b));
• Console.WriteLine(a + b);
• Console.WriteLine(14 / a);
• Console.WriteLine(14 % a);

33
Cont…

• Relational and equality operators


== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal

34
Cont….

• Logical operator
&& Conditional and
|| Conditional or
! Conditional not

35
Control statements and loop

36
Contents

• If statement
• Switch statement
• For loop
• While, Do while loop

37
If statement
• C#.net has several types of if statements:
one-way if statements,
two-way if statements,
nested if statements,
 A one-way if statement executes an action if and only if the
condition is true. The syntax for a one-way if statement is
shown below:
if (boolean-expression)
{
statement(s);
}
39
If statement cont…

40
If statement cont…
• Two-Way if Statements: in this statement the system performs the operation
in the if statement when the Boolean expression is true otherwise the else
block of statements are executed. That is the operation is performed based on
the values of the Boolean expression. Here is the syntax for a two-way if
statement:
if (boolean-expression)
{
statement(s) //for-the-true-case;
}
else
{
statement(s) //for-the-else-case;
}

41
If statement cont…

42
If ….else…if
• A common program construct that is based on upon a sequence of nested

Syntax
if (boolean_exp1) {
statement(s)1;
}
else if (boolean_exp2) {
statement(s)2;
}
..
..
else
statement(s)n;

43
Nested if Statements
• Nested if Statements: both if or if ... else statement can be any legal Java
statement, including another if or if ... else statement.
• The inner if statement is said to be nested inside the outer if statement.
• The inner if statement can contain another if statement; in fact, there is no
limit to the depth of the nesting.
Syntax
if (boolean_exp1)
if (boolean_exp2)
else
else
if (boolean_exp3)
else

44
switch Statements
• Switch is one of a selection statement in Java programming language .
Syntax
switch (switch-expression)
{
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
} 45
Cont…

47
C#.net console program Exercises

1. Write a C# program; that receive a number and


determine whether it is positive, negative or zero.
2. Write a C# program, that receive a number and
determine whether it is odd or even.
3. Write a C# program; obtain two numbers from
the keyboard, and determine and display which
(if either) is the larger of the two numbers.
4. Write a C# program; Find the maximum and
minimum, of three numbers given by the user.

48
Type of iteration statement(loop)
• For loop
• While loop
• Do while loop
• For each loop

49
The for Loop
Syntax
for (initial-action; loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
Statement(s);
}

50
Cont…
• Example:
for (int i = 0; i <= 10; i++)
{
Console.WriteLine(i + " ");

}
Console.ReadKey();

52
The while Loop
• The syntax for the while loop is as follows:
initialization ;
• while (loop-continuation-condition) {
// Loop body
Statement(s);
}
• The part of the loop that contains the statements to be repeated is called the loop
body. A one-time execution of a loop body is referred to as an iteration of the loop.
• Each loop contains a loop-continuation-condition, a Boolean expression that
controls the execution of the body.
• It is valuated each time to determine if the loop body is executed. If its evaluation is
true, the loop body is executed; if its evaluation is false, the entire loop terminates
and the program control turns to the statement that follows the while 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.
53
The while loop cont…..

54
Cont…
• Example: The purpose of the loop is to print on the console the numbers in
the range from 0 to 9 in ascending order:
// Initialize the counter
int counter = 0;
// Execute the loop body while the loop condition holds
while (counter <= 9)
{
// Print the counter value
Console.WriteLine("Number : " + counter);
// Increment the counter
counter++;
}

55
The do-while Loop
• The do-while loop is a variation of the while loop. Its syntax is given below:
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
• The loop body is executed first. Then the loop-continuation-condition is
evaluated.
• If the evaluation is true, the loop body is executed again; if it is false, the do-
while loop terminates.
• The difference between a while loop and a do-while loop is the order inwhich
the loop-continuation-condition is evaluated and the loop body executed.
• The while loop and the do-while loop have equal expressive power. Sometimes
one is a more convenient choice than the other.

56
The do-while Loop cont…..

57
Cont..,
• Example: find the product of all numbers in the range [n…m].
Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
Console.Write("m = ");
int m = int.Parse(Console.ReadLine());
int num = n;
long product = 1;
do
{
product *= num;
num++;
} while (num <= m);
Console.WriteLine("product[n...m] = " + product);

58
For each loop
• For each loop is a different kind of looping construct in
c#.Net programming does not include
initialization ,termination and increment /decrement
characteristics
• If use collection to take value one by one then process
them
• This programming construct serves to iterate over all
elements of an array.
Foreach(String name in array_name)
{
} 59
Con…
Example:
int[] numbers = { 2, 3, 5, 7, 11, 13, 17, 19 };
foreach (int i in numbers)
{
Console.Write(" " + i);
}
Console.WriteLine();
string[] towns = { "London", "Paris", "Milan", "New York" };
foreach (string town in towns)
{
Console.Write(" " + town);
}
60
Nested Loop
• That is one loop may be inside another
• The innermost loop is executed more times,
and the outermost – less times.
e.g for (initial-action; loop-continuation-condition; action-after-each-iteration) {
while (loop-continuation-condition) {
// Loop body
Statement(s);
}

61
Cont…
• Example:for a given number n, to print on the
console a triangle with n number of lines
int n = int.Parse(Console.ReadLine());
for (int row = 1; row <= n; row++)
{
for (int col = 1; col <= row; col++)
{
Console.Write(col + " ");
}
Console.WriteLine();
}
Console.ReadKey();
62
C#.net console program Exercises

1. Write a C# program; Add the numbers from 1 to 100 and


display the sum.
2. Write a C# program; Add the even numbers between 0
and any positive integer number given by the user.
3. Write a C# program; read 10 integers from the keyboard
in the range 0 - 100, and count how many of them are
larger than 50, and display this result.
4. Write C# programs; which get a natural value, n, as its
input and calculates sum of odd numbers equal or less
than n.

63

You might also like