0% found this document useful (0 votes)
4 views

Lec 03 - Introduction to Programming

Uploaded by

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

Lec 03 - Introduction to Programming

Uploaded by

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

Introducti

on to
Programm
ing
Lecture 3
Contents
Introduction to Programming
Introduction to Object-Oriented
Programming
Data Types
Variables
Operators
Standard Output
Standard Input
Strings
Strings Formatting
Arrays [ Java ]
Lecture 1 Sample Programs
Terminology
Software: A set of statements written in a programming language use to
operate computers
Statement: A line of code in a software program.
Snippet: A block of statements grouped together.
SD: Software Development – The process of creating a software program.
OOP: Object Oriented Programming – Program composed of interconnected
objects at runtime.
Expression: An entity-code component of a statement that can be evaluated to
produce a value.
Assign: The process of giving a combination of one or many expressions (result
is a value) on the right-hand side of the ‘ = ‘ to the left hand-side. Value: Data
Introduction to Programming
A program (software) is a set of code (statements) written in a
programming language. The program communicates with
computers to performs tasks and operations, such as:

Perform Read and Accept Input Display


Analyze Data
Calculations Write to Files from Users Images

Generate
Connect to a Display Output
Random Modify Text
Database to Screen
Numbers

Reference: https://en.wikipedia.org/wiki/Software
Introduction to Programming
Programming is the process of creating a program (software) using a
programming language. Each programming language has its own:
- Vocabulary (keywords, identifiers)
- Grammar (structure, syntax)
- Punctuation (operators, delimiters)

There are many programming languages. Example:


- Java
- C/C++/C#
- Python
- JavaScript
- Go

Reference: https://www.webopedia.com/definitions/programming-language/
Introduction to Programming
A programming language is either compiled or interpreted. Compilers
and interpreters turn the high-level programming language code into
low-level machine code for the computer to understand and process.

Compilers complete the


Interpreters complete the
conversion process all at
conversion process one
once after changes are
step at a time while the
made to the code and
code is being executed
before the code is
executed

Compiled Languages: Interpreted Languages:


- Java - Python
- C/C++/C# - PHP
- Go - JavaScript
Introduction to Programming
A program (software) is written in a file using editors:
- Notepad
- Nano
- Vim

Specialized IDEs are capable of spelling correction, syntax


correction, auto-complete syntax, fix suggestion, auto-
indentation
- BlueJ
- Netbeans
- IntelliJ
- Eclipse
- VS Code
- Sublime
Reference: https://en.wikipedia.org/wiki/Computer_programming
Introduction to Programming
The software development process is an iterative approach. A program
must be executed often to find exactly the line of code that does not
work and fix it.

Run your Repeat and


program often continue working

Develop
and
Debug

Find the line of


code that does Fix the problem
not work
Introduction to Programming
There are several OOP
Java is a high-level, class-
languages, such as: based, general purpose
- Java OOP language intended to
- C++ let programmers write the
- C# code once and run
- Python anywhere. This means that
- … there are many more compiled Java code can
run on all platforms that
support
Python Java is awithout the
high-level
In this subject we will need to recompile.language
programming
learn Java and Python intended to emphasize
code readability. Python
code is interpreted top to
bottom dynamically.
Python supports object-
oriented programming and
Introduction to Programming
Java is strictly an Object-Oriented Python is a scripting languages
Programming Language. Java code that also supports Object-Oriented
is written in classes Programming.
Python program can have many
Java Program can have multiple
scripts. Python scripts can be
classes. At least one of them must
imported into others for reusability
have the main( ) method.
of functions
Java class is written in file
Python is written in file with .py
with .java extension. E.g.:
extension. E.g.: welcome.py
Welcome.java
Java class is compiled to .class Python script is not compiled
binary file using Java compiler: instead it is executed from top to
javac Welcome.java bottom line by line
Java program is then executed Python script executed using the
using the command: command:
java Welcome python welcome.py
Object Oriented Programming
Object: An object is a thing, tangible and intangible. An object has
fields that contain the data and methods to access and modify the
data. The definition of object data and methods is specified in a
Class.
Class: A class is an abstract definition of objects. A class is a
template of a blueprint that defines what data and which methods
are included in objects. An object is an instance of a class
(created/instantiated from a class).
Method: A block of code grouped together to perform an operation.
A method has a name, parameters, and a return type.
Object Oriented Programming
… object is an occurrence of a corresponding class at a given moment

