0% found this document useful (0 votes)
37 views162 pages

Advanced Programming - Part 1

The document outlines the Advanced Programming course (AERO 108 / ME 108) taught by Seyed Yaser Nabavi at Gebze Technical University, detailing the syllabus, evaluation methods, and course rules. It emphasizes the importance of programming skills for aerospace engineers and provides a structured approach to learning C# programming. The course includes theoretical and laboratory components, with assessments based on midterms and finals, while projects and assignments are optional but recommended for practice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views162 pages

Advanced Programming - Part 1

The document outlines the Advanced Programming course (AERO 108 / ME 108) taught by Seyed Yaser Nabavi at Gebze Technical University, detailing the syllabus, evaluation methods, and course rules. It emphasizes the importance of programming skills for aerospace engineers and provides a structured approach to learning C# programming. The course includes theoretical and laboratory components, with assessments based on midterms and finals, while projects and assignments are optional but recommended for practice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 162

Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Advanced Programming
Spring 2025
Gebze Technical University
Department of Aerospace Engineering
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Who am I?
• Current Position: Assistant Professor at Gebze Technical University
• Work experience:
• Over 15 years research and industrial experiences
• Four years in academia
• Education:
• BSc in Aerospace Engineering from Sharif University of Technology – 1999
• MSc in Aerospace Engineering from Sharif University of Technology - 2001
• PhD in Aerospace Engineering from Sharif University of Technology – 2017
• Fields of Interest:
• Flight Dynamics and Control
• Guidance, Navigation and Control
• Design and Optimization
• System Concepts and System Engineering
• Space Robotics
• System Identification
• Room: Aerospace Dept. – Room 212
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Course Syllabus
Week 1 Introduction, Applications, Programming Necessity, Programming Languages, IDE
Week 2 Project Structure, Data Types, Concept of Object
Week 3 C# Programming Fundamental topics: Arrays, Loops, Conditionals, Debugging Techniques
Week 4 C# Programming advanced topics: Exception Handling, Methods
Week 5 C# Programming advanced topics: Passing by reference, Method overloading, Method Delegating
Week 6 Streams, File Handling, Introductory topics on using the database
Week 7 Example of application of computer programming techniques in a complicated aerospace problem
Week 8 Midterm Exam
Week 9 Programming paradigms, Classes and Objects, Lists and Constructors
Week 10 OOP concepts – Dynamic Link Libraries, Encapsulations
Week 11 OOP concepts – Inheritance
Week 12 OOP concepts – Abstraction, Polymorphism
Week 13 Example of application of OOP techniques in a complicated aerospace problem
Week 14 Introduction to Windows Form Application Development
Week 15 ----
Week 16 Final Exam
Textbook Learning Object-Oriented Programming in C# 5.0, BM Harwani
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Evaluation Method
The initial assessment plan – It be finalized during the course
depending on how course is going on
• Assignments: 0 / 100 (Optional)
• Midterm: 50 / 100
• Project: 0/100 (Optional)
• Final: 50/100
IMPORTANT NOTE: The direct score for assignments and the project is
0 (as stated above). However, you will receive little to no score from
the midterm and final exams if you do not complete them. While they
may seem optional, you must complete them to pass.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Rules
• Attendance is mandatory as per GTU rules (up to 3 absences are acceptable). If you have any excuses, such as a health problem,
please present them to the department secretary. If approved, the absence will not be considered in the assessment.

• The class consists of two parts: Theory (2 hours) and Laboratory (2 hours). Theory sessions will follow the
planned schedule. In the laboratory, you will write code on a computer according to the schedule provided in each
class.

• For the laboratory, you will be divided into groups, each working under the supervision of a TA. The laboratory
sessions will be online by default after class, but the timing can be adjusted based on mutual agreement.

• The midterm exam is scheduled for the 8th session (April 19, 2025) during the class time.

• The final exam is scheduled to be in the first week of the exams during the class time

• The minimum required score in the mid-term exam is 30 (Below this grade your grade will be VF)

• Exclusively utilize C# as the programming language and Visual Studio 2022 as the IDE in this course.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Conversion scales
• The conversion of numeric scores to alphabetical grades normally will
be carried out according to the scales provided on the GTU website.
Numeric Range Score
[0-39) FF 0.0
[39-53) DD 1.0
[53-63) DC 1.5
[63-68) CC 2.0
[68-78) CB 2.5
[78-83) BB 3.0
[83-89) BA 3.5
[89-100) AA 4.0
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Examples, Project and Assignments


• The term project involves the simulation of space systems, with detailed information
provided and to be presented at the beginning of the course.

• Throughout the term, a class example focusing on rocket simulation will be solved step
by step.

• As part of your assignments, you are asked to apply the same steps demonstrated in the
example to your project.

• Projects and assignments are for practice only (they are not graded). However, it is
highly recommended to complete them if you want to pass this course.

• IMPORTANT NOTE: This course is highly practice-oriented, and passing it requires


coding. As a general guideline for working at home:
• Reading time: 20%
• Coding time 80%
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

PART I – Foundation of C# Programming


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Why do we (as mechanical/aerospace


engineers) need to learn computer
programming?
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Why computer programming?


Tools and
Physical Laws
Materials
For developing a new product

In the first perspective we may think


Products
that we can use only available Computer
Mechanical /
Aerospace
resources, including humans and Programmers
Engineers
tools, for development phase.

Manager Software's
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Why computer programming?

Think more !!!!


• Example:
We want to design a vehicle that
1. Starts to fly from an airport
2. Then lands on water (sea, lake, ocean, …)
3. Then goes deep under the water level
4. Then take some pictures there
5. Then go back to the water level
6. Finally flies from there and come back to the airport
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Why computer programming?

• 3D Modeling
• Flight Analysis
• Sizing Modeling • Aerodynamic • User Interface
Rough Analysis Impleme
Analysis • Timing And • Hydrodynamic ntation
• Control and
Management
• …. Analysis Analysis
• Underwater
Movement Analysis
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Why computer programming?


Tools and
Develop Own materials
Knowledge /
Codes
Experience

Mechanical /
Available Software Engineers
Aerospace
Software's / Other colleagues
Engineer

Product
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Why computer programming?


For research purpose
New Idea

Analytical Approaches

Formulation
Numerical Approaches

Improving available software's


Solution
Developing New Codes

Evaluation
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Why computer programming?


How engineering software's are generally developed
An initial Need
for Solving a Marketing
problem Computer code
development
Verification and A general need is
Validation identified

Mechanical / Aerospace
Engineer Code Improvement /
Creating GUI
Software Engineer
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Why computer programming?


Dassault Systèmes (also known as 3DS) grew
out of the aerospace industry's search for more
sophisticated drafting tools to streamline the
development process and aid in the increasing
complexity of aviation design.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Applications of computer programming


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Applications?
Applications – Physical Perspective
(Not comprehensive just to make the subject clear)
Computer
Programming Software and Codes
Hardware
Microprocessors Design Analysis
Development
and
Microcontrollers Kits AutoCad NASTRAN
Arduino

