Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Lecture 7 - Function and Array

The document discusses visual programming using C# and .NET. It covers topics like C# syntax, language constructs, creating and invoking methods, developing graphical applications using structs, enums, and collections, handling events and interfaces, inheritance and polymorphism, accessing databases using LINQ, designing user interfaces with XAML, and improving performance with multithreading and asynchronous operations. Code examples are provided to demonstrate method declaration, invocation, overloading, exception handling, and recursive methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Lecture 7 - Function and Array

The document discusses visual programming using C# and .NET. It covers topics like C# syntax, language constructs, creating and invoking methods, developing graphical applications using structs, enums, and collections, handling events and interfaces, inheritance and polymorphism, accessing databases using LINQ, designing user interfaces with XAML, and improving performance with multithreading and asynchronous operations. Code examples are provided to demonstrate method declaration, invocation, overloading, exception handling, and recursive methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Visual Programming

Department of CSE, QUEST


Dr. Irfana Memon
Dr. Irfana Memon
Department of CSE, QUEST

https://sites.google.com/a/quest.edu.pk/dr-irfana-memon/lecture-slides
Course Content
Review of C# Syntax: Overview of Writing Applications using C#, Data types, Operators, and
Expressions
C# Programming Language Constructs, Creating Methods
Invoking Methods, Handling Exceptions, Creating overloaded Methods

Developing the Code for a Graphical Application: Implementing Structs and Enums
Implementing Type-safe Collections: Creating Classes, Organizing Data into Collections,

Department of CSE, QUEST


Dr. Irfana Memon
Handling Events, Defining and Implementing Interfaces
Creating a Class Hierarchy by Using Inheritance, Extending .NET Framework Classes,
Creating Generic Types
Accessing a Database: Creating and Using Entity Data Models, Querying and Updating Data
by Using LINQ
Designing the User Interface for a Graphical Application: Using XAML, Binding Controls to
Data, Styling a User Interface
Improving Application Performance and Responsiveness: Implementing Multitasking by
using Tasks and Lambda Expressions
2
Performing Operations Asynchronously, Synchronizing Concurrent Access to Data
C# Programming
language constructs,
Creating Methods,

Department of CSE, QUEST


Dr. Irfana Memon
Invoking Methods,
Overloaded Methods,
and Handling
Exceptions 3
C# Methods/Functions
• In C#, Method is a separate code block and that contain a
series of statements to perform a particular operations and
methods must be declared either in class or struct by
specifying the required parameters.
• Methods in C# are portions of a larger program that perform
specific tasks.

Department of CSE, QUEST


Dr. Irfana Memon
• They can be used to keep code clean by separating it into
separate pieces.
• They can also be used in more than one place allowing you to
reuse previous code.

4
Declaring C# Methods
• The general form of method declaration is
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
Method Body
}
Following are the various elements of a method −
Access Specifier − This determines the visibility of a variable or a method from

Department of CSE, QUEST


Dr. Irfana Memon
another class.
Return type − A method may return a value. The return type is the data type of the
value the method returns. If the method is not returning any values, then the return
type is void.
Method name − Method name is a unique identifier and it is case sensitive. It cannot
be same as any other identifier declared in the class.
Parameter list − Enclosed between parentheses, the parameters are used to pass
and receive data from a method. The parameter list refers to the type, order, and
number of the parameters of a method. Parameters are optional; that is, a method
may contain no parameters. 5
Method body − This contains the set of instructions needed to complete the
required activity.
Declaring C# Methods
Method parameters are enclosed in parentheses and are separated by commas.
Empty parentheses indicate that the method requires no parameters. This class
contains four methods:
abstract class Motorcycle
{
// Anyone can call this.
public void StartEngine()
{
/* Method statements here */

Department of CSE, QUEST


Dr. Irfana Memon
}
// Only derived classes can call this.
protected void AddGas(int gallons)
{
/* Method statements here */
}
// Derived classes can override the base class implementation.
public virtual int Drive(int miles, int speed)
{
/* Method statements here */
return 1;
6
}
// Derived classes must implement this.
public abstract double GetTopSpeed();
}
Monitoring Applications using
creating and Invoking Methods
Programming Example
namespace Declaring_Method
{
class Program
{
string name, city;

Department of CSE, QUEST


Dr. Irfana Memon
int age;
// Creating method for accepting details
public void acceptdetails()
{
Console.Write("\nEnter your name:\t");
name = Console.ReadLine();
Console.Write("\nEnter Your City:\t");
city = Console.ReadLine();
7
Console.Write("\nEnter your age:\t\t");
age = Convert.ToInt32(Console.ReadLine());
}
Monitoring Applications using
creating and Invoking Methods
Programming Example
// Creating method for printing details
public void printdetails()
{
Console.Write("\n\n===================");

Department of CSE, QUEST


Dr. Irfana Memon
Console.Write("\nName:\t" + name);
Console.Write("\nCity:\t" + city);
Console.Write("\nAge:\t" + age);
Console.Write("\n===================\n");
}

8
Monitoring Applications using
creating and Invoking Methods

Programming Example
static void Main(string[] args)
{
Program p = new Program();

Department of CSE, QUEST


Dr. Irfana Memon
p.acceptdetails();
p.printdetails();
Console.ReadLine();
}
}
}

