0% found this document useful (0 votes)
26 views43 pages

Lecture 3

Uploaded by

happylifehome924
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views43 pages

Lecture 3

Uploaded by

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

Chapter 3: Introduction to array

Program: 6th Semester


Department: BCS
Due Date : 27-08-24
Third lecture

By: DrSerat
Chapter 3

• Introduction to array
• Array declaration
• One dimensional array
Outline
• Two dimensional array
• Multi dimensional array

2
Introduction to array

oAn array stores a fixed-size sequential collection of elements of the


same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of
the same type stored at contiguous memory locations.

oAll arrays consist of contiguous memory locations. The lowest


address corresponds to the first element and the highest address to
the last element.

3
Declaring array

oTo declare an array in C#, you can use the following syntax:
data type[] array name;

oData type is used to specify the type of elements in the array.


o [ ] specifies the rank of the array. The rank specifies the size of the
array.
oArray name specifies the name of the array. For example, int[] x;

4
Initializing an Array

oDeclaring an array does not initialize the array in the memory.


When the array variable is initialized, you can assign values to
the array.

oArray is a reference type, so you need to use the new keyword


to create an instance of the array. For example, int [ ] x = new int
[5];

5
Assigning Values to an Array
o You can assign values to individual array elements, by using the index number, like:
int[] x = new int[4];
x[0] = 2;
o You can assign values to the array at the time of declaration as shown:

int[] x = { 1, 2, 3, 4};
You can also create and initialize an array as shown:
int [] x = new int[4] { 1, 2, 3, 4};
You may also omit the size of the array as shown:
int [] x = new int[] { 1, 2, 3, 4};

o You can copy an array variable into another target array variable. In such case, both the target and source
point to the same memory location:
int [] x = new int[] { 1, 2, 3, 4};
int[] y = x;
6
One dimensional array
using System;

namespace onedimension {
class Program {
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4 };
int[] b = new int[] { 1, 2, 3, 4 };
int[] c = new int[4] { 1, 2, 3, 4 };
int[] d;
d = new int[] { 1, 2, 3, 4 };
Console.WriteLine("a={0} b={1} c={2} d={3}",a[0], b[1], c[2], d[3]);
//now we want to display first array elements through for loop
for (int x = 0; x < 4; x++) {
Console.WriteLine("a={0}", a[x]); }
Console.ReadKey();
}}} 7
Two dimensional array
using System;