ARM Arduino
CATIA FLUENT
AVR Raspberry Pi
Siemens NX ABAQUS
Intel BeagleBone Black
Developed Codes Developed Codes
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Applications?
Applications – Functional Perspective
(Not comprehensive just to make the subject clear)

Numerical User Communication User


Hardware
Analysis Interface Between Hardware's Interface
Data Management Modeling and Artificial Digital Control
and Storing Simulations Intelligence Systems
Graphical Representation

Graphical Web-Based User/Product Fault


Representation Operations Interface Detection
Communication On-Line
between users Calculations
Implementation
Design
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
1

Introduction – Applications? Use available


software with
Applications current
features 5
2 Write your
Connect
• Available Solutions for an Engineer own code for
available an specific
Software's to problem or to
• All of these solutions need Computer programming extend open-
Programming skills – Except solution 1 languages Mechanical source codes
Engineer
• Even for communicating with a software
Engineer you should have programming Communicate
3 Use available 4
Skills for an effective communication with a
Software
while defining Software
Computer Programming Knowledge add-ins, engineer to
is not a choice it is a must!!! macros, … develop an
special code
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Applications?
Applications – Hardware Development Kit
The Hardware Development Kit is a collection of hardware design resources that
have been gathered to assist in the development of custom hardware

Arduino Uno R3 SMD CH340 Chipset Klon (Usb Kablo Dahil) | SAMM Market
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Applications?
Applications – Intelligent Systems
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Applications?
Applications – Software Development

Hardware Software and Codes


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Computer Programming Languages


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages

Low Level Languages High Level Languages

Machin Assembly Structured Procedural Object-Oriented


Language Language Programming Programming Programming
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
Low Level Languages High Level Languages

Machin Assembly Structured Procedural Object-Oriented


Language Language Programming Programming Programming

Low Level Languages

Low-level languages are used to write programs that relate to the specific architecture and
hardware of a particular type of computer. They are closer to the native language of a
computer (binary)
They are mostly used to develop operating systems, device drivers, databases and
applications that require direct hardware access
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
Low Level Languages High Level Languages

Machin Assembly Structured Procedural Object-Oriented


Language Language Programming Programming Programming
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
Low Level Languages High Level Languages

Machin Assembly Structured Procedural Object-Oriented


Language Language Programming Programming Programming

Low Level Languages - Advantages

• Fast and memory efficient.


• Programmers can utilize processor and memory in a better way
• There is no need of any compiler or interpreters to translate the source to machine code.
• Direct manipulation of computer registers and storage.
• They can directly communicate with hardware devices
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
Low Level Languages High Level Languages

Machin Assembly Structured Procedural Object-Oriented


Language Language Programming Programming Programming

Low Level Languages - Disadvantages

• Programs are machine dependent and are not portable.


• It is difficult to develop, debug and maintain.
• Low-level programs are more error-prone.
• Low-level programming usually results in poor programming productivity.
• A programmer must have additional knowledge of the computer architecture of a particular
machine, for programming in the low-level language.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
Low Level Languages High Level Languages

Machin Assembly Structured Procedural Object-Oriented


Language Language Programming Programming Programming

High Level Languages


High-level languages are similar to the human language.
They do not interact directly with the hardware. Rather, they focus more on the complex
arithmetic operations, optimal program efficiency and easiness in coding.
High-level programs require compilers/interpreters to translate source code to machine language
Examples: FORTRAN, C++, C#, Python, Java
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
Low Level Languages High Level Languages

Machin Assembly Structured Procedural Object-Oriented


Language Language Programming Programming Programming

High Level Languages – Advantages

• Programmer friendly, Easy to write, debug and maintain.


• Higher level of abstraction
• Machine independent
• Easy to learn.
• Less error-prone, easy to find and debug errors.
• Better programming productivity
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
Low Level Languages High Level Languages

Machin Assembly Structured Procedural Object-Oriented


Language Language Programming Programming Programming

High Level Languages – Disadvantages

• Additional translation times to translate the source to machine code.


• Comparatively slower than low-level programs.
• Less memory efficient.
• Cannot communicate directly with the hardware.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
An interpreted language is a type of
programming language for which most of its
implementations execute instructions directly A compiler is a program that converts
and freely, without previously compiling a human-readable code into computer-
program into machine-language instructions readable instructions—a process that
only happens once in the lifespan of that
code.
Ruby
JavaScript
Interpreted FORTRAN
BASIC
Python Languages Compiled C++
Languages C#
GO
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – Computer Programming Languages


Speaking in a Foreign Language

Compiled
Human brain Computer interface
Language

Low-Level Computer Programming


Interpreted
Language

Speaking in the native Language


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
Advantages Disadvantages
• Easy to learn and use • usually run quite slowly
• Minimum programming knowledge or experience • Limited access to low level and speed
• Allows complex tasks to be performed in relatively optimization code.
Interpreted

few steps • Limited commands to run detailed


• Allows simple creation and editing in a variety of text operations on graphics.
editors
• Allows the addition of dynamic and interactive
activities to web pages
• Edit and running of code is fast.
Compiled

• Fast execution • Require a compiler


• Optimized for the target hardware • Editing and Deploying the code is a lot
slower than interpreters.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Introduction – Computer Programming
Languages
C# C++ Python Fortran
Easiness to learn Medium Very Hard Simple Very Simple
Organization Very Organized Very Organized Less Organized Less Organized
Code Performance High Very High Very Low Very High
Available Libraries and Resources Very Rich Rich Extremely Rich Poor
Community Very big Big Very big Small
Development Speed Intermediate Slow Very Fast Fast
Structure Static Static Dynamic Static
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Integrated Development Environment


(IDE)
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – IDE
Note: In advanced programming projects it may be wanted to develop a huge software

Examples
Are not necessarily accurate – Just to make sense

Software lines of code


Google Chrome Browser 6-7 Millions
Mac OS X Tiger 85 millions
Facebook 61 Millions PHP, C++, Python, Java
Microsoft Office 45-50 Millions C++
Microsoft Windows 10 40 Millions C++
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – IDE
These software's are developed by a team of engineers over a long period of time

Advanced programming tools are developed to support the projects done by a team

Even for simple works these tools define a project by default with a predefined structure

For complex projects the structure will be changed by the development team
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – IDE
IDE : Integrated Development Environment
Code
Debugger
editor
Integrated development environments (IDE) are
applications that facilitates the development of other Class
Compiler hierarchy
applications. diagram

IDE
Build Class
automation browser
tools

Object
browser
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – IDE
• Support multiple programming languages
Multi-language IDE • Visual Studio, Visual Studio Code

• As the market for mobile app development grows, numerous


Mobile development programming tools are becoming available to help software
developers build efficient mobile apps
IDE • Android Studio and Xcode