in time (instance).

… many objects can be instantiated from one class.

… object is created when the code in the class template written in Java

language is compiled and executed.

… all objects created from a class have access to the methods defined

in that class.
Object Oriented Programming
Java Class Python Class
Structure { Optio
import packages Structure { Optio
import packages
nal} nal}
English comments { Optio English comments { Optio
nal} nal}
Class header { Requ Class header { Requ
ired} ired}
Fields { Optio Fields { Optio
nal} nal}
Constructors { Requ Constructors { Requ
ired} ired}
Methods { Optio Methods { Optio
nal} nal}
toString() { Optio __str__() { Optio
nal} nal}
Object Oriented Programming
Java type-strict declarative
programming language:
- Variable type must be specified
- Function type must be specified
- Object type must be specified

Defining a Variable Defining a Method Defining an Object

<Type> <variable-name>; <Type> <method-name>; <Type> <object-name>;


Object Oriented Programming
Python type-inferred
programming language:
- Variable type is inferred from
value
- Function behaviour is inferred
from return type
- Object type is inferred from
created instance
Defining a Variable Defining a Method Defining an Object

<variable-name> = <value> def <method-name>: <variable>=<object-name>


Object Oriented Programming
Java and Python use agreed upon naming convention to improve
code readability and code design.
Identifier Java Python
Type
Class A noun starting with an uppercase A noun starting with an uppercase
letter. Use CamelCase for multi-word letter. Use CamelCase for multi-word
classes, where each word starts with an classes, where each word starts with an
uppercase letter. uppercase letter.

Function Usually verbs or verb phrases, Lowercase words separated by


camelCase underscores.

Procedure Usually verbs or verb phrases, Lowercase words separated by


camelCase underscores.

Variable camelCase ,e.g., userName Lowercase words separated by


underscores, e.g., user_name.

Constant All uppercase words separated by All uppercase words separated by


Object Oriented Programming
Java class is defined in a same name .java which can be executed
only if main( ) exists in the class

Javais defined in a .py script thatPython


Python class can be executed as
standaloneClass
program and imported asclass
public class Person {
private String name;
Person:Class
a module
private int age;
def __init__(self,name,age):
public FirstProgram(String name, int age) { self.name=name
this.name = name; self.age = age
this.age = age;
}
def __str__(self):
@Override return f”{self.name} – {self.age}”
public String toString(){
return this.name +” –
“+ this.age
}
}

Defining a Java class Defining a Python class


Object Oriented Programming
Java uses the toString() function to return objects’ information.
Python can refer to attributes directly or use the __str()__ function
to return objects’
Java information Python
Class
public class FirstProgram {
public static void main(String[] args) Script
person1 = Person(“John Smith”,33)
{ print( f’Name: {person1.name}’ )
Person p1 = new
print( f’Age: {person1.age}’ )
Person(“John Smith”,33);
System.out.println(p1); print(person1)
}
}

Name: John Smith


John Smith - 33 Age: 33
John Smith - 33

Using a Java class Using a Python class