namespace twoDimension
{
class Program {
static void Main(string[] args) {
int[,] a = {{ 1, 2, 3, 4, 5, 6 }};
int[,] b = new int[,] {{1,2,3,4,5,6}};
int[,] c = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int[,] d = new int[2, 3] {{ 1, 2, 3}, {4, 5, 6 }} ;
//Console.WriteLine("{0}", d[1, 0]);
//display through nested loop
for (int x = 0; x <2; x++) {
for (int y = 0; y < 3; y++) {

8
Console.WriteLine("{0}", d[x, y]); } }
Multi dimensional array
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication15
{
class Program {
static void Main(string[] args) {
int[, ,] a = {{ { 1, 2, 3, 4, 5, 6,7,8 }} };
int[, ,] b = new int[,,] { { { 1, 2, 3, 4, 5, 6,7,8 } } };
int[,,] c=new int[,,] {{ { 1,2},{3,4}},{ {5,6},{7,8}}};
int[,,] d=new int[2,2,2] {{ { 1,2},{3,4}},{ {5,6},{7,8}}};
//Console.WriteLine(c[0, 0, 0]);
//display through nested for loop
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
for (int z = 0; z < 2; z++) {
Console.WriteLine("{0}", c[x, y, z]); 9
Thanks
10
Chapter 2

• Introduction to key basic syntax


• Identifiers
• Keywords
Outline
• Data types
• Value type
• Reference type
• Pointer type

11
Introduction to key basic syntax

A basic C# program consists of the following parts

Namespace declaration
Class
Class methods
Class attributes
Main method
Statements and Expressions
Comments
12
Introduction to key basic syntax

First program in C sharp

using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(" Hello seventh semester");
Console.ReadKey();

}
}
}
13
Introduction to key basic syntax

oThe first line of the program using System; the using keyword is
used to include the System namespace in the program. A program
generally has multiple using statements.

o The next line has the namespace declaration. A namespace is a collection of


classes. The ConsoleApplication1 namespace contains the class Program.

oActually namespace is used to handle redundancy or remove


conflicts between names. It mean the developer cannot able to
declare two classes with same names.
14
Introduction to key basic syntax

o The next line has a class declaration, the class Program contains the data and
method definitions that your program uses.
o Classes generally contain multiple methods. Methods define the behavior of the
class. However, the Program class has only one method Main.

o The next line defines the Main method, which is the entry point for all C#
programs.
o The Main method in C# is always declared with static because it can’t be call in
other method of function

o The Main method specifies its behavior with the statement


Console.WriteLine("Hello seventh semester"); 15
Introduction to key basic syntax

oWriteLine is a method of the Console class defined in the System


namespace and display message in new line.

oThe last line Console.ReadKey(); is for the VS.NET Users.


oThis makes the program wait for a key press and it prevents the
screen from running and closing quickly when the program is
launched from Visual Studio .NET.

16
Introduction to key basic syntax

Second program in C sharp

using System;

namespace ConsoleApplication {
class Program {
static void Main() {
Console.WriteLine("Please enter any name");

string str = Console.ReadLine();


//ReadLine accept string data and return string data
Console.WriteLine(str);
///////////////
Console.WriteLine("enter any value");
int value = Console.Read();
// Read accept first character of string, character and integer value then return ASCII code
//Console.WriteLine(value);
Console.WriteLine("the ASCII value is={0}",value);
Console.ReadKey();

} } }
17
Identifiers
o An identifier is a name used to identify a class, variable, function, or any other user defined item.

The basic rules for naming classes in C# are as follows:

 A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or
underscore.

The first character in an identifier cannot be a digit.

 It must not contain any embedded space or any special symbols.

an underscore can be allowed.

It should not be a C# keyword.


18
C sharp keywords
Reserved Keywords

abstract as base bool break byte case

catch char checked class const continue decimal

default delegate do double else enum event

explicit extern false finally fixed float for

foreach goto if implicit In in int

null object operator out out override params

private protected public readonly ref return sbyte

19
C sharp keywords
o Keywords are reserved words predefined to the C# compiler. These keywords cannot be
used as identifiers. However, if you want to use these keywords as identifiers, you may
prefix the keyword with the @ character.

Contextual Keywords

add alias ascending descending dynamic from get

global group into join let orderby set


Partial remove select

20
Data Types

The variables in C#, are categorized into the following types:

Value types

Reference types

Pointer types

21
Value Type
o Value type variables can be assigned a value directly.
They are derived from the class (System.ValueType).

o The value type contain two types:


o Predefined types: directly contain data. For example int, char, float, which store number,
alphabet, and floating point number, respectively.
o User defined types: enumeration, structures.

o When you declare an int type, the system allocates


memory to store the value.

22
Value Type
Type Represents Range

Bool Boolean value True or False

Byte 8-bit unsigned integer 0 to 255

Char 16-bit Unicode character U +0000 to U +ffff

decimal 128-bit precise decimal values with 28-29 significant digits (-7.9 x 1028 to 7.9 x 1028) / 100 to 28

double 64-bit double-precision floating point type (+/-)5.0 x 10-324 to (+/-)1.7 x 10308

Float 32-bit single-precision floating point type -3.4 x 1038 to + 3.4 x 1038

Int 32-bit signed integer type -2,147,483,648 to 2,147,483,647

Long 64-bit signed integer type -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

sbyte 8-bit signed integer type -128 to 127

short 16-bit signed integer type -32,768 to 32,767

uint 32-bit unsigned integer type 0 to 4,294,967,295

ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615

ushort 16-bit unsigned integer type 0 to 65,535

23
Reference Type
o The reference types do not contain the actual data stored
in a variable, but they contain a reference to the variables.

o In other words, reference type refer to a memory location.

o If the data in the memory location is changed by one of


the variables, the other variable automatically reflects
this change in value. Built-in reference type(or predefined type)
contain two types:
o Predefined type: object, dynamic, and string.
o User defined type: classes, array, delegate, interface. 24
Object Type
o The Object Type is the critical base class for all data types in
C# Common Type System (CTS).

o Object is an alias for System.Object class.

o The object types can be assigned values of any other types, value
types, reference types, predefined or user-defined types.
However, before assigning values, it needs type conversion.

o When a value type is converted to object type, it is called boxing


and on the other hand, when an object type is converted to a
value type, it is called unboxing. 25
Object Type/ Example
Boxing is the process of converting a value type to the type
object or to any interface type implemented by this value type.

 Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit.

o The integer variable z is boxed and assigned to object obj.

int z= 5; object obj = z; boxing


o The object obj then unboxed and assigned to integer variable z
obj = 5; z = (int)obj; unboxing

26
Type conversion/ Example

using System; Console.WriteLine("please enter two values");


namespace ConsoleApplication a = int.Parse (Console.ReadLine());
// b = int.Parse (Console.ReadLine());
{
b = Convert.ToInt32 (Console.ReadLine());
class Program c = a + b; //Boxing
{
static void Main() result = Convert.ToInt32(c); // Unboxing
{ // result = (int)c; // Unboxing
Console.WriteLine(result);
int a, b;
Console.ReadKey();
object c;
int result; }}}

27
Dynamic Type
o We can store any type of value in the dynamic data type variable.
o Type checking for these types of variables takes place at run-time.
o Syntax for declaring a dynamic type is:
dynamic <variable_name> = value; dynamic d = 20;

o Dynamic types are similar to object types except that type checking for object type
variables takes place at compile time, whereas that for the dynamic type variables takes
place at run time.

28
String Type
o String Type allows you to assign any string values to a variable. The string type is an alias for
the System.

o String class derived from object type.

o The value for a string type can be assigned using string literals in two forms: quoted and
@quoted. For example,
String str = “semester";

29
Pointer Type
o Pointer type variables store the memory address of another type.

o Pointers in C# have the same capabilities as the pointers in C or C++.

o Syntax for declaring a pointer type is:

o type* identifier; For example, char* a; int* b;

30
Thanks
31
Lecture Agenda
• Visual Studio 2022 and Installation
• Create a Project in Visual Studio
• Class, Object and Object Initializer
• Primary Constructor
• What and why extension methods?
Visual Studio 2022 and
Installation
• Visual Studio is a comprehensive integrated development
environment (IDE) developed by Microsoft.
• It provides tools and services for building various types of
applications, including desktop, web, mobile, cloud, and more.
Visual Studio 2022 and
Installation
• To install Visual Studio 2022, you can visit the official Microsoft Visual
Studio website and download the installer.
• Run the installer and follow the on-screen instructions to complete
the installation process.
• During installation, you can choose the workload(s) relevant to your
development needs, such as .NET desktop development, ASP.NET web
development, or mobile development with .NET.
Create a Project in Visual Studio
• Open Visual Studio 2022.
• Click on "Create a new project" or go to File > New > Project.
• Choose the type of project you want to create (e.g., Console
Application, Windows Forms Application, ASP.NET Web Application,
etc.).
• Select the target framework and other project settings as needed.
Create a Project in Visual Studio
• Click on "Create" to create the project.
• Visual Studio will generate the necessary project files and structure
based on your selection.
Class, Object, and Object
Initializer
• In C#, a class is a blueprint for creating objects. It defines the
properties, methods, and behavior that objects of the class will have.
• An object is an instance of a class. It represents a specific instance of
the class with its own set of property values.
• Object initializer is a syntax in C# that allows you to initialize the
properties of an object at the time of object creation, rather than
setting them individually after the object has been created. It provides
a concise and readable way to initialize object properties.
Con…
• // Define a class
• public class Person
• {
• public string Name { get; set; }
• public int Age { get; set; }
• }

• // Create an object of the class and initialize its properties using object
initializer
• Person person = new Person { Name = "John", Age = 30 };
Primary Constructor
• A primary constructor is a feature introduced in C# 9.0 that allows you
to declare constructor parameters directly in the class's definition,
reducing boilerplate code.
• It simplifies the process of initializing object properties by
automatically assigning constructor parameters to class properties.
Con…
• // Define a class with a primary constructor
• public class Person(string name, int age)
•{
• public string Name { get; init; } = name;
• public int Age { get; init; } = age;
•}

• // Create an object of the class using the primary constructor


• Person person = new("John", 30);
Extension Methods
• Extension methods allow you to add new methods to existing types
without modifying the original type or creating a new derived type.
• They are defined as static methods in a static class and are called as if
they were instance methods of the extended type.
• Extension methods are commonly used to add functionality to types
that you don't have control over (e.g., types defined in third-party
libraries or framework classes).
Con…
• public static class StringExtensions {
• public static string Reverse(this string input) {
• char[] charArray = input.ToCharArray();
• Array.Reverse(charArray);
• return new string(charArray);
• }
• }
• // Usage of extension method
• string original = "hello";
• string reversed = original.Reverse(); // reversed will be "olleh"
Summary
• Visual Studio 2022 and Installation
• Create a Project in Visual Studio
• Class, Object and Object Initializer
• Primary Constructor
• What and why extension methods?

You might also like