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

CPCS301 Topic6 Data Types and Functions Updated(1)

This document covers data types and functions in C, PHP, Python, and MATLAB. It explains fundamental and derived data types, typecasting, and provides examples of function definitions and calls in each language. The objective is to familiarize students with the implementation of codes using various data types across these programming languages.

Uploaded by

rkomosany
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)
2 views

CPCS301 Topic6 Data Types and Functions Updated(1)

This document covers data types and functions in C, PHP, Python, and MATLAB. It explains fundamental and derived data types, typecasting, and provides examples of function definitions and calls in each language. The objective is to familiarize students with the implementation of codes using various data types across these programming languages.

Uploaded by

rkomosany
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/ 13

Topic 06: Data Types and Functions

Objective
Knowing and learn about different data types in C, PHP, Python and Matlab languages

Current Lab Learning Outcomes (LLO)


Students should get familiar with:
1. Data Types in the four languages.
2. Implementing codes using different data types in C, Python, PHP and MATLAB.

Lab Description

Data Types

Data types simply refers to the type and size of data associated with variables and functions. Every
programming language has its own data type.

1. C Language
a) C’s Data Types
In C programming, variables (memory location) should be declared before it can be used. Similarly, a
function also needs to be declared before use. Data type can be either fundamental (provided in C compiler),
or derived (derived from fundamental data types ex: Array).

Fundamental data types


Data types Description Example
Int Integers are whole numbers that can have both zero, 0, -5, 10
positive and negative values but no decimal values.
float and float and double are used to hold real numbers. float salary;
double double price;
What's the difference between float and double?
The size of float (single precision float data type) is 4
bytes. And the size of double (double precision float data
type) is 8 bytes.
Char Keyword char is used for declaring character type char test = 'h';
variables. The size of character variable is 1 byte.
Void void is an incomplete type. It means "nothing" or "no
type". You can think of void as absent.
Data types Description Example
For example, if a function is not returning anything, its
return type should be void.
Note that, you cannot create variables of void type.
short If you need to use large number, you can use type long a;
and long specifier long. In the example, variable a can store integer long double c;
values and c can store a floating-point number.
If you are sure, only a small integer ([−32,767, short d;
+32,767] range) will be used, you can use short.
signed and In C, signed and unsigned are type modifiers. You can unsigned int x;
unsigned alter the data storage of a data type by using them. In the int y;
example, the variable x can hold only zero and positive
values because we have used unsigned modifier.

The following table shows the difference between float, double and long double. You can always check
size of a variable using sizeof() operator.

Type Storage size Precision

Float 4 byte 6 decimal places

Double 8 byte 15 decimal places

long double 10 byte 19 decimal places

b) Typecasting in C
Type casting is a way to convert a variable from one data type to another data type. For example, if you want
to store a long value into a simple integer then you can typecast long to int. There are two types of type
casting in C language which are implicit and explicit conversions.

#include <stdio.h>
int main ()
{
int i=20;
double p;
p=i; //Implicit conversion (int to float)
printf("%f\n",p);
float y=11/2;
int x = (int) y; //Explicit conversion (float to int)
printf("%d",x);
}

2. Python
a) Python’s Data Types
1. boolean: the type of the built-in values True and False. Useful in conditional expressions, and anywhere
else you want to represent the truth or falsity of some condition.
2. Numeric types:
a. int: Integers; equivalent to C longs. Integers are unbounded in Python (they can grow as large as
the memory of your computer allows).
b. long: Long integers of non-limited length.
c. float: Floating-Point numbers, equivalent to C doubles.
3. Sequences:
a. str: String; Strings can be either single (‘ ‘), double (“ “) or triple (‘’’ ‘’’ or “”” “””) quoted
strings. The difference is in that single and double quoted strings cannot span more than one line.

' Text '


" Text "

'''Text'''
""" Text """

triple_quoted_string_single = '''This is a string


that spans multiple lines.
Python allows this feature.'''
print(triple_quoted_string_single)

Output:
This is a string
that spans multiple lines.
Python allows this feature.

