[C#] QUT - IFN 555 Lecture Note :
QUT IFN555 Leucure Note :
IFN555 수업 노트
IFN563 Object Oriented Design 수업을 듣는데 너무 어려워서 처음부터 다시 복습하려고 작년에 들은 IFN555복습 및 lecture note. Blackboard에는 tutorial video 는없고 lecture 만 남아잇다.
IFN555 : C# review
Week 1 : A first C# program
Week 2 : Using Data
Week 3 : Making Decisions
Week 4 : Using Looping Structures
Week 5 : Using Arrays
Lecrture 1
WHat is the programming process :
Designing instruction to tell the computer what to do
Software : 1. Systsem software : OS
2. Application software: allow the user to do what they want
Hardware : Physical device -
Machine language - expressed by 0 and 1 ;
High-level programming language (C#, python , Java ... ): use a reasonable key word like "read" ,"write" and "add"
Allow user to locate the memory
Each high-level language has its own syntax
Use correct programming logic -
compiler translates high-level language to machine language
Procedural and Object-Oriented programming :
Procedural (component-oriented) programming: creates and names computer memory locations that can hold values (varibles) that are referenced by using a one-word name
Write a sereis of steps of operations - lot variables - lots steps
Procdeures or Methodes : grouping variables methodes
Object-oriented programming (OOP) : etensio nof procedural programming ; focues on objects that contatins the variables
Objects : ex) bank account ;
property (attributes) : represent its characterisitcs
behavior (methode) : things the object does
Joyce Farrell :
Calss : Category of thing
class Name: Videoo
Attribute : title , running time
Methoude : create(), play()
Common features :
inheritance : it inehrit all the property of its parents
encapsulation : ability to contain all the attributes and methods in one package
polymorphism : ability of different objects work properly based on its data type
inheritance : it inehrit all the property of its parents
Writing a C# progarm that produces output :
Literal String : ""
Argument : inside parenthesis (bracket)
Methoudes :
Namespace : group similar classes , inside of Namesapce lots of classes
Methode header: static void
Methode body : between {}
whitespace : combinations of space / tab => organize code
Keyword : such as void
Methode name is Main() ; application calsses
if they dont have main() then its non-application class
void : return type
Selecting Identifiers :
how to select identifiers in C#
identifiers are names for program components - class , namespaces , variables , objects, methods es,
classes,methods, and namespaces start with uppercase letter :
no space betwwen whitespace , only letters, digits , @ ,
no cant be C# reserved , and importand words like such , delete ... etc
public class Gretting
pubulic class DisplayBusinessPlan
variables, obects, and keywrods start with lowercasee (using camel case):
totalScore = firsthalfScore + secondHalgScores;
Comments and using the system Namespaces:
program comments :
line comments : //
block comments : /* */
using system namespace : using System.console => WriteLine("blach blach");
Compiling and Executing a C# program :
compile the program : converting your code into machine language
you can compile either CLI or IDE ;
CLI : csc blach.cs
if you get OS erroer message => check missepll, location of the file ,
if you get programming languege erroer msg = > your syntax has erroer writeLine => WriteLine => case sensitive
Lectuer 2
Lecture2 Using Data
2.1 Decalre Variables
if data item is constant , you can not change the variable
data type : int , double, decimal, char, string ,and bool
ex) int myAge = 29;
variable name is myAge
datat type is int
initial value is 29
initalized the valued with 29
initalize : int myAge = 25;
assigns : myAge = 50;
declare variable without initialization :
int myAge;
but you can only use it once you assign the value in it
Lecture 2
Lecture2 Using Data
2.1 Declare Variables
if data item is constant , you can not change the variable
data type : int , double, decimal, char, string ,and bool
ex) int myAge = 29;
variable name is myAge
datat type is int
initial value is 29
initalized the valued with 29
initalize : int myAge = 25;
assigns : myAge = 50;
declare variable without initialization :
int myAge;
but you can only use it once you assign the value in it
2.2 Display Variables values
double variableName = 6.18;
System.Console.WrtieLine(variaeName);
Display values :
WriteLine("My age is {0} years old ", myAge);
Vaiable Alignment ;
WriteLine("{0, -8}{1, 8}", "Richard","Lee")
WriteLine("{0, -8}{1, 8}", "Skyler","Bang")
WriteLine("{0, -8}{1, 8}", "Ed","JanmeRU")
int myAge = 20;
WriteLine("My age is {0} years old ", myAge);
2.3 Use integral data type
Store the whole numbers
you can only put _ not ,
2.4 Use floating-point data types
contains decimal positions
-flaot , up to 7 digit
-double , up to 15, or 16 ; most of time you use this
-decimal , 28 or 29
put F => float
put D => double
put M => decimal
put E => exponent
put C => currency?
fotmatting floating-point values :
double num = 123;
string numString;
numString = num.ToString("F2");
WriteLine(numString); /// 123.000;
string numString2;
numString2 = num.ToString("F3");
WriteLine(numString2);
double num = 123;
string numString;
numString = num.ToString("F2");
WriteLine(numString); /// 123.00;
string numString2;
numString2 = num.ToString("F3");
WriteLine(numString2); /// 123.000
double money = 123123;
string conversion;
conversion = money.ToString("c");
WriteLine(conversion); /// currency format $123,123.00
2.5 Use arithmetic opertors
arithmetic operators : addition , subtraction , multiplicatoin , divisoin , and reamainder ;
Shortcut arithmetic :
a += a * b
a = old a * b ;
-= , *= ,
increment :
someValue++ (prefix), someValue++ postfix: somaValue = someValue + 1 ;
Decrement :
somveValue-- , --someValue
prefix : ++a : value of a chagnes
postfix : a++ : dosent change
2.6 Use the bool data type
True or False ;
Comparison :
comapres == (* = is just assigne)
!=
2.7 Describe numeric type conversion
x is int
y is double
z = x+y is implicitly converted and become double;
double x = 5.73
int x => become 5
2.8 use the char data type
Char data type : you cant use in arithmetic statement
char letter = 'A'; or char letter = '\u0041'
2.9 use the string data type
string : holds a series of characters ;
can compare == and != ;
equal(), Comapre()and ComapareTo()
Substring():
string word = "word"
word.Substring(0,1) is "w";
word.Substring(0,2) is "wo";
word.Substring(0, word.Length) is "word";
2.10 Define named constants
constants, such as pi
2.11 Accept console input
Convert Class :
userInput = ReadLine()
userInputPrice = Convert.ToDouble(UserInput)
Parse() Methode :
userInputPrice = double.Parse(UserInput)
userInputPrice = double.Parse(ReadLine)
score = int.Parse(ReadLine)
string name1 = "sky";
string name2 = "sky";
string name3 = "scar";
WriteLine(" compare {0} to {1} : {2}", name1, name2, name1 == name2);
WriteLine(" compare {0} to {1} : {2}", name1, name3, name2 == name3);
Lecture 3
3.1 Understand logic- planning tools and decision making
3 ways of logic- planning
Pseudocode : with plain English statement to plan the logic
Flowchart : each step with arrow indicates the different types of instructions
Sequence structure : step by step
Decision structure : program progress by the result of the choice ?
its like one way or mulitple routre to the end of the goal
3.2 Make decisions using if statments
if statement : used to make a signle -alternative decision
if(condition)
{what to do }
Nested if : decision strucutres contained within antoehr.
* if an outer level if is false then inside if will be ignored.
WriteLine(" Please input one number : ");
int inputNum = int.Parse(ReadLine());
int low = 2;
int high = 7;
//WriteLine(" Your input is : {0} ", inputNum);
if (inputNum > low)
{
if(inputNum < high)
{
WriteLine(" Your numer {0} is between {1} and {2}", inputNum, low, high);
}
}
* important that in the condition if() you always use == two equal sign :
num = high : assign "high" in th num variable ;
num == high : compare num and high value
3.3 Make decision using if-else
dual -alternative decisions : have two possible resutlign actions
two actions upon the result of the if condition : true ? or false : both will result in dieffrent actions
Write(" Please input one number : ");
int inputNum = int.Parse(ReadLine());
int high = 7;
if (inputNum < high)
{
WriteLine(" Your numer {0} is lower than {1}", inputNum, high);
}
else {
WriteLine(" Your numer {0} is higher than {1}", inputNum, high);
}
ReadKey(); // if you want your output freeze in the screen.
3.4 use compound expressions in if statements
you can combine mutiple decision in to a single if statment :
AND : && determine weather both fo the condition is ture : both have to be true
OR : || determiend weather one of the condition is ture : one of the conditoin is true
<pic> <pic>
you can combine && and || together in one expression, morelikly && will prcess first
so you have to use ( a || b) && c
3.5 Make decisions using switch statements
Switch structure : tests a single variable against a series of exact mathces
switch :
case : follow by one of the possible vaoue that equal to switch expresssion
break : terminates a switch
default :
Write(" Please write which year you in ? : ");
int year = int.Parse(ReadLine());
switch(year)
{
case 1:
WriteLine("Freshman");
break;
case 2:
WriteLine("Sophomore");
break;
case 3:
WriteLine("Juniore");
break;
case 4:
WriteLine("Senior");
break;
default:
WriteLine(" WTF you ?");
break;rite(" Please write which year you in ? : ");
int year = int.Parse(ReadLine());
switch(year)
{
case 1:
WriteLine("Freshman");
break;
case 2:
WriteLine("Sophomore");
break;
case 3:
WriteLine("Juniore");
break;
case 4:
WriteLine("Senior");
break;
default:
WriteLine(" WTF you ?");
break;
3.6 use the conditional operator
testExpression ? trueResult : falseResult ;
WriteLine((testScore >= 60)) ? "pass" : "Fail" );
=> if the tesscore is over 60 => pass
biggerNum = (a >b ) ? a:b
=> bigger number comesout
3.7 Use the NOT operator
!= not same
3.8 Avoid common errors when making decisions
Rangecheck ; make sure your statement range is specified ranged
if statement : used to make a signle -alternative decision
Lecture4
3 Loops methodes
using it depdend on the problem / developer
Looping allow program to do reapeat tasks based on Boolean expression.
Loop body : block of stament in looping structure
reulst is true : keep looping
result in false : exit the loop
iteration = 1 loop
4.1 Create loops unsing the while Statmenet
while :
while loop = looping until the some condition is TRUE ; as soon as the conidion beceom false exit the loop
infinite loop : you make silly mistake and become never end the loop;
1. loop control variable should initlized;
2. loop control variable must be tsetd ;
3. body of the llop must take some action that alters the value of the loop control variable ;
//while loop
int number1 = 1;
int limit = 5;
while (number1 < limit)
{
number1++;
WriteLine(" hi this is while loop {0}", number1);
}
WriteLine(" End of the loop" );
ReadKey();
becareful where is the variable ? begining / in the end ?
depend on where is the evaluation there is some difference
definite loop : loop that has nubmer of iteration is already set ;
indefinite loop : user input will end the loop;
sentinel value : value such as Yes or No by user;s input ; every iteration it will ask user to continue
4.2 Create loops using the for statement
usually use for the defnite loops ,
using step value ;
this make the program shorter than while loop
iniitailizing , testing , updating ;
variables only exist in the loop;
multiple line from do-while loop => one line to the for loop;
most commonly used loop ;
<pic> <pic>
3 things in one line in for loop ,
int x;
for (x=1; x < 5; x++){
WriteLine("hi is is for loop {0}" , x);
}
4.3 Create (do- while )loops using the do staement
do loop
it will always enter the loop without testing
while loop and for loop are pre-test loops =control variable is tested before the loop body excited;
do-while loop is post-test loop = control variable is tested after the loop body excuted;
int number1 = 1;
int limit = 10;
{
WriteLine(" hi this is while loop {0}", number1);
number1++;
}
while (number1 < limit);
WriteLine(" End of the loop");
do-while loop will do (extue ) without test at least first time
4.4 Use nested loops
inner loop and outer loop (similiar wirh if )
* important : inner loop has to be insde the outer loop
loops will never overlap
//nested loops
double bankBal;
double rate;
int year;
const double START_BAL = 1000;
const double START_INT = 0.04;
const double INT_INCREASE = 0.02;
const double LAST_INT = 0.08;
const int END_YEAR = 5;
for (rate = START_INT; rate <= LAST_INT; rate += INT_INCREASE)
{
bankBal = START_BAL;
WriteLine("Starting bank balance is {0}", bankBal.ToString("C"));
WriteLine(" Interest Rate : {0}", rate.ToString("P"));
for(year = 1; year <= END_YEAR; ++year)
{
bankBal = bankBal + bankBal * rate;
WriteLine(" After year {0}, bank balance is {1}", year, bankBal.ToString("C"));
}
}
*/
// odometer
int pos100, pos10, pos1;
int MAX = 10;
for (pos100 = 0; pos100 < MAX; ++pos100)
{
for (pos10 = 0; pos10 < MAX; ++pos10)
{
for (pos1 = 0; pos1 < MAX; ++pos1)
{
WriteLine("-----");
WriteLine("{0} :{1} : {2}" , pos100, pos10, pos1);
WriteLine("-----");
ReadLine();
}
}
}
4.5 Accumulated totals
Garbarge value = unknown value ; it happens when you dont initalize ;
4.6 Understand how to improve loop performance
consider the order of evaluation
do ++Value not value++
loop fusion, putting two loops together in one evaultion
++X and X++ are same but ++X is faster
while loop = loop excite when the value is ture
for loop = loop for if you know how many iteratoin
do-while loop = check the bottom of the loop after one repetition
Lecture5 Array
5.1 : Declare an array and assin values to array elements
Array : list of data item have the same data type ;
- if one data is int every element in the array are all integer =>
we call them as integer array ;
subscrpt = index ;
Declaring array :
double[]sales;
sales = new[20] or
double []sales = new double[20];
new operator : used to create object ; [20] : 20 spearte elements ;
create different elemetns ;
Array element : each object
subscript = index: position of the element
array staring fomr 0 -> "Off by one" : remeber to count from 0
Assiging element in array : sales[0] = 2100;
getting the array element : WriteLine(sales[19]);
Array as object in C# but not all the languages take array as object;
1. Declare the array ;
2. You have to intiliize it
default value bool =false ; Numeric field = 0; Char field = null or \u000
Differnet ways to declare the array
1) int [] myScroes = new int[5]{99 , 100 ,59, 40 ,10}
2) int [] myScroes = new int[]{99 , 100 ,59, 40 ,10}
3) int [] myScroes = {99 , 100 ,59, 40 ,10}
5.2 : Access array elements
Length property : System.Array class
array's length can get via array.Length
int[] myScores = { 100, 90, 80,70, 59 };
WriteLine(" Array size is {0}", myScores.Length);
for (int x = 0; x < myScores.Length; ++x)
WriteLine(myScores[x]);
int[] myScores2 = { 100, 90, 80, 70, 59 };
WriteLine(" Array size is {0}", myScores.Length);
foreach(int score in myScores2)
{
WriteLine("{0}", score.ToString());
} array + loop : <code>
5.3 : Search an array suing a loop
1. array + loop :
this is useful you want to show part of the array ;
2. array for each :
foreach statement : used in array ; list element in array you want to print :
*foreach (int _name in arrayName )
WriteLine("{0}", _name.Tostring(""));
you cant not change the value its read only
and its shows all the array
* search student's grade
this is sequential search (from beginning to the end );
Parallel arrays : secon array to hold the corresponding data ;
string[] studentName = { "adam", "sky", "abc", "danny ", "tom", "simon" };
int[] studentScore = { 90, 90, 40, 60, 50, 20 };
string name;
int score = 0;
bool isPass = false;
Write(" Plese input the name of the studnet : ");
name = ReadLine();
for(int x = 0; x < studentName.Length; ++x)
{
if( name == studentName[x])
{
isPass = true;
score = studentScore[x];
x = studentName.Length; // to improve the loop efficiency;
}
}
if (isPass)
{
WriteLine(" The score of {0} is {1}", name, score);
}
else
{
WriteLine(" No student with that name");
} <code >
using while loop to get maximum efficient
while( x < studentName.length && name = studentName[x]) ;
when the input value is same from the
5.4 : Use the Binary Serach(), sort(), and Reverse() methods;
Array.BinarySearch(): find the element in the array
- no dubuplicated
Array.BinarySEarch(array_name , input);
Array.Sort(): sort an array element ( lowst- > highets) (alphatic order)
Array.Sort(name_array);
Array.Reverse(): reverse the order of elements
Array.Reverse(name_array);
using static System.Array() = to use BinarySearch(),Sort(),Reverse( )
5.5 use multidimensional arrays
One -dimensional (single-dimensional array);
multidimenional array :
double [,] sales = {{xx, xx,xx,xx},
{xx, xx,xx,xx},
{xx, xx,xx,xx}}
'IT > Programming' 카테고리의 다른 글
Heroku -django 설치오류 (0) | 2021.05.24 |
---|---|
[Youtube] 코딩 실습 튜토리얼 강의 추천 (0) | 2021.03.22 |
[Mac OS]. Mac 개발 관련 도구 에러Git Clon Error , xcrun: error (0) | 2021.02.24 |
[VS CODE] 단축키 (0) | 2020.12.29 |
[git] xcrun: error: invalid active developer path (0) | 2020.11.28 |