Object Oriented Programming
Java uses the dot “ . “ notation to access methods defined in a
class from another class.
Syntax:Java
<object>.<method>(<arguments>)
Class Java [Class This action is
possiblePerson
only if the method is declared
public class Person {
public
public ]People
class People
public
{
static void main(String[]
private String name; args){
private int age; Person p = new
Person(“Tom”,34);
public FirstProgram(String name, int age) {
p.show();
this.name = name;
this.age = age; }
} }

public void show(){ /*


System.out.println(name+” * The dot notation is used to call (invoke) a
age is: “+age); * method define in another class
} * Syntax: object.method(arguments)
}
*/
Defining a Java class with Using the show( ) method
a method show( ) in another class
Object Oriented Programming
Import a class from a Python script to from arithmetic import Value
use it in another script
class Calculator:

def total(self, ocv):


current = ocv.get_value()
ocv.add_value(current)
class Value:
return ocv.get_value()
def __init__(self, value):
self.value = value
value = Value(5)
def add_value(self, k):
self.value += k calculator = Calculator()

def get_value(self): total = calculator.total(value)


return self.value print("Current value = ",total)

total = calculator.total(value)
print("Current value = ",total)

Define a Value class in Define a Calculator class in


script1.py script2.py that uses Value
Data types
Data Size Default Description
Type Value
byte 1 byte 0 Stores whole numbers from -128 to 127
short 2 bytes 0 Stores whole numbers from -32,768 to 32,767
int 4 bytes 0 Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes 0L Stores whole numbers from -
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes 0.0f Stores fractional numbers. Sufficient for
storing 6 to 7 decimal digits
double 8 bytes 0.0d Stores fractional numbers. Sufficient for
storing 15 decimal digits
Primitive Data types
int: The int data type is generally used as a default data type for
integer values. By default, the int data type is a 32-bit signed two's
complement integer, which has a minimum value of -231 and a
maximum value of 231-1.
float: The float data type is a single-precision 32-bit IEEE 754
floating point. This data type should not be used for precise values,
such as currency.
double: The double data type is a double-precision 64-bit IEEE 754
floating point. This data type is generally the default choice. This
data type should not be used for precise values, such as currency.
boolean: The boolean data type has only two possible values: true
and false. Use this data type for simple flags that track true/false
Non-Primitive Data types
• Non-primitive data types (also called complex data types or
composite data types) are created from Classes.
• Examples of non-primitive data types are Arrays, Classes,
Interfaces, and Strings.
• Non-primitive data types are by default set to null in Java and
None in Python.
Variables
Variables Categories:
The following are the categories of variables in Java and Python:
• Local Variables: Declared within a method scope
• Global Variables: Declared at class level outside all methods and
available for all methods.
[In Java, global variables are the class fields, and those fields are
usually
class Car{
declared private] class Car:
//pos is a global variable #pos is a global variable
private int pos; pos = 0

public void move(){ def move:


//distance is #distance is local
local variable variable
int distance = 10; distance = 10
this.pos += pos += distance;
distance;
}
}
Variables
Declaring a variable:

• In Java: Variables are declared with type and then initialized to a


value
• In Python: Variables are initialized to a value and type of the
variable is inferred from the value
Java Python
int x = 2;
Code
//declare and initialize #initialize
x = 2
Code
//change value #change value
x = 4; x = 4

x = 3.5; will throw an error x = 3.5


Variables
Constants:

• In Java: A constant is a variable has a fixed (declared with final


keyword) value and cannot be changed after it has been initialized
the first time. Static makes the variable to be available without an
instance of its defining class being loaded. Final makes the variable
unchangeable
• In Python: Python does not have special keywords for constants,
Java are declared in modules and Python
instead variables imported into other
Python andCode
//declare scripts.
initialize a constant
static final double RATE = 5.65;
Code
#code in another module (exp: other.py)
RATE = 5.65

//constant cannot be changed after #import the other module


//first value is given import other
RATE = 4; will throw an error print(other.RATE) #rate is fixed here
Variables
Type Casting and Type-Promotion:
• In Python: Python a variable can be changed to a new type by
assigning a different value-type to it
• In Java: Type casting is used to convert a data type to another
programmatically.
NOTE: Not all data types can be casted to a target type.
• In Java: Type Promotion specifies that a small size datatype can be
promoted to a large size datatype. E.g., an Integer type can be
Java Type
promoted to long, float, double, etc.
Java Automatic
int
Casting
//declare and initialize
NOTE: Type-Promotion
public void method(double a){
x = 2; Not all data types can be type-promoted to a target
System.out.println("Method type.
called");
}
x = 3.5; will throw an error
public static void main(){ method(2); }
//the value stored in x is now 3
x = (int)3.5; works fine
Operators
There are several operator categories supported by Java and Python:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Ternary Operators
• Unary Operators (Java Only)
• Identity/Membership Operators (Python Only)
Operators
Operator Category Java Python

Unary expr++ expr--

++expr --expr +expr -expr +expr -expr

Arithmetic */% */%

+- +-

Relational < > <= >= < > <= >=

== != == !=

Logical && not and

|| or

Ternary (expr1) ? <expr2> : <expr3> <expr2> if (expr1) then <expr3>

Assignment = += -= *= /= %= = += -= *= /= %= **=

Identify/Membership is is not in not in


Operators
Operator Precedence in Java:
Order of precedence matters significantly
when an expression is evaluated.

Example:
4 + 2 * 3 = 10
(due to the higher precedence of
multiplication 2*3 is evaluated first)

( 4 + 2 ) * 3 = 18
(due to the higher precedence of
parentheses 4+2 is evaluated first)
Operators
Arithmetic Operators:

Example:

Java Python
int x = 2;
int y = 4;
Code x = 2;
Code
#declare and initialize

y = 4
int z = 1/2 #z holds the value 0.5
/* #python allows decimal division by default
z holds the value 0 since both operands are z = x/y;
integers the division is integer division.
To obtain 0.5 either x or y should be type-
casted to floating point
*/
Operators
Logical Operators:

Example:

Java Python
boolean x = trueCode
; x = True ; Code
boolean y = false; y = False;

boolean z = x || y && true // z is true z = x and y or True # z is True

// q is true
boolean q = (5%2 != 2) ? true : false; # q is True
q = True if (5%2 != 0) else False;
Standard Output
Jav Pytho
a n
The System class is part of the Displaying data to STDOUT with
java.lang package, which is Python is simple using the function
automatically imported into every print( ).
Java program.
- System.out (standard output print(“Welcome to Python”);
stream) Will output the string to the
- System.err (standard error STDOUT terminal :
stream) Welcome to Python
- System.in (standard input
stream)
Standard Input
Jav
a
Pyth
Scanner class in Java is part of the
on
java.util package. You need to Reading data with Python is simple.
import it at the beginning of your It can be accomplished using the
code. input function or by-passing
import java.util.Scanner; arguments to the scripts at
execution phase:
Java provides various ways to read
input from the keyboard, using the var = input(“prompt: ”) #var is a
System.in open stream. string type
nextInt() (read an integer)
nextLine() (read a line or a OR

String)
Standard Input
Example: Java
Code
import java.util.Scanner; Python
import sys Code
#has the argv list
public class Inputs{
// Create a Scanner object to read from
System.in (keyboard input) x = int(input("x = "))
static Scanner in = new Scanner(System.in);
print("x squared = ",pow(x,2))
public static void main(String[] args){
System.out.print("x = ");
#sys.argv[1] stores first argument
int x = in.nextInt();
System.out.println("x squared = "+Math.pow(x,2)); after the script name
} y = sys.argv[1]
} print("y = ",y)

x=4 $ python inputs.py 4


x squared = 16 x=4
x squared = 16
y= 4
Strings (Java)
String: The String class is a class from the default package java.lang.
Instances of String represent sequences of characters . String is a non-
primitive (complex) data type defined by Java.
There are many ways to create instances of String. RAM
Example:
Hello {Memory
String s1 = “Hello”; initialize using S1
location for s1}
literal syntax
String s2 = new String(“Hello”);initialize S2 Hello {another
using a constructor location for
Reference: s2}
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html
Strings (Java)
Other data types can be promoted to Strings.
Other data types can be concatenated (joined) with Strings using
Example:

int x = 2; boolean a = true;


String s = 2+” is integer”; (s String s = “4 > 2 is ”+a; (s
becomes “2 is an integer”) becomes 4 > 2 is true)
String s = “Hello”; int x = 2;
s = s + “ Tom”; (s becomes String s = “value “+x; (s
Strings (Java)
String is immutable and cannot be changed once it is created. If
you want to give a String a new value, then you create a new
String and assign it to the original one.
RAM
In the previous example “Tom” was not simply added to the
S
original value “Hello” of s. The Hello {original
dynamic is different from s in
the RAM}
String s = “Hello”;
numerical operations.
1 Hello Tom {new
s = s + “ Tom” ; String}

(1): creates a new String 2


S

(2): assign the new String


Strings (Java)
String: The String is a sequence of indexed characters starting from
Represented
zero until the length of the by
String length -1 h e l l o

Example: Considerindex
String s = “hello”; 0 1 2 3 4

charAt(index) (returns the first character in s, e.g. s.charAt(1)


is ‘e’)
contains(sequence) (check if s contains sequence, e.g.
s.contains(“he”) is true)
equals(otherString) (check if value is equals to otherString value,
Strings (Python)
String: The String is a sequence of indexed characters starting from
Represented
zero until the length of the h
by String length -1
e l l o

index 0 1 2 3 4
Example: Consider s = “hello”;

s[index] (returns the first character in s, e.g. s[1] is ‘e’)


find( ) (finds the first occurrence of the specified value,
e.g. s.find(“e”) is 1; returns -1 if the value is not found)
upper( ) (converts string characters to upper-case)
len( ) (returns the length of s, e.g. len(s) is 5)
strip( ) (removes trailing spaces from s)
Strings Formatting
Outputs in programming are text displayed to the STDOUT. The following
techniques are used to format output strings in Java and Python:

Jav Pyth
a on
• Using the DecimalFormat class • Using the modulo % operator for
string formatting
from java.text package • Using the format() function from
• Using the printf() method from string
the System class • Using f command for string
formatting (an f-string or a string
• Using the format() method from
literal prefixed with ‘f’ or ‘F’)
the System class
• Using the format() method from
Strings Formatting
Example (Java): Consider variables: String name =
“Tom”; double balance = 12.4556;
The objective
String is to display the output: <name> has
pattern = "####,####.##"; Tom has 12.46
DecimalFormat df = new DecimalFormat(pattern);
<balance>
System.out.println(name+” has ”+df.format(balance));

System.out.printf(”%s has %.3f”,name,balance); Tom has 12.456

String output = String.format(”%s has %.2f”,name,balance); Tom has 12.46


System.out.println(output);

System.out.format(”%s has %.4f”,name,balance); Tom has 12.4556


Strings Formatting
Example (Python): Consider variables: name =
“Tom”; balance = 12.4556;
The objective
print(“%s is to display the output: <name> has
has %.2f”%(name,balance)) Tom has 12.46

<balance>
print(“%10s has %.2f”%(name,balance)) 7 spaces Tom has 12.46

print(“{} has {}”.format(name,balance)) Tom has 12.4556

print(“{:>10} has {:.3f}”.format(name,balance)) 7 spaces Tom has 12.456

print(f'{name:^10} has ${balance:>10.2f}') Tom has 12.46


Arrays (Java)
Definition:
● An Array in Java is a collection of data of similar type.
● Multiple values can be stored in a single array object.
● The array name (reference) points to the contiguous memory
location where the array object is stored.
● Arrays in Java are index and ordered. The array elements are
indexed from zero to array length -1
● The array object is a dynamically generated class that inherits the
Object class in Java.
● Arrays can store primitive and complex data types (objects).
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
Arrays (Java)
Implementation:
To use arrays in Java there are three steps: Declaration, Instantiation,
and Initialization
Syntax: Array Declaration (only a reference of the array is created)
<data type> [] <variable-name> //variation 1
<data type> <variable-name>[] //variation 2

Syntax: Array Instantiation (creates or gives memory to the array)


<variable-name> = new <data type> [<size>]

Syntax: Array Initialization


<variable-name> = {<value0>, <value1>,…, <value(size-1)>}; //variation 1
<variable-name>[0] = <value0>;…<variable-name>[size-1] = <value(size-1)>; //variation 2

NOTE: Arrays in Java have fixed size, once they are created the size does
not change
Arrays (Java)
Example:
int a1 []; RAM
Declaring the a1 array a1
11
By default a1 points to null
null {Memory
in the RAM
location for a1}
a1 = new int[3];
22 Creating the a1 array a1
By default a1 values are int
default (zeros) 0 0 0 {Memory
a1[0] = 1; location for a1}
a1[1] = 7; {a1 values
33
a1[2] = -3; updated}
Initializing the a1 array 1 7 -3
Arrays (Java)
Access:
Arrays in Java are indexed in a proper order. Array elements are
accessed using the index of these elements.
Syntax: Accessing
Given:
<data type>[] <variable-name> = {<value0>, <value1>,…, <value(size-1)>};
<data type> x0 = <variable-name>[0]; //Accessing first element

<data type> xn = <variable-name>[size -1]; //Accessing last element

value0 value1 value2 … … value(size-1)


0 1 2 … … size-1
<variable>
Arrays (Java)
Modify:
Array elements are modified using the index of the elements to
access and then set these elements to new values.
Syntax: Modifying
Given:
<data type>[] <variable-name>= {<value0>, <value1>,…, <value(size-1)>};
<variable-name>[0] = x0;
<variable-name>[size-1] = xn; //Modifying last element

x0 x1 x2 … … xn
0 1 2 … … size-1
<variable>
Arrays (Java)
Example: Creating, Initializing, Accessing, and Modifying

● Declaring an integer array int x []= {2,4,-1,11,3};

int size = x.length;


● Creating and Initializing the array
System.out.println(“First = “+x[0]);
● Return the length of the System.out.println(“Last = “+x[size -1]);
array
x[2] = 4;
● Accessing the array elements
x[3] = 7;

● Modifying the array elements

NOTE: length is a constant property that


stores the array size
Arrays (Java)
Display (Printing an Array):
The Arrays class from java.util provide a wide range of useful
methods that could help with
converting/searching/sorting/copying/comparing/modifying arrays
Syntax: Printing (Using the Arrays class)
Given: <data type>[] array = {<value0>, <value1>,…, <value(size-1)>};
Step 1 - Import Step 2 - Convert Step 3 - Print

import java.util.Arrays; String s = System.out.println(s);


Arrays.toString(array);
Arrays (Java)
Example: Printing arrays using the Arrays class

● Importing the util package import java.util.Arrays;

int x [] = {2,4,-1,11,3};
● Declaring an integer array
String s = Arrays.toString(x);
● Creating and Initializing the array
System.out.println(s);

● Converting the array to String

● Printing the array as a String


Sample Program (Java)
import java.util.Scanner;

public class Inputs{


static Scanner in = new Scanner(System.in);

public static void main(String[] args){


Sample output
System.out.print("x = "); x=3
int x = in.nextInt();
Squareroot(x) =
//format( ) is a function to format the output 1.732
// %.3f format the value at 3-decimal points
System.out.format("Squareroot(x) = %.3f\n",Math.sqrt(x));
}
}
Sample Program (Python)
import math

class Geometry:
def __init__(self,radius):
self.radius = radius

# self is available to access the radius in the area Sample output


function Radius = 3
def area(self,radius):
return math.pi * pow(self.radius,2) Area = 28.27

# self is available to access the radius in the str


function
# formatter f’’ injects the values in the string output
# .2f formats the area at 2-decimal points
def __str__(self):
output = f'Radius = {self.radius}\n'
output += f'Area = {self.area(self.radius):.2f}'
return output

geo = Geometry(3)
print(geo)
Thank You

Refer to lecture videos for further code


demos

You might also like