Notes:
• You can use the opposite quotes inside a String.
• You can use the escape character, ’\’ (same as Java).
• Strings are immutable (cannot be changed after creation).
• Concatenation is done with the “+” operator.
• There is no char type in Python, just Strings of length one.
Example:

What's wrong with saying "Hello"?

Substrings:
• Indexing for Strings starts at 0. Example: s = “0123456789”
Description Indexing Example Output
To access character in index ‘i' s[i] s[3] “3”
To access a substring starting at index ‘i' and end at index ‘j-1’ s[i:j] s[2:5] “234”
To access a substring starting at index ‘i' till the string end s[i:] s[3:] “3456789”
To access a substring starting at index ‘0' and end at index ‘j- s[:j] s[:5] “01234”
1’
To return the length of a string len(string) len(s) 10

Note: Python support negative indexing starting from the last character with index ‘-1’ then ‘-2’
….to the first character with index ‘- string length’. It will be discussed in detail while covering
‘List’

b) Typecasting in Python

Casting in python is done using constructor functions:

• int() - constructs an integer number from an integer literal, a float literal (by rounding down to
the previous whole number), or a string literal (providing the string represents a whole
number)
• float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer literals
and float literals
• bool()

Examples:

Casted type Example


Integers x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Floats x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Strings x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Boolean a = bool("") # a will be False
b = bool("good") # b will be True
c = bool(0) # c will be False
d = bool(3.0) # d will be True
e = bool(“False”) # e will be True

The format Method:


Sometimes we may want to construct strings from other information. This is where the format() method
is useful.
How It Works?
A string can use certain specifications and subsequently, the format method can be called to substitute
those specifications with corresponding arguments to the format method.
A positional parameter of the format method can be accessed by placing the index of the parameter after
the opening brace, e.g. {0} accesses the first parameter, {1} the second one and so on.

3) PHP Language
a) PHP’s Data Types
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array and Objects
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example Output
<?php Hello world!
$x = "Hello world!"; Hello world!
$y = 'Hello world!';
echo $x;
echo "\n";
echo $y;
?>

In PHP, the operator used to concatenate (combine) two strings is the dot (.) operator.

<?php
$str1 = "Hello";
$str2 = "World!";
$result = $str1 . " " . $str2;
echo $result; // Output: Hello World!
?>
PHP Integer
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with
0x) or octal (8-based - prefixed with 0)

In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
Example Code Output
<?php int(5985)
$x = 5985;
var_dump($x);
?>

PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
In the following example $x is a float. The PHP var_dump() function returns the data type and value:
Example Code Output
<?php float(10.365)
$x = 10.365;
var_dump($x);
?>

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true; $y = false;
Booleans are often used in conditional testing. You will learn more about conditional testing later.

PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
Example Output
<?php array(3) { [0]=> string(5) "Volvo" [1]=>
$cars = array("Volvo","BMW","Toyota"); string(3) "BMW" [2]=> string(6) "Toyota" }
var_dump($cars);
?>

b) Typecasting in PHP:
Type casting in PHP works same as C programming. Desired data type name with parenthesis before the variable
which we need to cast. We can cast following data type variable in PHP

• (int), (integer) - cast to integer


• (bool), (boolean) - cast to boolean
• (float), (double), (real) - cast to float
• (string) - cast to string
Examples:

<?php
//casting to integer
$bool_false = false;
$int_val = (int) $bool_false ;
var_dump($int_val); //Output will be int(0)
$bool_true = true;
$int_val = (integer) $bool_true ;
var_dump($int_val); //Output will be int(1)
?>

<?php
//casting to integer
$float_num = 10.9;
echo (int) $float_num; //Output will be int(10)
?>

<?php
//casting to Boolean
var_dump((bool) 1); //return true
var_dump((bool) 0);//return false
var_dump((bool) "");//return false
var_dump((bool) "ank");//return true
?>

