Vous êtes sur la page 1sur 31

3.1.

Introduction to basic programming concepts

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:

What is a data type and how to use a data type?

What is a variable and its use?

How to control the flow of the program?

How to arrange and use a group of data?

How to group a set of instructions into a single unit?

How to create new data types?

A program is a sequence of instructions (written using a programming language) for


machine/computer to accomplish a task. A textual explanation of squence of instructions is
called an algorithm or pseudocode.

3.2. Datatypes

Data and Datatypes

Programs need data in the form of numbers, time, names, date, description etc.

Consider a program to calculate the sum of two numbers.

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.

Classifying data types

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.

Basic Data Types

Numeric type is divided into Integer type and Floating-point type. The table below shows the
division and examples for numeric types:

Numeric Types

Datatypes are mainly classified into primitve and composite types.

3.3. Introduction to variables

Variables and Constants

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:

Declare a variable radius to store radius of the circle.

Declare a variable area to store the area of the circle.

Declare a constant Pi to store the constant value.

Calculate the area of circle ( Pi* radius* radius).


Store the result in variable area.

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.

Actions using Variables

Following are the actions that a programmer can do using a variable:

Declaring or creating a variable

Initializing a variable

Storing data to a variable

Retrieving or fetching data from a variable

Declaring or Creating 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.

The general format for declaring a variable is :

data-type variable-name;

Eg: int counter; String name;


Initializing a variable

Initializing a variable means putting an initial value to the variable(bucket). A variable can be
initialized while creating or declaring it.

Eg: int counter=0; char gender='M';

Storing data to a variable

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

To retrieve or fetch data from a variable, use the name of variable.

int x = 10; int y= 20;

int sum = x+y;

In the above program statement, the names of the variables (x and y) are used to retrieve the
values stored in the variables.

Always initialize a variable while declaring or after declaring it.

3.4. Introduction to Operators

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

A program is a set of instructions or commands given to a computer to do a specific activity or


task. The normal execution flow of program statements will be sequential. Sometimes the
sequential flow should be altered because of some conditions which change the flow.

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.

Types of control structures

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.

3.6. Introduction to Arrays

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:

Number of students participating in the quiz

Names of the students

We need a variable to store the number of students and an array to store the names of students.

int count; //variable to store number of students

String nameArray[count]; // array to store names of students

An array is used to store a group of data of similar type.

Create and Use an Array

Creating and initializing an array

The general format for creating and initializing an array is given below.

datatype array_name[ ] = {value1 , value 2 , value3};

Eg. int nums_array[ ]={11, 22, 33,44,55} ;

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;

Eg. nums_array[0] = 88;

Retrieving data from an array

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];

Eg. num1 = nums_array[4];

Array creation example

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.

const int SIZE = 100;

Create an array to store the scores of 100 participants.

int quizScores[SIZE ];

Add participant score to the array (index starts from 0).

quizScores[0] = 25; quizScores[1] = 30; ...

For calculating the average score, iterate the array using for loop and calculate the sum and find
the average.
int totalScore= 0;

float avgScore =0.0;

/* iterate the array */

