0% found this document useful (0 votes)
13 views17 pages

Data and Datatypes

The document discusses datatypes, variables, operators, control structures, and arrays in programming. It defines what datatypes are and how they classify data. It also explains what variables and constants are, how they are declared and used. The different types of operators and control structures like sequence, selection, and repetition are outlined. Finally, it describes what arrays are and how they can store and manage groups of data using indexes.

Uploaded by

Shanmuga Nathan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views17 pages

Data and Datatypes

The document discusses datatypes, variables, operators, control structures, and arrays in programming. It defines what datatypes are and how they classify data. It also explains what variables and constants are, how they are declared and used. The different types of operators and control structures like sequence, selection, and repetition are outlined. Finally, it describes what arrays are and how they can store and manage groups of data using indexes.

Uploaded by

Shanmuga Nathan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

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.
Let’s 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 B’day”);

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.

You might also like