• Supports a cloud-based development environment


Web/cloud-based IDE • Platform-independent
• AWS Cloud9

• They are specifically built to support developers who work on


only one programming language
Specific-language IDE • Jcreator for Java, Idle for Python and CodeLite for C++, Arduino
IDE
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Introduction – IDE
In This course we use Visual Studio 2022 IDE

Advantages:
• It is very powerful in developing, editing and compiling of codes
• It supports Multi-Language Programming
• It has many plug-ins which enables it to be used for other applications (e.g.
Arduino Programming)
• It is free
Disadvantages:
• It requires lots of space
• It is relatively slow
• It may make you dependent on using Windows as the Operating System
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Homework
Install Visual Studio 2022 on your computer

Search about FORTRAN, MATLAB, C#, Python, Java and C++ and
compare them to each other considering the concepts presented in this
session. (1-2 pages)
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Algorithms and Flowcharts


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Algorithms and Flowcharts


• Intelligence
Intelligence can be defined as a general
mental ability for reasoning, problem solving,
and learning. Because of its general nature,
intelligence integrates cognitive functions
such as perception, attention, memory,
language, or planning.

Is a computer intelligent ?
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Algorithms and Flowcharts


Function Shape
• Algorithms and flowcharts are two different
ways of presenting the process of solving a
problem. Terminal Box - Start / End

• Algorithms consist of steps for solving a Input / Output


particular problem

Process / Instruction
• In flowcharts, those steps are usually displayed
in shapes and process boxes with arrows.
Decision

Connector / Arrow
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Algorithms and Flowcharts


• Example 1: Print 1 to 20
Algorithm:

• Step 1: Initialize X as 0,
• Step 2: Increment X by 1,
• Step 3: Print X,
• Step 4: If X is less than 20 then go back to step 2.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Algorithms and Flowcharts


• Example 2: Calculate n!
Algorithm:

• Step 1: Input n
• Step 2: Initialize X as 1 and R as 1,
• Step 3: Increment X by 1,
• Step 4: R = R * X
• Step 5: If X is less than n+1 then go back to step 2.
• Step 6: Print R
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Algorithms and Flowcharts


• Example 3: Integrate a function f(x)
Algorithm:

• Step 1: Input x0 and xf and dx


• Step 2: Initialize S as 0 and x as x0,
• Step 3: calculate f(x),
• Step 4: S = S + f(x)* dx
• Step 5: x = x + dx
• Step 6: If x<xf go to Step 3
• Step 7: print S
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Algorithms and Flowcharts


• Exercise: Derivative of a function
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Algorithms and Flowcharts


• Algorithm and Flowchart of Writing a computer
program for engineering problems(Very general)

Algorithm:

• Step 1: Determine the problem definition clearly


• Step 2: Determine interfaces (inputs and outputs)
• Step 3: Determine the relationship between the inputs an outputs
• Step 4: Write/Correct your code
• Step 5: Test your code
• Step 6: If there is problem about the code go to step 4
• Step 7: If there is a problem about the logic go to step 3
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

First Project – Hello World


(Seems Boring!!!!)
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

First Project – Hello World! (Templates)

Metal workshop

Wood workshop Electronic workshop


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

First Project – Hello World! (Templates)


Desktop

Application
Types

Mobile Web
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

First Project – Hello World!


1- Open Visual Studio

2- Go to File / New / Project

3- Look to the ”Create New Project” 1st page Window more in deep

It is for selecting the template of the project

You can select Programming Language, Platform and Project Type

4- Select C# and find “Console App (.NET Framework)” then press “Next”

5- Select the name of your project and its location and press “Next”

6- In the last page press “Finish”


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

First Project – Hello World!


• In the right you can see Solution Explorer
• What is a Solution?
A solution is a container to organize
one or more related code projects, like a
class library project and a corresponding
test project.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

First Project – Hello World!


Open the directory you determined for the solution

Obj
HelloWorld.exe
Properties
Debug HelloWorld.pdb
Bin
HelloWorld Release
HelloWorld App.config

Helloworld.csproj
HelloWorld.sln
Program.cs
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

First Project – Hello World!


To write a text in the console, you can use the following command:

Console.WriteLine(text);
or
Console.Write (text);

The first form writes something and then goes to the next line while the second one just writes
the text without going to the next line

The text can be string, char, int, double, …


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

DataTypes
0 1 1 1 0 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1 0 0 1 1 0 1

0 0 1 1 0 1 1 0 1 0 0 1 1 0 1 0 1 1 1 1 1 0 0 1 1 0 1 0 1 0 0 0 1 0 0

Memory
Hardware – bits - 0 and 1
Software (Program)– Addresses
Data Can hold different values at
Constants do not change value different points in time.
over the lifetime of a program

Constant Variable

How much memory


DataType
Range of values
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types
Pre-defined Data Types
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types
Pre-defined Data Types
Commonly used data types related to the numbers
Type Description Range Size
Int Signed integer -2,147,483,648 to 2,147,483,647 4
Uint Unsigned integer 0 to 4,294,967,295 4
Float Floating point -3.4E38 to 3.4E38 4
Double Double precision floating point -1.8E308 to 1.8E308 8
Decimal Fixed precision number -7.9E28 to 7.9E28 16

Boolean and conditional statement


Type Description Range Size
Bool Boolean value True / False 1
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types
A decimal variable
contains a floating decimal (0-9) point type.
• The precision of the decimal number is higher than that of float and double,
• Much slower than float and double.
• In financial applications, mainly due to its high precision and to minimize rounding errors.

A float variable
• Contains a floating binary (0-1) point type.
• Use in graphics libraries mainly due to the high demand for processing power and where
preventing rounding errors is not very important

A double variable
• Contains a floating binary point (0-1) type but has double precision.
• It is the data type that is mainly used for real values, but it is not recommended in situations
in which we require high precision and accuracy
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types
Numerical and logical variables definition
In C#, every variable should be defined first then its value can be determined and then
operations can be done over the variable.

int a = -10;
uint b = 5;
float c = 103; or float c = 103.0f;
decimal d = 145; or decimal = 145.7m;
double e = 231.47; or 2.56E5;
bool f = true; or f = false;
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types
String and char variables
Character (char) is a predefined data type in C# but string is not. However, you can easily
define both types of variables in C#.

For defining a character use the following format. Notice that we are using single quotation
mark for character definition. The character should contain only one character.
Example: char c = ‘a’;

String is actually an array of characters. It can be defined as follows. Pay attention to double
quotation mark.
Example: string s = “My name is Yaser”;

You can read a string from the Console using following command:
string s = Console.ReadLine();
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types - Name of variables – in C#


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types
Name of variables – in C#
• It is recommended to use the first letter of variable name be in lowercase and if you are
attaching more words to variable name then start them with uppercase
camelCase bookTitle petName
• It is better that the name not be too short. For example if a variables relates to the
temperature we can use both of these names but temp is better
t VS temp

• It is better that the name be clear not vague. For previous example both of these names
can be assign but temp can stands for both temporal and temperature
temp vs Temperature

• The similar variables may be used so make the name as specific as possible.
roomTemp vs outTemp
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Main Example
Course Main Example: Receive Rocket Data
𝑑2 𝑥
𝑀𝑎𝑥 = 𝑀 2 = (𝑇 − 𝐷) cos 𝜃
𝑑𝑡
𝑑2 𝑦
𝑀𝑎𝑦 = 𝑀 2 = 𝑇 − 𝐷 sin 𝜃 − 𝑀𝑔
𝑑𝑡
𝑑𝑉𝑥
𝑎𝑥 =
𝑑𝑡
𝑑𝑉𝑦
𝑎𝑦 =
𝑑𝑡
𝑉𝑦
𝜃 = atan
𝑉𝑥
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Main Example
Course Main Example: Receive Rocket Data
𝑑2 𝑥 Input
𝑀𝑎𝑥 = 𝑀 2 = (𝑇 − 𝐷) cos 𝜃 Description Initial Value
𝑑𝑡 Parameter
𝑑2 𝑦 𝑀 Mass of the full rocket (Kg): 20
𝑀𝑎𝑦 = 𝑀 2 = 𝑇 − 𝐷 sin 𝜃 − 𝑀𝑔
𝑑𝑡 𝑀𝑝 Mass of the propellant (Kg): 10
𝑑𝑉𝑥
𝑎𝑥 = 𝑉0 Initial Velocity of the Rocket (m/s) 25
𝑑𝑡
𝑑𝑉𝑦 𝜃0 Initial flight path of the rocket (Deg) 45
𝑎𝑦 = 𝑇 Average thrust of the rocket (N) 400
𝑑𝑡
𝑉𝑦 𝐶𝐷 Drag Coefficient : 0.3
𝜃 = atan
𝑉𝑥 𝑡𝑏 Burn time (Seconds): 3
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types
Exercise:
Write a code that asks the user somethings about himself/herself and also about his/her pet
(like type, name, age and …) and then writes a sentence about the user.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Data Types
String operations
• Addition of two strings
• String s1 = “My Name is ”;
• String s2 = “Karl”;
• String s = s1 + s2;
• Access to substring and chars
• Char c1 = s1[4] Character M y N a m e i s
• String s3 = s1.Substring(6); index 0 1 2 3 4 5 6 7 8 9 10
• String s4 = s1.Insert(6, “here”);
• String s5 = s1.Remove();
• Information about string
• Int len = s1.Length();
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Homework
1- Write the following simple game:
1. Change the foreground and background color of the console.
2. Clear the console
3. Write a sentence (For example: “I love C# programming!!!”)
4. Wait for 5 seconds (You can use this command for waiting:
System.Threading.Thread.Sleep(5000); )
5. Ask the user to choose between four different integers (for example 2, 6, 8, 11). The selected
integer is the number of letter in the sentence that the user should remember. (For example
1 is I and 5 is v in the above sentence)
6. Ask the user to enter the selected letter.
7. Show the entered and true answers to the user

2- Use your own ideas and only the methods available in the Console and String to
make the game more attractive. You can even add your own rules to the game.

IMPORTANT: Use the correct naming method for variables


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Project-Based Homework
1- For the satellite simulation project, study about satellite orbits (planar) and its parameters
- semi-major axis (s)
- eccentricity (s)
- anomaly (𝜃).
Also study about the meaning and purpose of satellite simulation. Write a 2 pages report for
your studies.

2- In your report add the general algorithm for satellite simulation and draw the flowchart.

2- Start your term project by writing the code that receives these parameters from the user as
variables

3- Help user about the definition of each of these parameters


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept
Object-Oriented Programming is based on a concept called Object-Oriented thinking. So we
can look it as a Philosophy, a way that we can look to our world. Object-Oriented thinking is
defined as:
Way of thinking where we consider each component of a problem in
terms of object.
What is the meaning of an object?
Look your around :
- Cars - Animals
- Buildings - Factories
- Cell Phone - Stores
- Trees - Table
- Humans - Clothes
How do we discriminate between them?
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept

Behavior Object Data

• Fuel to Air ratio


• Gear ratio for different settings
• Fuel pump pressure
• Wheel Diameter
• Maximum engine temperature
• ….
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept

Behavior Object Data

• Model gas pedal


Pressing
• Pressing Break Pedal
Manufacturer
• Changing the gear
Color
• Steering
Automatic/Manual
• Lighting of
Number thepassengers
lamps on/off
• Opening/Closing
Number of Airbags
the door
• …
0-100 Km/h time
• …
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept

Example: What are you checking when you want to buy a television
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept

Example: How is your teacher assessing you?


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept
In programming we are using objects to separate unnecessary parts.

Setting the value Contains

Insert String Object Replace

Remove - String value Reverse


- Length
Substring ToLower
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept
• The behavior of an object is what the object can do.
• In OO programming terminology these behaviors are contained in methods
• You invoke a method by sending a message to it

Data or
Behavior Object
Attributes

• Represents the state of the object


• The attributes contain the information that differentiates between the
various objects
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept
Exersice:
Assess the Console object in Visual Studio and write some of its Attributes and Methods

For seeing some behaviors and attributes of Console object it is enough to write Console in
Visual Studio IDE and put a dot (.) after. You will see a list of behaviors and attributes.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Object Concept
Example:
Console.WriteLine("Window height is: ");
Console.WriteLine(Console.WindowHeight);
Console.WindowHeight = 20;
Console.ReadLine();
Console.Clear();
string s1 = "Enter your name: ";
Console.Write(s1);
string p1 = Console.ReadLine();
Console.WriteLine("Your Name is :" + p1);
Console.ReadLine();
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Before continuing
Comments
Writing comments is a very important part in developing a code

When you are defining variables, using conditional statements and in


general, developing every part of your code it is highly recommended
make good comments to make your code clear, understandable and
followable.

In this course writing comments in your codes is an important part of


your job affecting your score.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Arrays
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Arrays
Arrays
One dimensional int array definition (first method)
int[] intArr = new int[4]; // Creates 4 dimensional integer array
intArr[0] = -1; intArr[1] = 3; intArr[2] = 12; intArr[3] = 7;

One dimensional int array definition (second method)


int[] intArr = new int[]{-1, 3, 12, 7};
Exercise 1: Use the same approach to define an array of doubles

Exercise 2: Use the same approach to define an array of Booleans

Exercise 3: Check some of the methods that can be applied to an integer array
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Arrays
Arrays
Two dimensional int array definition (first method)
int[,] intArr = new int[2,2]; // Creates 2*2 dimensional integer array
intArr[0,0] = -1; intArr[0,1] = 3;
intArr[1,0] = 12; intArr[1,1] = 7;
One dimensional int array definition (second method)
int[] intArr = new int[]{{-1, 3}, {12, 7}};
Exercise 1: Use the same approach to define an array of doubles
Exercise 2: Compare the length properties of one dimensional array with two
dimensional array. Check the GetLength method of the int array variable.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Arrays
Exercise
• Define two 3 dimensional vectors as arrays

• Calculate the dot product of two vectors

• Calculate the angle between two vectors


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Conditions and Loops


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Conditional Statements
If statement:
if (condition1)
{
if condition1 is true: Do this part
}
else
{
if condition1 is false : Do this part
}

Variables scope – if a parameter defined in blocks of if, it is accessible only in that block
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Conditional Statements
If statement:
if (condition1)
{
if condition1 is true: Do this part
}
else if (condition2)
{
if condition1 is false and condition 2 is true: Do this part
}
else
{
if condition1 and condition 2 are false : Do this part
}
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Conditional Statements
If statement:
C# supports the usual logical conditions from mathematics:
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Conditional Statements
Switch statement:
Switch (expression)
{
case x:
// Code block Variables scope – if a parameter defined in blocks of
break; switch, it is accessible only in that block
case y:
// Code block
break;
case z:
// Code block
break;
default:
// Code block
break;
}
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Loops
For statement:
for (loop variable initialization ; testing condition; increment / decrement)
{
// statements to be executed
}
Example: for (int i=100; i>=0; i--)
{
Console.Writeline(“Counter : ” + i);
}
Example: double X = 0;
double dx = 0.1;
Variables scope – if a parameter defined in the
for (int k=0; k<=1000; k++) block of For loop, it is accessible only in that
{ block
X = X + 3 * X * X * dx;
}
Console.Writeline(“Result is: ” + X);
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Loops
Exercise
• Define two vectors as arrays

• Calculate the dot product of two vectors

• Calculate the angle between two vectors


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Loops
While statement:
while (boolean condition) do
{ {
loop statements... statements..
} }while (condition);

Exercise
Read a special character from the Console
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical operations
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Basic Operations
Increment and Decrement operators

increment operator: ++ Decrement operator --


int i = 3; int i = 3;
Console.WriteLine(i); // output: 3 Console.WriteLine(i); // output: 3
Postfix
Console.WriteLine(i++); // output: 3 Console.WriteLine(i--); // output: 3
Console.WriteLine(i); // output: 4 Console.WriteLine(i); // output: 2
double a = 1.5; double a = 1.5;
Console.WriteLine(a); // output: 1.5 Console.WriteLine(a); // output: 1.5
Prefix
Console.WriteLine(++a); // output: 2.5 Console.WriteLine(--a); // output: 0.5
Console.WriteLine(a); // output: 2.5 Console.WriteLine(a); // output: 0.5
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Basic Operations
Other basic operators
Operation Operator Operation Operator
Summation + Subtraction -
Multiplication * Division /
Remainder % Compound assignment X op= Y
int a = 5;
X op= Y example:
a += 9; Console.WriteLine(a); // output: 14
a -= 4; Console.WriteLine(a); // output: 10
a *= 2; Console.WriteLine(a); // output: 20
a /= 4; Console.WriteLine(a); // output: 5
a %= 3; Console.WriteLine(a); // output: 2
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Basic Operations
Other basic operators Be careful about the type of numbers
In division operation:

Console.WriteLine(13 / 5); // output: 2


Console.WriteLine(13 / 5.0); // output: 2.6

If one of the operands is decimal another operand can be neither float nor double
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Basic Operations Be careful about the type of numbers
Other basic operators
In remainder operation:

It is generally expected to find the remainder of division of two Integers.


Console.WriteLine(5 % 4); // output: 1
However, for double and float numbers the remainder operation returns a value.

For the float and double operands, the result of z=x % y for the finite x and y is the
value z such that
• The sign of z, if non-zero, is the same as the sign of x.
• The absolute value of z is the value produced by |x| - n * |y| where n is the largest possible
integer that is less than or equal to |x| / |y| .
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Precedence from the highest to the lowest
Postfix increment Prefix increment Multiplicative operators Additive operators
(x++ , x-- ) (++x , - -x ) (*, /, and % ) (+ and -)

1 2 3 4

Binary arithmetic operators are left-associative. That is, operators with the
same precedence level are evaluated from left to right.

Console.WriteLine(2 + 2 * 2); // output: 6 Console.WriteLine(9 / 5 / 2); // output: 0


Console.WriteLine((2 + 2) * 2); // output: 8 Console.WriteLine(9 / (5 / 2)); // output: 4
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Logical and Conditional Operations
NOT Operator: ! bool passed = false;
Console.WriteLine(!passed); // output: True
Console.WriteLine(!true); // output: False

Console.WriteLine(false & true); // Output: False Logical AND


Console.WriteLine(true & true); // Output: True Operator: &
Conditional AND
Console.WriteLine(false & false); // Output: False
Console.WriteLine(true & false); // Output: False

Logical OR Console.WriteLine(false| true); // Output: True


Operator: |
Conditional OR Console.WriteLine(true | true); // Output: True
Console.WriteLine(true | false); // Output: True
Console.WriteLine(false | false); // Output: False
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Logical and Conditional Operations
Exclusive OR Operator: ^ Console.WriteLine(false & true); // Output: True
Console.WriteLine(true & true); // Output: False
Console.WriteLine(false & false); // Output: False
Console.WriteLine(true & false); // Output: True
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Math Operations
There is library “Math” in C# that includes many mathematical functions

Sqrt Ceiling Sin Sinh Max E


Pow IEEERemainder Cos Cosh Min PI
Abs Floor Tan Tanh Maxmagnitude Tau
Exp Round SinCos Acosh Minmagnitude
Log Truncate Acos Asinh
Log10 Asin Atanh
Log2 Atan
Sign Atan2
Cbrt
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Class Exercise
Euler equation:
𝑓 𝑥 + ∆𝑥 = 𝑓 𝑥 + 𝑓′(𝑥)∆𝑥
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Class Exercise
Write a program that uses Euler integration method to calculate this
expression:
𝜋
𝑦 = න 𝑥sin(2𝑥)𝑑𝑥
0
Compare with the analytical result
𝑥 cos 2𝑥 sin 2𝑥
𝑦=− +
2 4
Calculate the following integral using Newton Integration Method
1
𝑒 −sin 𝑥
න 3 𝑑𝑥
𝑥 + cos(𝑥)
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Creating Random Numbers in C#
To create random numbers you can use Random Object.
Random rand = new Random();
Console.WriteLine(rand.Next());
Console.WriteLine(rand.NextDouble());

• You should know that there is no real random number in computer


programming.
• The Random object uses a sequence function called pseudo-random with a
very complicated behavior such that the numbers seems to be random
• You can use seed to determine where the sequence should be started from
Random rand = new Random(seed);
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Mathematical Operations
Creating Random Numbers in C#
To create random numbers you can use Random Object.
Random rand = new Random();
Console.WriteLine(rand.Next());
Console.WriteLine(rand.NextDouble());

• You should know that there is no real


random number generated by the computers.
• The Random object uses a sequence
function called pseudo-random with a very
complicated behavior such that the numbers
seems to be random
• You can use seed to determine where the
sequence should be started from Random rand = new Random(seed);
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Homework – Typing Game


1- Write the following game (Basic Game):
1. Choose a character between {a,s,d,f} or {j,k,l}
2. Show the character to the user in console
3. The user should type the shown character
4. The response time of the user should be measured
5. If it is bigger than 1 second repeat the game from the start
6. Else increase the user score and go to 1
7. If the score passed a level write a message of success to the user
8. For measuring the response time use DateTime object
9. The score should be shown always to the user
2- Use your ideas and the contents presented in this course to improve the
game (Improved Game) and make it more interesting (For example add
scoring system, Adapt the desired response time with typing skill, ….)
Note: Deliver both basic game and your own improved game.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Debugging techniques
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Debugging Techniques
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Debugging Techniques

Bugs

After-Run Bugs Programming Bugs

Input Errors

Logic/Formulation Errors

Implementation Errors
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Debugging Techniques
• Watch Windows
• The Watch Window allows you to see value of variables and
expressions while debugging
• Up to 4 Watch Windows can be opened
• You can access the Watch Windows through Debug/Windows/Watch
• To add items to watch do any of the following:
• Write them manually in a new row of the Watch window
• Right-click on a variable choose “Add Watch” in the context menu
• Right-click on a variable in the DataTip and choose “Add Watch”
• “Add Watch” button from QuickWatch
• Although you can see the variables value in DataTip of variable but if
you want to see some variables simultaneously you have to use
Watch Window
• Local Window
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Debugging Techniques
Breakpoint
Breakpoints are one of the most important debugging tools in your
developer's toolbox.
You can set breakpoints before debugging and even while debugging
To set a breakpoint
• Click in the far left margin next to a line of code
• Select the line and press F9
• Select Debug > Toggle Breakpoint
• Right-click and select Breakpoint > Insert breakpoint.
The breakpoint appears as a red dot in the left margin.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Debugging Techniques
• Line by Line Running
• During the debugging process you can go line by line both forward and
backward
• Step over (F10) – It runs just one line and goes forward. If the current line
calls a method, this action assumes the call as a line so it runs the whole
method without going inside the method
• Step into (F11) – It runs just one line and goes forward. If the current line calls
a method, this action going inside the method and let you to debug the inside
of method
• Step Backward (Alt+]) – It runs backward to the previous line.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Debugging Techniques
Breakpoint - Conditional
You can control when and where a breakpoint executes by setting
conditions.
To set a breakpoint condition:
1. Right-click the breakpoint symbol and select Conditions
2. hover over the breakpoint symbol, select the Settings icon, and then select Conditions in
the Breakpoint Settings window.
Breakpoint Management
You can use the Breakpoints window to see and manage all the breakpoints
in your solution.
• Debug > Windows > Breakpoints,
• Or press Ctrl+Alt+B.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Debugging Techniques
• Class Exercise
• Write a code to calculate the following integral
1 1
න න 𝑥 2 − 3𝑦 2 + 𝑥𝑦 3 𝑑𝑥𝑑𝑦
0 0