for (int i=0 ; i<SIZE ; i++) {

totalScore = totalScore + quizScores[i];

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.

3.7. Introduction to Functions

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

The following questions help to define a function:

What specific task needs to be performed by the function (body)?

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.

The general format of a function is as follows.

return_type functionName( [datatype parameter1, datatype parameter1, ]){

// 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(){

sendAlertMessage( Low Resource);

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.

The common syntax for invoking a sub function is:

functionname([arguments]) ; or

result = function_name([arguments]); //store result in a variable, if function return some data


float result = avg(10,20,30);

int count= getCount();

alert();

store(Happy Bday);

3.8. Composite Datatypes

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.

The program requires:

A new data type, which represents a student

An array, which can store the student details

Defining data type

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 name[50]; // C language use character array as string

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.

Creating a variable of composite 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.

Student stud1 ={ 100, John ,SNC,EC,A}; //structure in C

Student stud2 = new Student( 101,Rohit,MIT,CS,A); // object in Java


Accessing data members

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.

char[ ] name = stud1.name;

String college = stud2.college

Composite variable consists of a fixed number of variables glued together.


Extra:

Composite data types


Up to now we have used only simple data types. In this section we discuss a new
feature of C++. One can derive new data type by composition: composite data types.

Composite data types can be derived from an arbitrary number of primitive data types
and composite data types.

Composite data types are called structs.

We give a first example. Two int-numbers are combined building the new data type
rational:

struct rational { // key word struct + name


int n; // a number of data types
int d; // with semicolon
} ;
Defining a variable, the new data type is used like the built-in ones:

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:

Syntax 2.27 (Composite data types)

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.

Program 2.28 (Rational numbers, first) rational1.cc

#include <iostream.h>

struct rational {
int n; // nominator
int d; // denominator
} ;

rational con_rat (int n, int d)


{
rational t;

t.n = n; t.d = d;
return t;
}

rational add_rat (rational p, rational q)


{
return con_rat(p.n*q.d+q.n*p.d,p.d*q.d);
}

rational sub_rat (rational p, rational q)


{
return con_rat(p.n*q.d-q.n*p.d,p.d*q.d);
}

rational mul_rat (rational p, rational q)


{
return con_rat(p.n*q.n,p.d*q.d);
}

rational div_rat (rational p, rational q)


{
return con_rat(p.n*q.d,p.d*q.n);
}

void pri_rat (rational p)


{
cout << p.n << '/' << p.d << endl;
}

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:

rational con_rat (int n, int d)


{
rational t;

if (n*d<0) // normalize sign


{
n=-abs(n); d=abs(d);
}
else
{
n=abs(n); d=abs(d);
}
int g=LCD(abs(n),d); // reducing
t.n = n/g; t.d = d/g;
return t;
}
Suppose, we want to use rational and complex numbers. We could proceed in the
same way.

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.

C++ provides functionality to deal with mixed arithmetic.


For every combination we could provide a different function. This is very tedious.

We present a variant using labeled data, i.e. every number has a label according to its
type.

Firstly we consider a variant of the composite data type:

Syntax 2.29 (Variant structure)

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.

Often it is convenient to choose labels of enumeration type:

Syntax 2.30 (Enumeration type)

enum name { name1 , name2 , ..., namen } ;

An enumeration type is a finite set.

Example:
enum state = { old, new, whatever };
state x=whatever;
Program 2.31 (Mixed arithmetic, first) mixed1.cc

#include <iostream.h>

enum type {type_rational, type_complex};

struct rational {
type a;
int n;
int d;
} ;

struct complex {
type a;
float re;
float im;
} ;

union mixed {
rational p;
complex c;
} ;

mixed con_rat (int n, int d)


{
mixed t;

t.p.a = type_rational;
t.p.n = n; t.p.d = d;
return t;
}

mixed con_com (float re, float im)


{
mixed t;

t.p.a = type_complex;
t.c.re = re; t.c.im = im;
return t;
}

mixed convert (mixed z)


{
if (z.c.a==type_complex) return z;
mixed t;
t.c.a = type_complex;
t.c.re = z.p.n;
t.c.re = t.c.re/z.p.d; // floating point division
t.c.im = 0.0;
return t;
}

mixed add (mixed a, mixed b)


{
if (a.p.a==type_rational && b.p.a==type_rational)
return con_rat(a.p.n*b.p.d+b.p.n*a.p.d,a.p.d*b.p.d);
if (a.p.a==type_rational)
a = convert(a);
if (b.p.a==type_rational)
b = convert(b);
return con_com(a.c.re+b.c.re,a.c.im+b.c.im);
}

void print (mixed a)


{
if (a.p.a==type_rational)
cout << a.p.n << '/' << a.p.d << endl;
if (a.c.a==type_complex)
cout << a.c.re << "+i*" << a.c.im << endl;
}

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 variable of type mixed needs the same amount of memory.

Every arithmetic operation contains knowledge about all variants used. Each
time a new variant is added, all functions have to be modified.

In the section about object-oriented programming we address this problem again.

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;

// allocates memory for 10 integers


anArray = new int[10];

// initialize first element


anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;

System.out.println("Element at index 0: "


+ anArray[0]);
System.out.println("Element at index 1: "
+ anArray[1]);
System.out.println("Element at index 2: "
+ anArray[2]);
System.out.println("Element at index 3: "
+ anArray[3]);
System.out.println("Element at index 4: "
+ anArray[4]);
System.out.println("Element at index 5: "
+ anArray[5]);
System.out.println("Element at index 6: "
+ anArray[6]);
System.out.println("Element at index 7: "
+ anArray[7]);
System.out.println("Element at index 8: "
+ anArray[8]);
System.out.println("Element at index 9: "
+ anArray[9]);
}
}
The output from this program is:

Element at index 0: 100


Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
In a real-world programming situation, you would probably use one of the supported looping
constructs to iterate through each element of the array, rather than write each line individually as
in the preceding example. However, the example clearly illustrates the array syntax. You will
learn about the various looping constructs (for, while, and do-while) in the Control Flow
section.

Declaring a Variable to Refer to an Array


The preceding program declares an array (named anArray) with the following line of code:

// declares an array of integers


int[] anArray;
Like declarations for variables of other types, an array declaration has two components: the
array's type and the array's name. An array's type is written as type[], where type is the data type
of the contained elements; the brackets are special symbols indicating that this variable holds an
array. The size of the array is not part of its type (which is why the brackets are empty). An
array's name can be anything you want, provided that it follows the rules and conventions as
previously discussed in the naming section. As with variables of other types, the declaration does
not actually create an array; it simply tells the compiler that this variable will hold an array of the
specified type.

Similarly, you can declare arrays of other types:

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:

// this form is discouraged


float anArrayOfFloats[];
However, convention discourages this form; the brackets identify the array type and should
appear with the type designation.

Creating, Initializing, and Accessing an Array


One way to create an array is with the new operator. The next statement in the ArrayDemo
program allocates an array with enough memory for 10 integer elements and assigns the array to
the anArray variable.

// create an array of integers


anArray = new int[10];
If this statement is missing, then the compiler prints an error like the following, and compilation
fails:

ArrayDemo.java:4: Variable anArray may not have been initialized.


The next few lines assign values to each element of the array:

anArray[0] = 100; // initialize first element


anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth
Each array element is accessed by its numerical index:

System.out.println("Element 1 at index 0: " + anArray[0]);


System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array:

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:

public static void arraycopy(Object src, int srcPos,


Object dest, int destPos, int length)
The two Object arguments specify the array to copy from and the array to copy to. The three int
arguments specify the starting position in the source array, the starting position in the destination
array, and the number of array elements to copy.

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];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);


System.out.println(new String(copyTo));
}
}
The output from this program is:

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) {

char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e',


'i', 'n', 'a', 't', 'e', 'd'};

char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);

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.

Vous aimerez peut-être aussi