Académique Documents
Professionnel Documents
Culture Documents
When a programmer writes a program, he/she needs to write the instructions to store, process
and arrange data. Also, instructions are required to control the flow of the program. A
programmer needs to understand the following concepts to write a program:
3.2. Datatypes
Programs need data in the form of numbers, time, names, date, description etc.
sum = x+y
Here the two numbers are the data and the type of data (numeric data-integer, decimal etc.) is the
data type. In more elaborate terms, a data type used in a program determines the type of data,
memory needed for storing the data, and the kind of operation that can be performed with the
data (e.g. you can multiply two numbers together, you can concatenate alphabets and make it a
word and multiple words into a sentence.)
What can we infer from the figure above? We can see that different types of data like integer,
string, date etc. have been used in the form.
A datatype represents the type of data, memory storage and the operations that can be
performed using the data.
Data types are divided into primitive and composite types. The primitive data types are the basic
data types that are available in most of the programming languages.
Primitive data types are used to represent single values that include numeric types like integer or
float, boolean, character and string.
The data types that are derived from primary data types are known as non-primitive or composite
data types. These data types are used to store a group of values. Composite type includes Array,
Structure, Class etc.
Numeric type is divided into Integer type and Floating-point type. The table below shows the
division and examples for numeric types:
Numeric Types
The input data needed for a program and the output data generated by the program are stored in
the computer memory. While writing a program, the programmer needs to specify the memory
required for storing the data needed for the program and generated by the program. The memory
location where data is stored is called a variable. The program can change the data in that
memory location any number of times, and hence the name.
A program also needs a memory location where it can store data but cannot alter it later. Such
memory locations are called constant memory locations.
Consider a program that finds the area of a circle. The program takes radius (numeric) as an
input data to calculate the area. When user gives the input data, the program stores it in the
memory for further calculation. The program also stores the result (area of circle) after
calculation. This means that the program uses at least two memory locations (two variables); one
for storing the input (radius of circle) and one for storing the result (area of circle). You know
that Pi is a constant and has a fixed value (3.14). In this program the value of Pi can be stored as
a constant because the program cannot alter the value of Pi.
Program Steps:
A variable is a memory location whose value can change throughout the operation of a program.
A constant is a memory location whose associated value cannot be altered by the program during
its execution.
Initializing a variable
To declare or create a variable, the programmer needs to select an appropriate data type and a
meaningful name for the variable. The data type must be used only while declaring a variable.
data-type variable-name;
Initializing a variable means putting an initial value to the variable(bucket). A variable can be
initialized while creating or declaring it.
Once a variable is created, data can be stored in the variable. An assignment operator(=) is used
in the program to store data to a variable. The initial value of the variable can be changed by
assigning a new value using the assignment operator(=).
counter = 10;
gender = F;
Retrieving or fetching data from a variable
In the above program statement, the names of the variables (x and y) are used to retrieve the
values stored in the variables.
Operators are special symbols that perform specific operations on one or two operands, and then
return a result.
Consider a program that does mathematical operations like addition, subtraction, multiplication,
division on two numbers. (The program needs two variables to hold the two numeric values.)
int num1 ; // declares a variable num1 of type int to store the first numeric data.
int num2; // declares a variable num2 of type int to store the second numeric data.
int result; // declares a variable result of type int to store the result after operation.
result = num1 + num2; // add num1 and num2 and store the sum in variable result.
In the above program statements, num1 and num2 are the operands and + is the operator. The
sum of num1 and num2 is stored in the variable named result.
Operators can be classified into unary and binary operators. Unary operators are the operators
that deal with only one operand (one variable). Binary operators are the operators that deal with
two operands (variables or constants).
3.5. Control structures
Introduction
For example, every day a person drives his car from city A to city B through a straight national
highway to reach his office. One day, there is a big traffic jam on the way to city B. If the person
wants to reach city B then the he has to select an alternate route. Here changing route is equal to
changing the flow of program (controlling the flow) and the decision of selectiing an alternate
route will be based on some parameters like distance or condition of the road.
Control structures help to control the flow of a program.
Sequence, Selection and Repetition (Iteration) are the three main control structures used to
control the flow of program in any programming language.
Sequence:
Statements in the program will be executed one-by-one from the first to the last statement.
Selection:
The selection control structure allows one set of statements to be executed if a condition is true
and another set of statements to be executed if a condition is false.
The following are the common selection control structures use in programming languages.
if
if-else
switch
Repetition
Executing one or more steps of an algorithm or program based on some condition. The repetition
control structure is also known as the looping or iteration control structure.
The following are the common looping control structures use in programming languages.
while
do-while
for
Sequence, Selection and Repetition (Iteration) are the three main control structures used to
control the flow of program.
Introduction
Most of the programs deal with a group/collection of data. For example, list of bank account
numbers, exam scores, country names etc. Data could be primitive like integer or composite like
Date.
Program needs to arrange and manage these groups of data. All programming languages provide
one basic data structure named array, that helps to store and manage a group of data.
An array helps to store a collection of data (elements). Like the numbering used in the above
diagram, array uses an index to represent the location of each independent data stored in it.
The main ability of an array is to represent a group of data using a single name and accessing
each individual data stored in it using an index. In programming world, starting index of an array
will always be zero.
Arrays can be one dimensional, two dimensional or multi-dimensional. The figure given above
can be looked upon as a single dimensional array having a single row with 11 columns (0 10
seats).
Consider a program that needs to store the names of all the students participating in a quiz
program. The input data for the program is:
We need a variable to store the number of students and an array to store the names of students.
The general format for creating and initializing an array is given below.
Array Creation
Adding elements into an array
After creating an array, data can be added to it. For adding data to an array use the index of the
array. The general format for adding elements to an array is given below.
array_name[index] = value;
Use array index to retrieve data from an array.The general format of accessing data from an array
is given below:
variable_name = array_name[index];
Consider a program that stores the scores of the participants who attended a quiz and calculates
the average score of all participants.
The type of data(quiz score and average score) which we need to use in this program is numeric.
If the selected programming language is Java/C/C++, then we can select int or float as numeric
type. Lets select int for individual score and float for average score.
Assume the total number of participants as 100 and declare a constant named SIZE that stores
the total number of participants.
int quizScores[SIZE ];
For calculating the average score, iterate the array using for loop and calculate the sum and find
the average.
int totalScore= 0;
avgScore = totalScore/SIZE;
So we calculated the average score of all participants by storing individual score in an array and
iterating the array using a for loop.
Introduction
Functions are a named group of program statements that perform a specific task. Functions are
reusable sets of code useful to other programs. Each function is like a black box that takes input,
processes it and gives the result.
Programs or functions can call any function to perform a task. A main function is the function
that has the main control flow of a program. All other functions are called sub functions of a
program. In object oriented programing languages like java, functions are called methods.
Functions are a named group of instructions that perform a specific task.
Defining a function
What are the inputs (arguments/parameters) needed by the function to complete its task?
Does function return any result? If it returns, what kind of result (data) does it return?
Each function has two parts, header and body. Function header specifies the name of the
function, input parameters and the output type. The function body contains the logic of the
function.
// function body
Here return_type means the type of data(numeric , String,) the function will return after
executing the logic in the body part. If the function does not return any data but performs a task,
then the return type will be void (means no return_value).
Example:Function definition
Function Examples
Example1: Function that takes an input, performs a task and returns a result.
Example2: Function that takes an input, performs a task and returns no result.
Example3: Function that takes no input, performs a task and returns a result.
Example4: Function that takes no input, performs a task and returns no result.
void alert(){
The function alert takes no input, but performs a task via a function sendAlertMessage() and
does not return any output.
Calling/Invoking a function
The main function should know the name of the sub function and the arguments/inputs needed
by the sub function to invoke/call the sub function.
functionname([arguments]) ; or
alert();
store(Happy Bday);
Introduction
Programs not only use primitive data types but also composite data types like Date, String,
Employee, Student etc. Composite data types are constructed using primitive data types and
other composite data types. Composite data types can be built-in data types (e.g. String or Date)
or programmer defined data types (e.g. Student, Employee).
Consider a program that stores the details of a group of students. Here each student has data like
Id, name, age, college, stream, and grade.
Every programming language provides a way to define and use composite data types.
C programming language provides keywords like typedef and struct to define a composite data
type. Object oriented programming language like Java provides a keyword named Class to create
a composite data type.
C program
typedef struct {
int id;
char college[100];
char stream[25]
char grade;
} Student;
Java program
class Student{
int id;
String name;
String college;
String stream;
char grade;
};
Both these programs define a new type Student, where Id, name, college, stream, grade are the
members (data members) or properties of Student type.
Composite variables are created like primitive variables. A composite variable consists of a fixed
number of variables "glued together".
The example below shows how to declare and initialize composite variables.
A special operator named dot operator (.) is used to access data member of a composite data.
Here stud1 and stud2 are variables that store composite data.
Composite data types can be derived from an arbitrary number of primitive data types
and composite data types.
We give a first example. Two int-numbers are combined building the new data type
rational:
rational p;
The names of the components are used to access them:
p.n = 3;
p.d = 4; // represents the number 3/4
Here is the general syntax:
struct name {
component1 ;
component2 ;
...
componentn ;
}
A component is (in this case) a definition of a variable or an array without
initialization. The type can be primitive or composite.
#include <iostream.h>
struct rational {
int n; // nominator
int d; // denominator
} ;
t.n = n; t.d = d;
return t;
}
void main ()
{
rational p=con_rat(3,4);
rational q=con_rat(5,3);
rational r;
pri_rat(p); pri_rat(q);
r = sub_rat(add_rat(mul_rat(p,q),p),mul_rat(p,p));
pri_rat(r);
}
The output of the program is:
3/4
5/3
1104/768
We see, the fraction is not reduced. We may get an overflow sooner
than necessary.
Within all functions we used con_rat to construct a rational number, so we choose this
function to normalize the fraction:
Or we like to mix rational and complex numbers. As long as we use rationals we stay
within them. If we combine rational and complex numbers, we first convert the
rational to a complex.
We present a variant using labeled data, i.e. every number has a label according to its
type.
union name {
component1 ;
component2 ;
...
componentn ;
}
This type of composite data can contain each of the types it is composed of, but
only one of them at a time. In general the data of each component is stored at the
same place.
Labeled data can be realized as unions, where every component is composite (struct
starting with the same data type, the label.
Example:
enum state = { old, new, whatever };
state x=whatever;
Program 2.31 (Mixed arithmetic, first) mixed1.cc
#include <iostream.h>
struct rational {
type a;
int n;
int d;
} ;
struct complex {
type a;
float re;
float im;
} ;
union mixed {
rational p;
complex c;
} ;
t.p.a = type_rational;
t.p.n = n; t.p.d = d;
return t;
}
t.p.a = type_complex;
t.c.re = re; t.c.im = im;
return t;
}
void main ()
{
mixed p=con_rat(3,4);
mixed z=con_com(3.14,0.66);
mixed r;
print(p); print(z);
r = add(p,z);
print(r);
}
This solution has some drawbacks:
Every arithmetic operation contains knowledge about all variants used. Each
time a new variant is added, all functions have to be modified.
Arrays
An array is a container object that holds a fixed number of values of a single type. The length of
an array is established when the array is created. After creation, its length is fixed. You have seen
an example of arrays already, in the main method of the "Hello World!" application. This section
discusses arrays in greater detail.
An array of 10 elements.
Each item in an array is called an element, and each element is accessed by its numerical index.
As shown in the preceding illustration, numbering begins with 0. The 9th element, for example,
would therefore be accessed at index 8.
The following program, ArrayDemo, creates an array of integers, puts some values in the array,
and prints each value to standard output.
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
You can also place the brackets after the array's name:
int[] anArray = {
100, 200, 300,
400, 500, 600,
700, 800, 900, 1000
};
Here the length of the array is determined by the number of values provided between braces and
separated by commas.
You can also declare an array of arrays (also known as a multidimensional array) by using two or
more sets of brackets, such as String[][] names. Each element, therefore, must be accessed by
a corresponding number of index values.
In the Java programming language, a multidimensional array is an array whose components are
themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows
are allowed to vary in length, as shown in the following MultiDimArrayDemo program:
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}
};
// Mr. Smith
System.out.println(names[0][0] + names[1][0]);
// Ms. Jones
System.out.println(names[0][2] + names[1][1]);
}
}
The output from this program is:
Mr. Smith
Ms. Jones
Finally, you can use the built-in length property to determine the size of any array. The
following code prints the array's size to standard output:
System.out.println(anArray.length);
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one
array into another:
The following program, ArrayCopyDemo, declares an array of char elements, spelling the word
"decaffeinated." It uses the System.arraycopy method to copy a subsequence of array
components into a second array:
class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
caffein
Array Manipulations
Arrays are a powerful and useful concept used in programming. Java SE provides methods to
perform some of the most common manipulations related to arrays. For instance, the
ArrayCopyDemo example uses the arraycopy method of the System class instead of manually
iterating through the elements of the source array and placing each one into the destination array.
This is performed behind the scenes, enabling the developer to use just one line of code to call
the method.
For your convenience, Java SE provides several methods for performing array manipulations
(common tasks, such as copying, sorting and searching arrays) in the java.util.Arrays class.
For instance, the previous example can be modified to use the copyOfRange method of the
java.util.Arrays class, as you can see in the ArrayCopyOfDemo example. The difference is
that using the copyOfRange method does not require you to create the destination array before
calling the method, because the destination array is returned by the method:
class ArrayCopyOfDemo {
public static void main(String[] args) {
System.out.println(new String(copyTo));
}
}
As you can see, the output from this program is the same (caffein), although it requires fewer
lines of code. Note that the second parameter of the copyOfRange method is the initial index of
the range to be copied, inclusively, while the third parameter is the final index of the range to be
copied, exclusively. In this example, the range to be copied does not include the array element at
index 9 (which contains the character a).
Some other useful operations provided by methods in the java.util.Arrays class, are:
Searching an array for a specific value to get the index at which it is placed
(the binarySearch method).
Comparing two arrays to determine if they are equal or not (the equals
method).
Filling an array to place a specific value at each index (the fill method).
Sorting an array into ascending order. This can be done either sequentially,
using the sort method, or concurrently, using the parallelSort method
introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor
systems is faster than sequential array sorting.