• Use the tools described here to debug the code


• Analytical solution (just for checking)

1 1 𝑥=1 𝑦=1 13
3 3 2 4
𝑥 𝑦−𝑦 𝑥+ 𝑥 𝑦 =− ≈ −0.5417
3 8 𝑥=0 𝑦=0 24
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Main Example
Course Main Example: Solve the equations of motion
𝑑2 𝑥
𝑀𝑎𝑥 = 𝑀 2 = (𝑇 − 𝐷) cos 𝜃
𝑑𝑡
𝑑2 𝑦
𝑀𝑎𝑦 = 𝑀 2 = 𝑇 − 𝐷 sin 𝜃 − 𝑀𝑔
𝑑𝑡
𝑑𝑉𝑥
𝑎𝑥 =
𝑑𝑡
𝑑𝑉𝑦
𝑎𝑦 =
𝑑𝑡
𝑉𝑦
𝜃 = atan
𝑉𝑥
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Main Example
Course Main Example: Receive Rocket Data
𝑑2 𝑥 Input
𝑀𝑎𝑥 = 𝑀 2 = (𝑇 − 𝐷) cos 𝜃 Description Initial Value
𝑑𝑡 Parameter
𝑑2 𝑦 𝑀 Mass of the full rocket (Kg): 20
𝑀𝑎𝑦 = 𝑀 2 = 𝑇 − 𝐷 sin 𝜃 − 𝑀𝑔
𝑑𝑡 𝑀𝑝 Mass of the propellant (Kg): 10
𝑑𝑉𝑥
𝑎𝑥 = 𝑉0 Initial Velocity of the Rocket (m/s) 25
𝑑𝑡
𝑑𝑉𝑦 𝜃0 Initial flight path of the rocket (Deg) 45
𝑎𝑦 = 𝑇 Average thrust of the rocket (N) 400
𝑑𝑡
𝑉𝑦 𝐶𝐷 Drag Coefficient : 0.3
𝜃 = atan
𝑉𝑥 𝑡𝑏 Burn time (Seconds): 3
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Today’s Outline
• Debugging techniques
• Exception handling in C#
• Methods
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Exception Handling
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Exception Handling
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Exception Handling
• Understanding and using exceptions is crucial to creating readable code that
responds correctly to errors at runtime.

• What is an Exception?

Exceptions
An exception is a problem that arises
during the execution of a program.
Interactions
Example exception:
• Division by Zero Executions
• Conversion Exception
• File Not Found Exception
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Exception Handling
C# exception handling is built upon four keywords:
• try − A try block identifies a block of code for which particular exceptions is
activated. It is followed by one or more catch blocks.
• catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem. The catch
keyword indicates the catching of an exception.
• finally − The finally block is used to execute a given set of statements,
whether an exception is thrown or not thrown. For example, if you open a
file, it must be closed whether an exception is raised or not.
• throw − A program throws an exception when a problem shows up. This is
done using a throw keyword.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Exception Handling
try {
// statements causing exception
} catch( ExceptionName e1 ) {
// error handling code
} catch( ExceptionName e2 ) {
// error handling code
} catch( ExceptionName eN ) {
// error handling code
} finally {
// statements to be executed
}
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Debugging Techniques
• Class Exercise
• In the double integration exercise, ask user to enter the range of x and y for
calculation of
𝑦𝑓 𝑥𝑓
න න 𝑥 2 − 3𝑦 2 + 𝑥𝑦 3 𝑑𝑥𝑑𝑦
𝑦0 𝑥0
• Write the code such that when the user enters a wrong value asks him to
retry
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods
• A method is a code block that contains a series of statements.

• You can pass data, known as parameters, into a method.

• Methods are used to perform certain actions, and they are also known
as functions.

Why use methods?

• To reuse code:
• define the code once, and use it many times.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods

Variables

Method

Interface
Interface Local Variables
Inputs Outputs
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods – Method Signatures


Basic Data Types
Access Level User Defined Data Types
1 Modifier (Optional) Objects
2 Return Value
Private
abstract 3 Method Name
Public
4 Parameters
protected static
Basic Data Types 5
internal sealed
User Defined Data Types

Objects
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods – Method Signatures


Example 1 – Parameter and argument
private double Add_Numbers(double A, double B)

Example 2 – Non-predefined data type parameters


private double[] Add_Vectors(double[] A, double[] B)
Example 3 – void
private void Show_Person(string namePerson, int agePerson)
Example 4 – Parameters with default values
private double Add_Numbers(double A = 0, double B = 0)
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods – Method Signatures


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods – Pass by ? Therefore, changes to the


argument have no effect on the
original instance in the calling
Passing by value method.

By default, when an instance of a value type is passed to a method, its copy is


passed instead of the instance itself.

Passing by reference To pass a value-type instance by reference, use the ref keyword

When an object of a reference type is passed to a method, a reference to the object is passed.
That is, the method receives not the object itself but an argument that indicates the location of
the object.
If you change a member of the object by using this reference, the change is reflected
in the argument in the calling method, even if you pass the object by value.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods – Method Signatures


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods – Expression body definition


Expression body definitions

It is common to have method definitions that simply return immediately with the
result of an expression, or that have a single statement as the body of the method..

There is a syntax shortcut for defining such methods using =>.

Example:
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods – Comments
Using // you can put ordinary comments in your method to make it reusable for
future works.

Using /* and */ you can convert some lines of the code to the comment.

Using /// before the start of the method you can put some comments about the
method, its arguments and return value. These comments will be shown to the user
of the method as a tipbox when he is using the method
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Enumeration
Enums
In C#, an enum (or enumeration type) is used to assign constant names to a
group of numeric integer values.
Example: enum WeekDays
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

You can assign different values to enum member.


enum Categories
{
Electronics = 1, Food = 5, Automotive = 6,
Arts = 10, BeautyCare = 11, Fashion = 15, WomanFashion = 15
}
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods –Overloading
Method Overloading
With method overloading, multiple methods can have the same name with different
arguments number/type/sequence.

Two
numbers Two
Vectors
Add

Two
Matrices
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods –Overloading
Method Overloading

Exercise
Define two enums for doors and windows of the car (FrontLeft, FrontRight,
RearLeft, RearRight)

Use method overloading to define Open and Close methods for doors and windows.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods –Delegating (Optional)


Method Delegating
What if we want to pass a function as a parameter?
The C# handles the callback functions or event handler using delegates.

The delegate is a reference type data type


that defines the method signature

You can define variables of delegate, just like


other data type
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods –Delegating (Optional)


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods –Delegating (Optional)


Method Delegating

There are three steps involved while working with delegates:


1.Declare a delegate
2.Set a target method
3.Invoke a delegate

Syntax:
[access modifier] delegate [return type] [delegate name]([parameters])
Example:
public delegate double Function2D(double x, double y);
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods –Delegating (Optional)


Method Delegating
1.Declare a delegate
2.Set a target method
3.Invoke a delegate
Example:
Function2D del = new Function2D(Function1);
static double Function1(double a, double b)
{
return a*a + b*b;
}
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Methods –Delegating (Optional)


Method Delegating
1.Declare a delegate
2.Set a target method
3.Invoke a delegate

public delegate double Function2D(double x, double y);


Example: Function2D del = new Function2D(Function1);
del.Invoke(5.0,3.0);
static double Function1(double a, double b)
{
return a*a + b*b;
}
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Homework – Matrix Calculation


1. Write the following code:
a) Ask the user which operation does he want to do (Addition, Subtraction,
Multiplication, Transpose, Determinant calculation and Eigenvalues calculation)
b) The code should then receive required matrices from the user
I. First ask the number of rows (and if necessary columns) of each matrix
II. Then get the elements of each matrix one by one
c) Perform the operation and show the result
d) After each operation the code should go to line (a) again
2. In case of any error the program should show a message about the reason
of the problem and then continues its operation
3. Use comments and proper naming
4. Use methods efficiently
5. For Determinant calculation and Eigenvalues calculation just use 2*2
matrices (bigger matrices are not required)
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Project-Based Homework Y
D
Use the following equations to simulate the dynamics of a planar
y
satellite
𝑑𝑥 𝑑𝑦 𝑑𝑉𝑥 𝑑𝑉𝑦 V
= 𝑉𝑥 = 𝑉𝑦 = 𝑎𝑥 = 𝑎𝑦 W
𝑑𝑡 𝑑𝑡 𝑑𝑡 𝑑𝑡
Where x and y are related to the position of the satellite and 𝑉𝑥
and 𝑉𝑦 are velocity components and 𝑎𝑥 and 𝑎𝑦 are acceleration Earth
x X
terms
1 1
𝑎𝑥 = σ 𝐹𝑥 𝑎𝑦 = σ 𝐹𝑦
𝑚 𝑚
σ 𝐹𝑥 and σ 𝐹𝑦 are the summation of forces acting on satellite on x and y directions. Assume only gravity and
aerodynamic forces are available and assume constant gravity with 𝑔 = 9.8 and 𝑚 = 50𝐾𝑔, 𝐶𝐷 = 0.3, 𝜌 =
10−7 , 𝑆 = 0.4𝑚2 and use the following equation to calculate the aerodynamic force:
1
𝐷 = 𝜌𝑉 2 𝑆𝐶𝐷 and 𝑉= 𝑉𝑥2 + 𝑉𝑦2
2
Hints:
• Gravity is towards the center f earth
• Drag is in the opposite direction f the velocity
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

File Handling
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

File Handling - Streams


Streams
A stream is a wrapper or an abstract class that provides the required methods
to read, write, and perform other relevant operations with bytes.
Different types of Streams available in C#:
• File Stream - helps in reading/writing content from/to a file (any format).
• Memory Stream - helps in reading/writing content from/to memory.
• Buffered Stream - helps in reading/writing content from another Stream.
• Network Stream - helps in reading/writing content from/to network socket.
• Pipe Stream - helps in reading/writing content from/to the pipes.
• Crypto Stream - helps in linking data streams with cryptographic transformations
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

File Handling - Streams


File Streams
A File Stream takes up data from the file and stores/processes it in the form
of a byte.

Bytes – [1 0 0 1 1 0 0 1]

The question is, how do we humans understand it?

characters bytes
human Machin
understandable understandable
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

File Handling - Streams


File Streams

• Generate a file stream


1 • FileStream fs = new FileStream(FileName, FileMode, FileAccess, FileShare)