Note:
We can convert any data type to string using (string). In most of the cases, the value is not changed. But for
boolean false converted into “” and true in “1”. Below is the example
<?php
//casting to string
$boo_true = true;
var_dump((string) $boo_true); // Output will be "1"
var_dump((string) false) ; //Output will be ""
var_dump((string) 1); //output will be “1”
?>
4) MATLAB Data Types:
To construct variables, MATLAB has a total of 15 fundamental data types. Every data type stores data that is in
the form of a matrix or array.

The following table shows the most commonly used data types in MATLAB −

Data Type Description


int8 8-bit signed integer
uint8 8-bit unsigned integer
int16 16-bit signed integer
uint16 16-bit unsigned integer
int32 32-bit signed integer
uint32 32-bit unsigned integer
int64 64-bit signed integer
uint64 64-bit unsigned integer
Single single precision numerical data
Double double precision numerical data
Logical logical values of 1 or 0, represent true and false respectively
Char character data (strings are stored as vector of characters)
array of indexed cells, each capable of storing an array of a different dimension
cell array
and data type
C-like structures, each structure having named fields capable of storing an array
Structure
of a different dimension and data type
function handle pointer to a function
user classes objects constructed from a user-defined class
java classes objects constructed from a Java class

The output:
Functions:
1-Functions in C:
A function is a group of statements that together perform a task. Every C program has at least one function,
which is main(), and all the most trivial programs can define additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.

Defining a Function
The general form of a function definition in C programming language is as follows −

return_type function_name( parameter list ) {

body of the function

Example
Given below is the source code for a function called max(). This function takes two parameters num1 and
num2 and returns the maximum value between the two −

/* function returning the max between two numbers */

int max(int num1, int num2) {

/* local variable declaration */

int result;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

Calling a Function
To use a function, you will have to call that function to perform the defined task. To call a function, you
simply need to pass the required parameters along with the function name, and if the function returns a value,
then you can store the returned value. For example: if we call the previous function:

#include <stdio.h>

int main () {

/* local variable definition */

int a = 100;
int b = 200;

int ret;

/* calling a function to get max value */

ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;

2- Functions in Python

Let’s learn how to write function in python by example, start by defining a function fahr_to_celsius that
converts temperatures from Fahrenheit to Celsius:

def fahr_to_celsius(temp):
return ((temp - 32) * (5/9))

The function definition opens with the keyword def followed by the name of the function (fahr_to_celsius)
and a parenthesized list of parameter names (temp). The body of the function — the statements that are
executed when it runs — is indented below the definition line. The body concludes with a return keyword
followed by the return value.
When we call the function, the values we pass to it are assigned to those variables so that we can use them
inside the function. Inside the function, we use a return statement to send a result back to whoever asked for
it.
Let’s try running our function.

fahr_to_celsius(32)

This command should call our function, using “32” as the input and return the function value.
In fact, calling our own function is no different from calling any other function:

print('freezing point of water:', fahr_to_celsius(32), 'C')


print('boiling point of water:', fahr_to_celsius(212), 'C')
freezing point of water: 0.0 C
boiling point of water: 100.0 C
3- Function in PHP

PHP functions are similar to other programming languages. It is very easy to create your own PHP function.
Suppose you want to create a PHP function which will simply write a simple message on your browser when
you will call it. Following example creates a function called writeMessage() and then calls it just after
creating it.
Note that while creating a function its name should start with keyword function and all the PHP code should
be inside { } braces as shown in the following example below:

<?php

/* Defining a PHP Function */

function writeMessage() {

echo "You are really a nice person, Have a nice time!";

/* Calling a PHP Function */

writeMessage();

?>

This will display following result:


You are really a nice person, Have a nice time!

Example 1:

<?php

function addFunction($num1, $num2) {

$sum = $num1 + $num2;

echo "Sum of the two numbers is : $sum";

addFunction(10, 20);

?>

This will display following result:


Sum of the two numbers is : 30
Example 2:
A function with a return a value.
In PHP, you define a function using the function keyword. You can specify a return value using the return
keyword inside the function.

<?php

function addFunction($num1, $num2) {

$sum = $num1 + $num2;

return $sum;

$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";

?>

This will display following result:


Returned value from the function : 30

Extra (supplementary) Materials (if any)

Provide extra references or more materials for the covered topics.

You might also like