0% found this document useful (0 votes)
40 views65 pages

Lu1 - Lo 5 - 8

Uploaded by

Queraysha Jairaj
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)
40 views65 pages

Lu1 - Lo 5 - 8

Uploaded by

Queraysha Jairaj
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/ 65

Introduction to

PROGRAMMING 2A
PROG6221
Lecturer: Mr. Mpho Gift Doctor Gololo
Class contents

• Recap from previous class


• Write a console program that requires user input
• Slides and examples
• In class problems to solve together
• Apply string manipulation to solve a programming problem
• Slides and examples
• In class problems to solve together
• Use implicitly typed variables in a program
• Slides and examples
• In class problems to solve together
• Purpose of nullable
• Slides and examples
• In class problems to solve together
C# - Program
• Comments //
• Inline Comments //
• Multiline comments /* */
• XML documentation Comments ///
• Using Directives
• using System – specify group of classes you
have to access
C# - Program
• Namespace
• Class Definition
• Interfaces – Class Iname
• Main() Method
• Method Body Statement
• Syntax
• Compilation and execution Process in visual
studio.
Common Type System
• In.NET, type implies a member from the set
• A .NET-aware language, interacts with types
• Section header
Understand the five types defined by the CTS in
their language of choice.
• {class, interface, structure, enumeration,
delegate}.
Assemblies, namespaces, and types
• Assembly is a binary unit that contains managed code within .net
core. Assembly may contain any number of distinct types. In the
world of .NET, type is simply a general term used to refer to a member
from the set {class, interface, structure, enumeration, delegate}.
• CTS is a formal specification that documents how types must be
defined in order to be hosted by the CLR.
Assemblies
• Used to avoid name conflicts (many classes with same name) ‰
• Potential for name conflicts much higher in large projects or projects using
many external libraries
• Every class has to be inside a namespace
• Namespaces can be nested
• Classes from the vast library offered by the .NET framework
structured in vast hierarchy of namespaces
• Namespaces orthogonal to the structure of the source code ‰
• There can be multiple namespaces in a single source file, a namespace can
span multiple source files
• The “using somenamespace;” directive gives he convenience of not
having to use fully qualified names for all classes
• May lead to name conflicts, compiler detects ambiguities
Namespace
• A namespace is a grouping of semantically related types contained in
an assembly or possibly spread across multiple related assemblies.
For example, the System.IO namespace contains file I/O–related
types, the System.Data namespace defines basic database types, and
so on.
Standard namespaces

• System contains classes that implement basic functionalities like


mathematical operations, data conversions etc.

• System.IO contains classes used for file I/O operations

• System.Collections.Generic contains classes that implement collections


of objects such as lists, hashtable etc. using C# generics

• System.Text contains classes that manipulate strings and text

• System.Diagnostics contains classes used in profiling and debugging


your application
Installation of Visual studio 2022

Visual Studio download

Start the installation


Installation of Visual studio 2022

Select packages to install


Installation of Visual studio 2022

Installation process Color theme


Installation of Visual studio 2022

Start using Visual Studio


Write a console program that requires user input
Constructions of Note
• using
• like import in Java: bring in namespaces
• namespace
• disambiguation of names
• like Internet hierarchical names and C++ naming
• class
• like in C++ or Java
• single inheritance up to object
Write a console program that requires user input
Constructions of Note
• static void Main()
• Defines the entry point for an assembly.
• Four different overloads – taking string arguments and returning int’s.
• Console.Write(Line)
• Takes a formatted string: “Composite Format”
• Indexed elements: e.g., {0}
• can be used multiple times
• only evaluated once
• {index [,alignment][:formatting]}
Write a console program that requires user input
The System.Console Class
• Console class encapsulates input, output, and error-stream
manipulations for console-based applications.
• Console class does provide some members that can spice up a simple
command-line application, such as the ability to change background
and foreground colors and issue beep noises
Write a console program that requires user input
Basic Input and Output with the Console Class
• Console class defines a set of methods to capture input and output.
• WriteLine() pumps a text string (including a carriage return) to the
output stream.
• Write() method pumps text to the output stream without a carriage
return.
• ReadLine() allows you to receive information from the input stream
up until the Enter key is pressed.
• Read() is used to capture a single character from the input stream.
Write a console program that requires user input
Formatting
• The tokens such as {0} and {1} are embedded within various string
literals.
• Used when you are defining a string literal that contains segments of
data whose value is not known until runtime, you are able to specify a
placeholder within the literal using this curly-bracket syntax.
• At runtime, the values passed into Console.WriteLine() are substituted
for each placeholder.
• Note that the first ordinal number of a curly-bracket placeholder
always begins with 0.
Write a console program that requires user input
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace User_Input
{
internal class Program
{
static void Main(string[] args)
{
// Type your username and press enter
Console.WriteLine("Enter username:");

// Create a string variable and get user input from the keyboard and
store it in the variable
string userName = Console.ReadLine();

// Print the value of the variable (userName), which will display the
input value
Console.WriteLine("Username is: " + userName);
}
}
}
Write a console program that requires user input
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Convert_methods
{
internal class Program
{
static void Main(string[] args)
{
string userInput;
int intVal;
double doubleVal;

Console.Write("Enter integer value: ");


userInput = Console.ReadLine();
/* Converts to integer type */
intVal = Convert.ToInt32(userInput);
Console.WriteLine("You entered {0}", intVal);

Console.Write("Enter double value: ");


userInput = Console.ReadLine();
/* Converts to double type */
doubleVal = Convert.ToDouble(userInput);
Console.WriteLine("You entered {0}", doubleVal);

int sum = Convert.ToInt32(userInput) + Convert.ToInt32(doubleVal);

Console.WriteLine(sum);
Console.ReadLine();
}
}
}
Write a console program that requires user input

• Write a console application to calculate the area of the rectangle with user input
• Calculate the area of the right-angle triangle with user input from the orange triangle
• Extra problem – use an to check if the area of the two right-angle triangles will sum to the area of
the rectangle
12 m

20 m 8m
Write a console program that requires user input
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Area_Calculation
{
internal class Program
{
static void Main(string[] args)
{
string userInput_length;
int length;

string userInput_height;
int height;

string userInput_base;
int base_side;

Console.Write("Please enter the length of the rectangle: ");


userInput_length = Console.ReadLine();
/* Converts to integer type */
length = Convert.ToInt32(userInput_length);
Console.WriteLine("You entered {0}", length);

Console.Write("Please enter the height of the rectangle: ");


userInput_height = Console.ReadLine();
/* Converts to integer type */
height = Convert.ToInt32(userInput_height);
Console.WriteLine("You entered {0}", height);

Console.Write("Please enter the base of the triang;e: ");


userInput_base = Console.ReadLine();
/* Converts to integer type */
base_side = Convert.ToInt32(userInput_base);
Console.WriteLine("You entered {0}", base_side);

int Area_rectacngle = length * height; // Area of a triangle


double Area_triange = 0.5* Convert.ToDouble(base_side) * Convert.ToDouble(height); // Area of a triangle

Console.WriteLine(Area_rectacngle);
Console.WriteLine(Area_triange);

double sum_Areas = Area_triange + Area_triange;

Console.WriteLine(sum_Areas);

Console.WriteLine(sum_Areas == Area_rectacngle);

}
}
Apply string manipulation to solve a programming problem
• System.String provides a number of methods you would expect from
such a utility class, including methods that return the length of the
character data, find substrings within the current string, and convert
to and from uppercase/lowercase
Apply string manipulation to solve a programming problem

• Strings are used for storing text.

• A string variable contains a collection of characters


surrounded by double quotes

• A string in C# is actually an object, which contain


properties and methods that can perform certain
operations on strings.
• Example is a String Length

• Given a string text = “cdscghdc”, then we can get length with txt.length
Apply string manipulation to solve a programming problem
• using System;
• using System.Collections.Generic;
• using System.Linq;
• using System.Text;
• using System.Threading.Tasks;

• namespace Char_string
• {
• internal class Program
• {
• static void Main(string[] args)
• {
• char[] arr = { 'M', 'p', 'h','o' };

• Console.WriteLine(arr.Length);

• string Combined_characters = new string(arr);

• Console.WriteLine(Combined_characters);
• }
• }
• }
Apply string manipulation to solve a programming problem

• String Interpolation substitutes values of variables into


placeholders in a string. Note that you do not have to
worry about spaces, like with concatenation:

• Access Strings - You can access the characters in a string by


referring to its index number inside square brackets [].
Using System

Namespace Strings_Example{
class Program{
static void (){
string firstName = "John";
string lastName = "Doe";
string name = $"My full name is: {firstName} {lastName}";
Console.WriteLine(name);
}
}
}
Apply string manipulation to solve a programming problem

Formatting
• The tokens such as {0} and {1} are embedded within various string
literals.
• Used when you are defining a string literal that contains segments of
data whose value is not known until runtime, you are able to specify a
placeholder within the literal using this curly-bracket syntax.
• At runtime, the values passed into Console.WriteLine() are substituted
for each placeholder.
• Note that the first ordinal number of a curly-bracket placeholder
always begins with 0.
Apply string manipulation to solve a programming problem
Apply string manipulation to solve a programming problem
Apply string manipulation to solve a programming problem

String Methods
Apply string manipulation to solve a programming problem

String Concatenation Strings and Equality


Apply string manipulation to solve a programming problem

Strings and Equality


Apply string manipulation to solve a programming problem

• Merge the following sentences together


• Down the way nights are dark And the sun shines daily on the mountain top
• I took a trip on a sailing ship
• And when I reached Jamaica
• I made a stop

• From the paragraph you get, check for the following substrings using
the Contains method
• Nights, sun, mountain, trip, reached, gone, wrong.

• Are all these strings available in your merged paragraph?


Use implicitly typed variables in a program

• Implicitly typed variables are those variables which are declared


without specifying the .NET type explicitly.

• In implicitly typed variable, the type of the variable is automatically


deduced at compile time by the compiler from the value used to
initialize the variable.

• The implicitly typed variable is not designed to replace the normal


variable declaration, it is designed to handle some special-case
situation like LINQ(Language-Integrated Query).
Use implicitly typed variables in a program

• Why it is termed Local?

• Answer: It is not allowed to use var as a parameter value or return type


in the method or defining it at class level etc. because the scope of the
implicitly typed variable is local.
Use implicitly typed variables in a program
// C# program to illustrate – This should give us an error

// implicitly typed local variable

using System;

public class GFG {

// declaring and initializing implicitly

// typed local variable at class level.

// It will give compile time error

var imp = 15;

// Main method

static public void Main()

// trying to print the value of 'imp'

Console.WriteLine(GFG.imp);

}
Use implicitly typed variables in a program

• Implicitly typed variables are generally declared using var keyword as


shown below:
• var ivariable = 10;

• In implicitly typed variables, you are not allowed to declare multiple var in


a single statement as shown below:
• var ivalue = 20;

• var a = 20;

• It is allowed to use the expression in var like:


• var b = -30;
Use implicitly typed variables in a program

• It is not allowed to use a null value in implicitly typed variable like:


• var ivalue; //not allowed

• The initializer cannot contain any object or collection, it may contain a


new expression that includes an object or collection initializer like:
// Not allowed
• var data = { “23, 24, 10”};

// Allowed
• var data = new int [] {23, 34, 455, 65};
Use implicitly typed variables in a program

• It is not allowed to initialize implicitly typed variable with different


types more than one type

• The following will give error because:


• The type of the value is different

• one is of string type and another

• one is of int type

• var value = "sd"

• value = new int[]{1, 2, };


Use implicitly typed variables in a program
// C# program to illustrate the

// concept of implicitly typed variable

using System;

public class GFG {

// Main method

static public void Main()

// Declaring and initializing

// implicitly typed variables

var a = 50;

var b = "Welcome! Geeks";

var c = 340.67d;

var d = false;

// Display the type of the variables

Console.WriteLine("Type of 'a' is : {0} ", a.GetType());

Console.WriteLine("Type of 'b' is : {0} ", b.GetType());

Console.WriteLine("Type of 'c' is : {0} ", c.GetType());

Console.WriteLine("Type of 'd' is : {0} ", d.GetType());

}
Use implicitly typed variables in a program
// C# program to illustrate the

// use of implicitly typed variable

using System;

class GFG {

// Main method

static public void Main()

// implicitly typed variables

var Base = 13;

var Height = 20;

var Area = (Base * Height) / 2;

// Display result

Console.WriteLine("Height of triangle is: " + Height + "\nBase of the triangle is: " + Base);

Console.Write("Area of the triangle is: {0}", Area);

}
Use implicitly typed variables in a program

• Implicitly typed arrays are those arrays in which the type of the array


is deduced from the element specified in the array initializer.

• The implicitly typed arrays are similar to implicitly typed variable. In


general, implicitly typed arrays are used in the query expression.

• Similarly to implicitly typed variables, there are a set of rules to follow


when using and implementing this typed variables.
Use implicitly typed variables in a program

• Important points about implicitly typed arrays:


• In C#, the implicitly typed arrays do not contain any specific data type.
• In implicitly typed array, when the user initializes the arrays with any
data type then compiler automatically convert these arrays into that
data type.
• Implicitly typed arrays generally declared using var keyword, here var
does not follow [].
• var iarray = new []{1, 2, 3};
• All types of array-like 1-D, Multidimensional, and Jagged Arrays etc.
can be created as an implicitly typed array
• In C#, it is necessary to initialize implicitly typed array and have the
same data type.
Use implicitly typed variables in a program
// C# program to illustrate

// 1-D implicitly typed array

using System;

public class GFG {

// Main method

static public void Main()

// Creating and initializing 1-D

// implicitly typed array

var author_names = new[] {"Shilpa", "Soniya", "Shivi", "Ritika"};

Console.WriteLine("List of Authors is: ");

// Display the data of the given array

foreach(string data in author_names)

Console.WriteLine(data);

}
Use implicitly typed variables in a program
// C# program to illustrate

// 2-D implicitly typed array

using System;

public class GFG {

static public void Main()

// Creating and initializing

// 2-D implicitly typed array

var language = new[, ] { {"C", "Java"},

{"Python", "C#"} };

Console.WriteLine("Programming Languages: ");

// taking a string

string a;

// Display the value at index [1, 0]

a = language[1, 0];

Console.WriteLine(a);

// Display the value at index [0, 2]

a = language[0, 1];

Console.WriteLine(a);

}
Use implicitly typed variables in a program
// C# program to illustrate

// implicitly typed jagged array

using System;

class GFG {

// Main method

static public void Main()

// Creating and initializing

// implicitly typed jagged array

var jarray = new[] { new[] { 785, 721, 344, 123 }, new[] { 234, 600 }, new[] { 34, 545, 808 }, new[] { 200, 220 }

};

Console.WriteLine("Data of jagged array is :");

// Display the data of array

for (int a = 0; a < jarray.Length; a++) {

for (int b = 0; b < jarray[a].Length; b++)

Console.Write(jarray[a][b] + " ");

Console.WriteLine();

}
Use implicitly typed variables in a program
Problem of the day:

• Given the following two matrices: 3

A=2x3 B=3x3

A = [1 4 2B = [3 4 2

2 5 1] 357

1 2 1]

• Use Implicitly typed variables to declare your matrices

• Multiply these two matrices together to get:

• C = 2 x 3 Matrix
Purpose of nullable

• Null types can only work with Value Type, not with Reference Type.

• The Value Data Types will directly store the variable value in memory
and it will also accept both signed and unsigned literals.

• The Reference Data Types will contain a memory address of variable


value because the reference types won’t store the variable value
directly in memory.
Purpose of nullable

• Null types can only work with Value Type, not with Reference Type.

• The Value Data Types will directly store the variable value in memory
and it will also accept both signed and unsigned literals.

• The Reference Data Types will contain a memory address of variable


value because the reference types won’t store the variable value
directly in memory.
Value types

• The derived class for these data types are System.ValueType.

• Different Value Data Types in C# programming language :

• Signed & Unsigned Integral Types : There are 8 integral types which
provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or
unsigned form.

• Floating Point Types :There are different floating point data types
which contain the decimal point. E.g: Float, double, Decimal
Value types
// C# program to demonstrate ulong ul = 3624573;
// the above data types // by default fraction value
using System; // is double in C#
double d = 8.358674532;
namespace ValueTypeTest {

class GeeksforGeeks { // for float use 'f' as suffix


float f = 3.7330645f;
// Main function

static void Main() // for float use 'm' as suffix


decimal dec = 389.5m;
{

// declaring character Console.WriteLine("char: " + a);


Console.WriteLine("integer: " + i);
char a = 'G'; Console.WriteLine("short: " + s);
// Integer data type is generally Console.WriteLine("long: " + l);
Console.WriteLine("float: " + f);
// used for numeric values Console.WriteLine("double: " + d);
int i = 89; Console.WriteLine("decimal: " + dec);
Console.WriteLine("Unsinged integer: " + ui);
short s = 56; Console.WriteLine("Unsinged short: " + us);
// this will give error as number Console.WriteLine("Unsinged long: " + ul);
}
// is larger than short range }
// short s1 = 87878787878; }

// long uses Integer values which

// may signed or unsigned

long l = 4564;
Reference data types

• The Reference Data Types will contain a memory address of variable


value because the reference types won’t store the variable value
directly in memory.

• The built-in reference types are string, object.


• String : It represents a sequence of Unicode characters and its type name is
System.String. So, string and String are equivalent.
• Object : In C#, all types, predefined and user-defined, reference types and
value types, inherit directly or indirectly from Object. So basically it is the base
class for all the data types in C#.
Purpose of nullable
using System;

namespace ValueTypeTest {

class GeeksforGeeks {

// Main Function

static void Main()

// declaring string

string a = "Geeks";

//append in a

a+="for";

a = a+"Geeks";

Console.WriteLine(a);

// declare object obj

object obj;

obj = 20;

Console.WriteLine(obj);

// to show type of object

// using GetType()

Console.WriteLine(obj.GetType());

}
Purpose of nullable

• The Nullable type is an instance of System.Nullable<T> struct.

• Here T is a type which contains non-nullable value types like integer


type, floating-point type, a boolean type, etc. 

• For example, in nullable of integer type you can store values from -
2147483648 to 2147483647, or null value.
• Nullable<data_type> variable_name = null;

• datatype? variable_name = null;


Purpose of nullable

// this will give compile time error

int j = null;

// Valid declaration

Nullable<int> j = null;

// Valid declaration

int? j = null;
Purpose of nullable

• How to access the value of Nullable type variables?

• You cannot directly access the value of the Nullable type.

• You have to use GetValueOrDefault() method to get an original


assigned value if it is not null.

• You will get the default value if it is null. The default value for null
will be zero.
Purpose of nullable
// C# program to illustrate Nullable Types // using Nullable type syntax
using System; // to define non-nullable
class Geeks { int? n2 = 47;
// Main Method
// using the method
static void Main(string[] args)
Console.WriteLine(n2.GetValueOrDefault());
{

// defining Nullable type


// using Nullable type syntax
Nullable<int> n = null; // to define non-nullable
// using the method Nullable<int> n3 = 457;
// output will be 0 as default

// value of null is 0 // using the method


Console.WriteLine(n.GetValueOrDefault()); Console.WriteLine(n3.GetValueOrDefault());
// defining Nullable type
}
int? n1 = null;

// using the method


}
// output will be 0 as default

// value of null is 0

Console.WriteLine(n1.GetValueOrDefault());
Purpose of nullable

Characteristics of Nullable types

• With the help of nullable type you can assign a null value to a variable
without creating nullable type based on the reference type.

• In Nullable types, you can also assign values to nullable type. As


shown in the below example.
Purpose of nullable
// C# program to illustrate the

// use of Nullable type

using System;

class GFG {

// Main Method

static public void Main()

// a is nullable type

// and contains null value

int ? a = null;

// b is nullable type int

// and behave as a normal int

int ? b = 2345;

// this will not print

// anything on console

Console.WriteLine(a);

// gives 2345 as output

Console.WriteLine(b);

}
Purpose of nullable

• You can use Nullable.HasValue and Nullable.Value to check the


value.

• If the object assigned with a value, then it will return “True” and if the
object is assigned to null, then it will return “False”.

• If the object is not assigned with any value then it will give compile-
time error.
Purpose of nullable
// C# program to illustrate the

// use of Nullable<L>.Hasvalue

using System;

class GFG {

// Main Method

static void Main()

// a is nullable type

// and contains null value

Nullable<int> a = null;

// check the value of object

Console.WriteLine(a.HasValue);

// b is nullable type

// and contains a value

Nullable<int> b = 7;

// check the value of object

Console.WriteLine(b.HasValue);

}
Purpose of nullable

• You can also use == and ! operators with nullable type.

• You can also use GetValueOrDefault(T) method to get the assigned


value or the provided default value, if the value of nullable type is
null.

• You can also use null-coalescing operator(??) to assign a value to the


underlying type originate from the value of the nullable type.
Purpose of nullable
// C# program to illustrate the

// use of null-coalescing operator(??)

using System;

class GFG {

// Main Method

static public void Main()

// a is nullable type

// and contains null value

int ? a = null;

// it means if a is null

// then assign 3 to b

int b = a ?? 3;

// It will print 3

Console.WriteLine(b);

}
Purpose of nullable

• Nullable types do not support nested Nullable types.

Advantage of Nullable Types:


• The main use of nullable type is in database applications. Suppose, in
a table a column required null values, then you can use nullable type
to enter null values.
• Nullable type is also useful to represent undefined value.
• You can also use Nullable type instead of a reference type to store a
null value.
Purpose of nullable

• Given the following variables, use the The Null Coalescing Operator
(??)

• How does this operator differ from the ? Operator for true and false

You might also like