• Generate a stream reader/writer


2 • StreamReader sr = new StreamReader(fs), StreamWriter sw = new StreamWriter(fs)

• Read/Write to the stream reader/writer


3 • sr.Read(), sr.ReadLine() or sw.write(TEXT), sw.writeline(TEXT)

• Close stream reader/writer (sr.close(), sw.close())


4 • Close Filestream (fs.close())
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

File Handling - Streams


A constant that determines how to open or create the file.
Methods CreateNew, Create, Open, OpenOrCreate, Append

FileStream fs = new FileStream(FileName, FileMode, FileAccess, FileShare)

StreamWriter sw = new StreamWriter(FileStream Name) A constant that determines how


the file can be accessed by the
StreamReader sr = new StreamReader(FileStream Name) FileStream object.
Read, Write, ReadWrite

String s = sr.Read() String s = sr.ReadLine()


sw.Write(string Text) sw.Write(string Text)

sr.close() sw.close()
fs.close()
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

File Handling - Streams


Class Exercise

Make a 3*3 matrix of double numbers call it A.


Write a code that creates a file with the name “Data.dat”
Write in the first line of the matrix: “The matrix is:”
Write the members of first row of the matrix in the next line of the file
Write the members of second row of the matrix in the next line of the file
Write the members of third of the matrix in the next line of the file

Read the file and store the result in another matrix B


Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Homework – Matrix Calculation


1. Write the following code:
a) Ask the user which operation does he want to do (Addition, Subtraction,
Multiplication, Transpose, Determinant calculation, Eigenvalues calculation)
b) The code should then receive required matrices from the user
I. First ask the number of rows (and if necessary columns) of each matrix
II. Then get the elements of each matrix one by one
c) Perform the operation and show the result
d) After each operation the code should go to line (a) again
2. In case of any error the program should show a message about the reason
of the problem and then continues its operation
3. Use comments and proper naming
4. Use methods efficiently
5. For Determinant calculation and Eigenvalues calculation just use 2*2
matrices (bigger matrices are not required)
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Project-based Homework
𝑑𝑥 𝑑𝑦 𝑑𝑉𝑥 𝑑𝑉𝑦
• Calculate the derivative ( , , , ) in a separate method
𝑑𝑡 𝑑𝑡 𝑑𝑡 𝑑𝑡
• Add methods to your code for calculation of gravity constant (g) and drag
coefficient
• Assume drag coefficient and gravity as constant values.
• Use comment for the method
• Use method overloading and define anther method for calculation of gravity
constant (g) which uses the following equation
𝑅 2
𝑔 = 𝑔0
𝑅+ℎ
Where, 𝑔0 = 9.81 R is the radius of the earth and 𝑅 + ℎ is the distance f
satellite from the earth center.
• Add the option of write/read the data of the satellite (that you entered in the
console) in/from a file.
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Example Problem
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Example Problem
Double Mass-Spring-Damper Dynamics
Consider a system containing two masses m and M that are connected by a spring with
stiffness K and a damper with damping of c. The system is initially at rest. At t=0 a force
𝐹 𝑡 = 𝐹0 . exp(𝑝. 𝑡) ∗ sin 𝜔. 𝑡 is applied to the system. Simulate the dynamic behaviour
of the system. (Test case: K=10, c=0.2, M=1, m = 0.5, p=0.3, 𝐹0 = 0.1 and 𝜔 = 2)

𝑚 M F(t)
c

y
𝑦2
𝑦1
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Example Problem
Double Mass-Spring-Damper Dynamics
Modeling
K(𝑦1 − 𝑦2 ) K(𝑦1 − 𝑦2 )
𝑚 M F(t)
c(𝑦ሶ 1 − 𝑦ሶ 2 ) c(𝑦ሶ 1 − 𝑦ሶ 2 )

K 𝑦1 − 𝑦2 + c 𝑦ሶ1 − 𝑦ሶ 2 = 𝑚𝑦ሷ 2 F(t) − K 𝑦1 − 𝑦2 − c 𝑦ሶ1 − 𝑦ሶ 2 = 𝑀𝑦ሷ 1


If we define 𝑋Ԧ = [𝑥1 , 𝑥2 , 𝑥3 , 𝑥4 ] such that 𝑥1 = 𝑦1 , 𝑥2 = 𝑦2 , 𝑥3 = 𝑦ሶ 1 , 𝑥4 = 𝑦ሶ 2
𝑥ሶ 1 = 𝑥3 1 1
𝑥ሶ 3 = F(t) − K 𝑦1 − 𝑦2 − c 𝑦ሶ 1 − 𝑦ሶ 2 = F(t) − K 𝑥1 − 𝑥2 − c 𝑥3 − 𝑥4
𝑀 𝑀

1 1
𝑥ሶ 2 = 𝑥4 𝑥ሶ 4 = K 𝑦1 − 𝑦2 + c 𝑦ሶ 1 − 𝑦ሶ 2 = K 𝑥1 − 𝑥2 + c 𝑥3 − 𝑥4
𝑚 𝑚
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Example Problem
Double Mass-Spring-Damper Dynamics
Modeling
𝑋Ԧ = [𝑥1 , 𝑥2 , 𝑥3 , 𝑥4 ]
𝑥ሶ 1 = 𝑥3

𝑥ሶ 2 = 𝑥4
1
𝑥ሶ 3 = F(t) − K 𝑥1 − 𝑥2 − c 𝑥3 − 𝑥4
𝑀
1
𝑥ሶ 4 = K 𝑥1 − 𝑥2 + c 𝑥3 − 𝑥4
𝑚
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Example Problem
Double Mass-Spring-Damper Dynamics
Solution Approach – Numerical Integration
Euler Method
ሶ Ԧ
𝑋Ԧ 𝑡 + ∆𝑡 = 𝑋Ԧ 𝑡 + 𝑋Ԧ (𝑋, 𝑡)∆𝑡
Standard 4th order Runge-Kutta Method
∆𝑡
𝑋 𝑡 + ∆𝑡 = 𝑋 𝑡 + (𝐾1 + 2𝐾2 + 2𝐾3 + 𝐾4 )
6
ሶ 1 ∆𝑡
ሶ K 3 = 𝑋 (𝑋 + 𝐾2 ∆𝑡, 𝑡 + )
K1 = 𝑋 (𝑋, 𝑡) 2 2
ሶ 1 ∆𝑡 ሶ (𝑋 + 𝐾 ∆𝑡, 𝑡 + ∆𝑡)
K 2 = 𝑋 (𝑋 + 𝐾1 ∆𝑡, 𝑡 + ) K 4 = 𝑋 3
2 2
Advanced Programming (AERO 108 / ME 108) Seyed Yaser Nabavi

Homework
Solve the Mass-Spring-Damper Problem for three objects

K1 K2

𝑀1 M2 M3 F(t)
c1 c2

y
𝑦3
𝑦2

𝑦1

You might also like