CPCS301 Topic6 Data Types and Functions Updated(1)
CPCS301 Topic6 Data Types and Functions Updated(1)
Objective
Knowing and learn about different data types in C, PHP, Python and Matlab languages
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).
The following table shows the difference between float, double and long double. You can always check
size of a variable using sizeof() operator.
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 """
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:
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
• 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:
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
<?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 −
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 −
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 −
int result;
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 () {
int a = 100;
int b = 200;
int 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:
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
function writeMessage() {
writeMessage();
?>
Example 1:
<?php
addFunction(10, 20);
?>
<?php
return $sum;
?>