9
Declaring C# Methods
Example: Code shows a function FindMax that takes two integer values
and returns the larger of the two. It has public access specifier, so it can
be accessed from outside the class using an instance of the class.

Department of CSE, QUEST


Dr. Irfana Memon
10
Declaring C# Methods
Example: Following code shows a function FindMax that takes two
integer values and returns the larger of the two. It has public access
specifier, so it can be accessed from outside the class using an instance of
the class.
class NumberManipulator
{
public int FindMax(int num1, int num2)

Department of CSE, QUEST


Dr. Irfana Memon
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else result = num2;
return result; 11
}
}
Calling C# Methods
You can call a method using the name of the method. The following
example illustrates this:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */

Department of CSE, QUEST


Dr. Irfana Memon
int result;
if (num1 > num2) result = num1;
else result = num2; return result;
}
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator(); //calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine(); 12
}
}
}
Recursive Method in C#
A method can call itself. This is known as recursion. Following is an example that calculates factorial
for a given number using a recursive function −
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* local variable declaration */
Int result;

Department of CSE, QUEST


Dr. Irfana Memon
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num; return result;
}
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//calling the factorial method {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8)); 13
Console.ReadLine();
}
}
}
Passing Parameters to a Method in
C#
• When method with parameters is called, you need to pass the parameters to the
method. There are three ways that parameters can be passed to a method −

Sr.No. Mechanism & Description


1 Value parameters This method copies the actual
value of an argument into the formal parameter of
the function. In this case, changes made to the

Department of CSE, QUEST


Dr. Irfana Memon
parameter inside the function have no effect on the
argument.
2 Reference parameters This method copies the
reference to the memory location of an argument
into the formal parameter. This means that changes
made to the parameter affect the argument.
14
3 Output parameters This method helps in returning
more than one value.
Exercise
1. Create a static function add() that accept two number from user and
returns sum of the number.

Department of CSE, QUEST


Dr. Irfana Memon
15
Exercise
1. Create a static function add() that accept two number from user and
returns sum of the number.
class Program
using System; {
namespace Example1 static void Main(string[] args)
{ {
class calculation calculation.add();
{ }
static int num1, num2, result; }
public static void add()

Department of CSE, QUEST


Dr. Irfana Memon
}
{
Console.Write("Enter number 1st.\t");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number 2nd.\t");
num2 = Convert.ToInt32(Console.ReadLine());
result = num1 + num2;
Console.Write("\nAdd = {0}", result);
Console.ReadLine();
}
} 16
Exercise
2. Write a program that calculate add, subtract, multiply and division.
Accept two number from the users and then using appropriate function
calculate them and shows output to the user.

Department of CSE, QUEST


Dr. Irfana Memon
17
Creating Overloaded Methods
• Method overloading allows programmers to use multiple
methods with the same name.
• The methods are differentiated with their number and type
of method arguments.
• Method overloading is an example of the polymorphism
feature of an object oriented programming language.

Department of CSE, QUEST


Dr. Irfana Memon
• Method overloading can be achieved by the following:
 By changing number of parameters in a method
 By changing the order of parameters in a method
 By using different data types for parameters

18
Creating Overloaded Methods
Here is an example of method overloading.
public class Methodoveloading
{
public int add(int a, int b) //two int type Parameters method
{
return a + b;

}
public int add(int a, int b,int c) //three int type Parameters with same method same a

Department of CSE, QUEST


Dr. Irfana Memon
s above
{
return a + b+c;
}
public float add(float a, float b,float c,float d) //four float type Parameters with same
method same as above two method

{
return a +b+c+d;
19
}
}
Arrays in C#
• An 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.
• The lowest address corresponds to the first element and the

Department of CSE, QUEST


Dr. Irfana Memon
highest address to the last element.

20
Declaring Arrays in C#
• To declare an array in C#, you can use the following syntax −

datatype[] arrayName;

Department of CSE, QUEST


Dr. Irfana Memon
21
Initialization of Arrays in C#
• Array is a reference type, so you need to use
the new keyword to create an instance of the array.
• For example,
double[] balance = new double[10];

Department of CSE, QUEST


Dr. Irfana Memon
22
Assigning values to Arrays in C#
• You can assign values to individual array elements, by using the
index number,
double[] balance = new double[10]; balance[0] = 4500.0;
• You can assign values to the array at the time of declaration, as
shown −
double[] balance = { 2340.0, 4523.69, 3421.0};
• You can also create and initialize an array, as shown −

Department of CSE, QUEST


Dr. Irfana Memon
int [] marks = new int[5] { 99, 98, 92, 97, 95};
• You may also omit the size of the array, as shown −
int [] marks = new int[] { 99, 98, 92, 97, 95};
• 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 [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks;
23
• When you create an array, C# compiler implicitly initializes each
array element to a default value depending on the array type. For
example, for an int array all elements are initialized to 0.
Accessing elements of Arrays in C#
• An element is accessed by indexing the array name.
• This is done by placing the index of the element within
square brackets after the name of the array.
• For example,
double salary = balance[9];

Department of CSE, QUEST


Dr. Irfana Memon
24
Exercise: Arrays in C#
Write a C# program to count a specified number in a given array of
integers.

Department of CSE, QUEST


Dr. Irfana Memon
25
Exercise: Arrays in C#
Write a C# program to count a specified number in a given array of
integers.

Department of CSE, QUEST


Dr. Irfana Memon
26
Exercise: Arrays in C#
Write a C# program to count a specified number in a given array of
integers.
using System;
public class Exercise
{
static void Main(string[] args)
{

Department of CSE, QUEST


Dr. Irfana Memon
Console.WriteLine("\nInput an integer:");
int x =Convert.ToInt32(Console.ReadLine());
int[] nums = {1, 2, 2, 3, 3, 4, 5, 6, 5, 7, 7, 7, 8, 8, 9};
Console.WriteLine("Number of " + x + " present in the said array:");
Console.WriteLine(nums.Count(n => n == x));
}
}
27
Exercise: Arrays in C#
Write a C# program to check if a number appears as either the
first or last element of an array of integers and the length is 1 or
more.

Department of CSE, QUEST


Dr. Irfana Memon
28
Exercise: Arrays in C#
Write a C# program to check if a number appears as either the
first or last element of an array of integers and the length is 1 or
more.

Department of CSE, QUEST


Dr. Irfana Memon
29
Exercise: Arrays in C#
Write a C# program to check if a number appears as either the
first or last element of an array of integers and the length is 1 or
more.

using System;
public class Exercise
{

Department of CSE, QUEST


Dr. Irfana Memon
public static void Main()
{
Console.WriteLine("\nInput an integer:");
int x = Convert.ToInt32(Console.ReadLine());
int[] nums = {1, 2, 2, 3, 3, 4, 5, 6, 5, 7, 7, 7, 8, 8, 9};
Console.WriteLine( (nums[0] == x) || (nums[nums.Length - 1] == x));
}
} 30
Exercise: Arrays in C#
1. Write a C# program to compute sum of all the elements
of an array of integers.

Department of CSE, QUEST


Dr. Irfana Memon
31
Wish You Good Luck

Dr. Irfana Memon


32

Department of CSE, QUEST

You might also like