Combinepdf
Combinepdf
C++ Examples
Explicit Heap Dynamic 1
Explicit heap dynamic
Dart Examples
Array
Enumeration
Fibonacci
Hello World
List
Print Integer
t1
Test
Type inferencing
Type inferencing 2
JavaScript Examples
Console
Dynamic Types
Running
Vars
Perl Examples
Ex1
Chapter 5 Scope
C
main() { In main i=1
{ // inner block
int i=3;
————————————————————————————————————————————————————————--
#include<stdio.h> In sub3, x=1, y=2, z=3
void sub2() {
int y;
void sub3() {
int z = 3;
} // sub3
y = 2;
sub3();
} // sub2
x = 1;
sub2();
} // sub1
void main() {
sub1();
}
#include<stdio.h>
in foo: n=5
void foo() {
in bar: i=7
static int n = 5;
in foo: n=6
printf("in foo: n=%d\n", n);
n++;
} // foo
void bar() {
static int n = 7;
void main() {
foo();
bar();
foo();
} // main
————————————————————————————————————————————————————————--
JavaScript
x=5;
let x = 3; x in global: 5
————————————————————————————————————————————————————————--
x=5;
x=3
{ // var does not create local
scope for its variables in the
block.
var x = 3;
console.log("x="+x);
function sub1() {
var x;
function sub3() {
var z;
z=3;
} // sub3
y=2;
sub3();
} // sub2
x = 1;
sub2();
} //sub1
sub1()
————————————————————————————————————————————————————————--
x = 1; in foo, x=3
function foo() { in global x=1
var x = 3; // try with/without "var"
foo();
————————————————————————————————————————————————————————--
x = 1; in foo, x=3
function foo() { in global x=3
x = 3; // try with/without "var"
foo();
function foo2() {
}
————————————————————————————————————————————————————————--
x=5;
foo();
————————————————————————————————————————————————————————--
x=5;
foo();
foo(5);
console.log(x);
————————————————————————————————————————————————————————--
x=5;
while (n==1) {
n=0;
————————————————————————————————————————————————————————--
x=5;
n=1;
n=0;
sub foo {
in foo, a is 0
return "in foo, a is $a\n";
in bar, b is 1
}
global b is 77
sub staticScope {
return foo();
$b = 0; # global variable
sub bar {
sub dynamicScope {
$b =77;
local $b = 1;
return bar();
————————————————————————————————————————————————————————--
sub visible {
sub dynamic {
var has the value global
local $var = 'local'; # new temporary value for the still-global var has the value local
visible(); # variable called $var var has the value global
sub lexical {
$var = 'global';
B();
sub B {
C();
sub C {
A();
sub foo {
foo(); # 456}
foo();
————————————————————————————————————————————————————————--
sub static_parent {
sub dynamic_parent {
check;}
dynamic_parent;}
static_parent;
sub static_parent {
my $x='static-parent';
check;
check;
dynamic_parent;
static_parent;
————————————————————————————————————————————————————————--
sub big {
$var=1;
In global, before big, var is **
sub sub1 () { In sub1, var=1
In sub2, var is 2
print "In sub1, var=$var\n";}
In sub1, var=2
sub sub2 () { In sub1, var=2
$var = 2; In global, after big, var is 2
sub1();
sub1();
sub2();
sub1();
big();
sub sub2 () {
local $var = 2;
sub1();
sub2();
sub1();
big();
————————————————————————————————————————————————————————--
sub big {
my $var=1;
In global, before big, var=
sub sub1 () { In sub2, var=2
print " In sub1 var=$var\n"; In sub1 var=1
In sub1 var=1
}
In global, after big, var=
sub sub2 () {
my $var = 2;
sub1();
sub2();
sub1();
big();
$a = 0; 0
1
sub foo {
return $a;
sub staticScope {
my $a = 1; # lexical (static)
return foo();
print "\n";
$b = 0;
sub bar {
return $b;
sub dynamicScope {
local $b = 1;
return bar();
————————————————————————————————————————————————————————--
PHP
<?php
echo "SIZE=".SIZE."\n";
$twice = SIZE * 2;
?>
<?php
$day ="Monday";
$month = "October";
function calendar() {
$day = "Tuesday";
$gday = $GLOBALS['day'];
$GLOBALS['day'] = "Wednesday";
Global variables in PHP
print "gday is $gday.<br>"; local day is Tuesday
local gday is Monday
$month = "April";
gday is Monday.
print "local month is $month<br>"; local month is April
global month is March
In the other block, day is Wednesday
In the other block, month is March
global $month; // affects the rest of block
In the other block, year is 2020
$month = "March";
global $year;
$year=2020;}
calendar();
?>
<?php
?>
————————————————————————————————————————————————————————--
<?php
$x = 5;
$y = 10;
x is
function foo() {
in foo, y is
echo "x is $x<br>"; // $x is not visible in global, y is 5
global $y; }
foo();
?>
<!--
For the most part all PHP variables only have a single scope.
-->
x=
<?php g=3
function foo() {
$x = 7;
global $g;
bar();
} // foo
foo();
?>
————————————————————————————————————————————————————————--
Python
day = "Monday"
calendar()
————————————————————————————————————————————————————————--
day = "Monday"
calendar()
def calendar():
UnboundLocalError: local variable 'day'
print ("global day is", day) referenced before assignment
day = "Tuesday" #day becomes local !!! Error
calendar()
————————————————————————————————————————————————————————--
day = "Monday"
def calendar():
global day is Monday
global day #day is defined as global
global day is Tuesday
print ("global day is", day)
calendar()
————————————————————————————————————————————————————————--
day = "Monday"
def c():
calendar()
c()
————————————————————————————————————————————————————————--
day = "Monday"
calendar()
msg = "Inside!"
print(msg)
inside()
print(msg)
outside()
————————————————————————————————————————————————————————--
msg = "Global"
Inside!
def outside():
Outside!
msg = "Outside!"
Inside!
def inside():
global msg
msg = "Inside!"
print(msg)
inside()
print(msg)
outside()
print(msg)
————————————————————————————————————————————————————————--
def outside():
msg = "Outside!"
Inside!
def inside():
Inside!
nonlocal msg
msg = "Inside!"
print(msg)
inside()
print(msg)
outside()
msg = "Global"
def outside():
Inside!
msg = "Outside!"
Inside!
def inside():
Global
nonlocal msg
msg = "Inside!"
print(msg)
inside()
print(msg)
outside()
print(msg)
————————————————————————————————————————————————————————--
x=0
def outer():
x=1
inner: 2
def inner():
outer: 2
nonlocal x
global: 0
x=2
print ("inner:", x)
inner()
print ("outer:", x)
outer()
print ("global:", x)
————————————————————————————————————————————————————————--
x=0
def inner():
nonlocal x
x=2
print ("inner:", x)
inner()
print ("outer:", x)
outer()
print ("global:", x)
def level1():
x=1
def level2():
y=2 level3: x= 3 y= 2
nonlocal x level1: x= 3
x=3
level3()
level2()
level1()
————————————————————————————————————————————————————————--
def foo ():
bar()
x=7
foo()
————————————————————————————————————————————————————————--
def foo ():
x=5
in main x is 3
def bar():
in foo x is 5
#x=7
in bar x is 5
print("in bar x is", x)
in foo x is 5
in main x is 3
print("in foo x is", x)
bar()
x=3
foo()
C Examples
Code arrays.c
Output
foo, sa[0]=0 sa[1]=0 sa[2]=0 sa[3]=33
foo, ehda[0]=0 ehda[4]=44
bar, sda[0]=0 sda[1]=0 sda[2]=22 sda[3]=0
main, sa[0]=3 sa[1]=5 sa[2]=7 sa[3]=9
Code dangling_ptr_explicit.c
Output
p is 0x563867d372a0
q is 0x563867d372a0
after free(q):
q is 0x563867d372a0
p is 0x563867d372a0
is 0x563867d372a0
*p is 7
Code dangling_ptr_implicit.c
Output
*ip is 32765
Code enum.c
Code multi-dim-array.c
Code nested-struct.c
Output
Person2: Name=Ahmet, Age=21, Salary=4567.890137
Person2: Name=Ahmet, Age=22, Salary=4567.890137
Person1: Name=Ahmet, Age=21, Salary=4567.890137
Code stack-array.c
Output
357
468
357
Code static-variable.c
Output
in foo: n=5
in foo: n=5
in bar: i=7
in bar: i=8
Code string.c
Output
97-98-99-0-0-0-0-0-0-0-
97-98-99-100-101-102-0-0-0-0-
Code string_0.c
Output
5th char in Ali is **
Code struct.c
Output
Size of name in person is 50
Size of age in person is 4
Size of salary in person is 4
Size of person is 60
Person2: Name=Ahmet, Age=21, Salary=4567.890137
Person2: Name=Ahmet, Age=22, Salary=4567.890137
Person1: Name=Ahmet, Age=21, Salary=4567.890137
Code union.c
Output
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Memory size of a Data: 20
Code vla.c
Output
In foo, Enter number: In foo, 17
Size of array is 21931
JS Examples
Code associative-array.js
Code associative-array.html
Output
hi32
Perl Examples
Code dynamic-array.pl
Output
Foo Bar Moo
$names[1] = Bar
Foo 30 Moo
Foo 30 Moo Darth Vader
Vader
Foo 30 Moo Darth
Foo
30 Moo Darth
Code grades.pl
Output
grade of Veli: 80
grade of Veli: 90
grade of Su: 100
Su 100
Veli 90
Nur 99
after makint it empty:
PHP Examples
Code array_0.php
Output
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
)
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
[B+] => 3.3
)
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
[B+] => 3.3
[4] => fifth
)
Code array_1.php
Output
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
)
<br>first<br />third<br />
first<br />
Array
(
[0] => 0.2
[1] => 2
[2] => Ahmet
)
Rust Examples
Code array_0.rs
Output
[1, 2, 3, 4, 5]
Code array_1.rs
Output
[1, 2, 3, 4, 5]
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
Code hello-world.rs
Output
Hello, world!
Code slice.rs
Output
first element of the array: 1
second element of the array: 2
array size: 5
zs is [0, 4, 16, 36, 64]
zs1 is [16, 36, 64]
borrow a section of the array as a slice
first element of the slice: 3
the slice has 3 elements
Python Examples
Code dynamic_array.py
Output
[2, 1.6, (3+5j), 'c', 'a word']
(-7+11j)
['a', 3]
a is ['a', 3, 'q']
first element of a is a
a is ['z', 3, 'q', 'hale', 'jale', 'lale']
a is ['z', 3, 'q', 'jale', 'lale']
last element of a is lale
Code garbage_collect.py
Code garbage_collect_ex.py
Output
2
3
3
Code lists.py
Output
[1, 2.3, 'three']
[1, 'three']
[1, 'orange', 'three']
[1, 'orange', 'three', 'plum']
Code reference-counts.py
Output
2
4
2
Code reference-counts-1.py
Output
4
5
4
5
Code reference-counts-2.py
Output
Code slices.py
Output
[2, 4, 6]
[8, 10, 12, 14, 16]
[2, 4, 6, 'a', 'b', 14, 16]
[[1, 2, 3], [2, 4, 6, 'a', 'b', 14, 16], [7, 8, 9]]
[[1, 2, 3], [2, 4, 6, 'a', 14, 16], [7, 8, 9]]
[11, 33, 55]
[3, 6, 9]
Code tuple.py
Output
Code tuples.py
Output
5.8
[3, 5.8, 'apple']
[3, 6.7, 'apple']
(3, 6.7, 'apple', 1, 'pear')
5
Chapter 7 Code Examples
C Examples
Bitwise-and.c
c.c
coercion.c
float2int.c
functional_side_effect.c
increment.c
short-circuit.c
unary-ops.c
conditional.c
Java Examples
Ex.java
JavaScript Examples
short-circuit.c
Output
in foo !
x = true
Perl Examples
multiple-assignment.pl
Python Examples
conditional.py
fibonacci.py
operator-overloading.py
Ruby Examples
ex.rb
CS 315 Examples 1
Subscript range checking for arrays is a part of type checking, but it must be done in the run-
time. Out-of-range subscript often cause errors that do not appear until long after actual
violation.
#include <stdio.h>
foo (char s[]) {
printf ("5th char in %s is %c\n", s, s[4]);
}
main () {
char str[] = "abc";
foo(str);
}
produces:
5th char in abc is }
$x = 5;
5
print $x ."\n";
Hello
$x = "Hello";
Hello
print $x ."\n";
Ali Ayse Can Canan
@x = ("Ali", "Ayse", "Can", "Canan");
print "$x \n";
print "@x \n";
%data = ('A', 4.0, 'A-', 3.7, 'B+', 3.3, 'B', 3); 3.7
print "$data{'A-'}\n";
Ex in Java:
Integer i = new Integer(5);
5.4-Summary
C Example:
int a1[10]; // static global variable.
static int a2 = 5; // static global variable, initialized
void foo(){
static int a3[10]; // static local array variable
int a4[10]; // stack-dynamic variable
int *a5 = (int *)malloc(10*sizeof(int));
// a5 (pointer) is stack-dynamic
// *a5 is explicit heap-dynamic
...
free(a5);
}
Sub2();
sub1();
}
CS 315 Examples 4
6. Data Types
6.3.3 String Length Options
• Limited dynamic length strings: (C and C++)
Following are equivalent in C
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
Python
>>> mylist = [2, 1.6, (3+5j), 'c', "a word"]
>>> print mylist
[2, 1.6, (3+5j), 'c', 'a word']
>>> x = (1+2j) * mylist[2]
>>> x
(-7+11j)
6.6 Associative Arrays
Provided in Perl (called hash) and Java.
* Indexed by keys
* The size can grow and shrink dynamically.
#!/usr/local/bin/perl
%notlar = ("Ali" => 95, "Veli" => 80, "Selami" => 95);
To print an entry:
print "Veli’nin notu $notlar{Veli}\n";
To add a new entry:
$notlar{"Hulki"} = 75;
To delete an entry:
delete $notlar{"Veli"};
To change an entry:
$notlar{"Veli"} = 82;
To go through the array:
foreach $anahtar (keys %notlar) {
print "$anahtar $notlar{$anahtar}\n";
}
To empty the array:
%notlar = ();
Ex: Python
>>> myTuple = (3, 5.8, 'apple')
>>> myTuple[1]
5.8
CS 315 Examples 6
>>> myTuple[1] = 6.7
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> myTuple = [3, 5.8, 'apple'] #Now, it is a list
>>> myTuple[1] = 6.7
>>> myTuple = (3, 5.8, 'apple') # Back to tuple
>>> yourTuple = (1, 'pear')
>>> print myTuple + yourTuple
(3, 5.8, 'apple', 1, 'pear')
>>> print yourTuple
(1, 'pear')
>>> del yourTuple
>>> print yourTuple
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'yourTuple' is not defined
List Types
Lists were first supported in Lisp and Scheme.
Ex: Python:
>>> myList = [1, 2.3, "three"]
>>> del myList[1]
>>> myList
[1, 'three']
>>> myList.insert(1,"orange")
>>> myList
[1, 'orange', 'three']
>>> myList.append("plum")
>>> myList
[1, 'orange', 'three', 'plum']
int main() {
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
Generates the following output:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf("Memory size occupied by data: %d\n", sizeof(data));
return 0;
}
Prints 20.
9. Subprograms
9.2.3 Parameters
Python Example / positional parameter passing
def sum(x, y, z):
return x + y + z
u = sum(a, b, c)
v = [3, 5, 6, 8]
u = sum(*v) # same as sum(3, 5, 6, 8)
int y;
int z;
int foo(int x) {
x = x + 5;
y = x;
x = x + 6;
return y;
}
void main(){
y = 4;
z = bar(y);
print(y, z);
}
// Pass-by-value-result: 15 15
// Pass-by-reference: 225 225
// Pass-by-value: 36 4
9.5.2.5. Pass-by-name
Example in Scala
https://alvinalexander.com/source-code/scala/simple-scala-
call-name-example
(Scala is a type-safe JVM language that incorporates both object oriented and functional programming)
CS 315 Examples 10
def square(x):
return x*x
def triple(x):
return 3*x
C++ Example
9.12. Closures
A JavaScript closure example:
http://dijkstra.cs.bilkent.edu.tr/~guvenir/closure.htm
CS 315 Examples 11
Python Example:
def make_adder(x):
def adder(y):
return x+y # x is captured from y.
return adder # make_adder returns inner function.
f = make_adder(3) # f is a function
print(f(5)) #prints 8
# 3 of the previous line is captured as x
C++ Example:
9.13. Coroutines
Not exactly a full-coroutine implementation, but a similar feature in Python, “generators” example:
def genPairs(n):
for i in range(0, n):
for j in range(i+1, n):
yield (i, j)
for p in genPairs(5):
print(p)
CS 315 Examples 12
SUBROUTINE X
INTEGER K, J
COMMON I
K=5
I=6
J=I+K
RETURN
END
The translator performs the following bindings for the main program:
I d[COMMON, 0]
J d[MAIN,1]
10 c[MAIN,3] CONTINUE statement
X c[X,0] first statement of X
And the following bindings for the subroutine X:
I d[COMMON, 0]
K d[X, 1]
J d[X, 2]
The linker then performs a further binding of addresses by combining the main program and the
subroutine X.
I D[0]
J D[2]
10 C[3]
X C[5]
And the following bindings for X:
I D[0]
K D[4]
J D[5]
CS 315 Examples 13
The contents of the memory will be as follows: