SlideShare a Scribd company logo
C-Data Types,
Arrays and Structs
PREPARED BY SAAD SHAIKH.
Data Types
 The basic definition of a data type is a data storage
format that can contain a specific type or range of
values.
 When computer programs store data in variables, each
variable must be assigned a specific data type.
Types of Data Types
 Primary Data Types
 They are arithmetic types and are further classified into:
(a) Integer types, (b) Character and (c) Floating-point types.
 Derived Data Types:
 They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union
types and (e) Function types.
 User Defined Data Types:
 They include TypeDef and ENUM.
Integer Type
 Integers are a commonly used data type in computer programming. An
integer is a whole number (not a fraction) that can be positive, negative, or
zero.
 It is denoted by “int” .
Type Storage Size Value Range
Int 2 or 4 bytes -32,768 to 32,767 or -
2,147,483,648 to
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to
4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to
2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Floating Point Type
 As the name implies, floating point numbers are numbers that contain
floating decimal points. For example, the numbers 5.5, 0.001, and -
2,345.6789 are floating point numbers.
 Denoted by keyword “float”.
Type Storage size Value Range Precision
float 4 byte 1.2E-38 to
3.4E+38
6 decimal places
double 8 byte 2.3E-308 to
1.7E+308
15 decimal places
long double 10 byte 3.4E-4932 to
1.1E+4932
19 decimal places
Character Data Types
 Character data type allows a variable to store only one character.
 “char” keyword is used to refer character data type.
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Example Code:
#include <stdio.h>
void main()
{
int i = 20;
float f = 3.1415;
char c;
c = 'd';
printf("This is my float: %f n", f);
printf("This is my integer: %d n", i);
printf("This is my character: %c n", c);
}
VOID DATA TYPE
 The void type has no values therefore we cannot declare it as variable as we
did in case of integer and float.
 The void data type is usually used with function to specify its type.
User Defined Data Types
 User defined data types are those data types which are created by the
user to characterize the existing data types.
 This user defined data type can later be used to declare variables.
 In other words we are redefining the name of existing data types.
User Defined Data Types-Enum:
 An enumeration is a user-defined data type consists of integral constants and
each integral constant is give a name. Keyword enum is used to defined
enumerated data type.
 Syntax: enum type_name{ value1, value2,...,valueN };
 Here, type_name is the name of enumerated data type or tag. And value1,
value2,....,valueN are values of type type_name.
 By default, value1 will be equal to 0, value2 will be 1 and so on but, the
programmer can change the default value.
Example:
#include<stdio.h>
#include<conio.h>
Enum Weekday
{
Sun,Mon,Tues,Wed,Thus,Fri,Sat
};
Int main ()
{
enum Weedkday wd;
wd = Thus;
printf(“%d”,wd):
}
4
Output
User Defined Data Types-typedef
The C programming language provides a keyword called typedef, which you can
use to give a type, a new name.
 Syntax:
typedef <type><identifier>;
 Example:
typedef int score;
Score player1,player2;
Derived Data Types: ARRAY
 Array is a kind of data structure that can store a fixed-size sequential collection
of elements of the same type.
 An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type.
 All arrays consist of contiguous memory locations.
First Element Last Element
a[1]a[0] a[2] a[3] a[4] a[5] a[6] a[7] a[n]
Declaring Arrays
 To declare an array in C, a programmer specifies the type of the elements
and the number of elements required by an array as follows :
type arrayName [ arraySize ];
 For example we can declare a 10 element array like:
int marks [10];
Initializing Array
 We can initialize an array in C either one by one or using a single
statement as follows:
double price[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
 The number of values between braces { } cannot be larger than the
number of elements that we declare for the array between square brackets
[ ].
Example:
#include <stdio.h>
int main ()
{
int n[ 10 ];
/* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100;
/* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %dn", j, n[j] );
}
return 0;
}
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Output
Multidimensional Arrays
 Array having more than one subscript variable is called multidimensional array.
 Multidimensional array is also called as matrix
 To declare a two-dimensional integer array of size [x][y], you would write
something as follows:
type arrayName [ x ][ y ];
 To initialize multidimensional array we specify bracketed value of each row; for
example:
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
Example:
#include <stdio.h>
int main () {
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8} };
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %dn", i,j, a[i][j] );
}
}
return 0;
}
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
Output :
Structures
 Arrays allow to define type of variables that can hold several data items of the
same kind. Similarly structure is another user defined data type available in C
that allows to combine data items of different kinds.
 Structures are used to represent a record. Suppose you want to keep track of
your books in a library.
You might want to track the following attributes about each book like:
Title
Author
Subject
Book ID
Defining Structures
 To define a structure, you must use
the struct statement.
 The format is as follows:
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
Example:
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
}
book;
Accessing Structure Members
 To access any member of a structure, we use the member access operator
(.).
Example:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;};
int main( )
{
struct Books Book; /* Declare Book of type Book */
/* book specification */
strcpy( Book.title, "C Programming");
strcpy( Book.author, "Aptech");
strcpy( Book.subject, "C Programming");
Book.book_id = 6495407;
/* print Book info */
printf( "Book title : %sn", Book.title);
printf( "Book author : %sn", Book.author);
printf( "Book subject : %sn", Book.subject);
printf( "Book book_id : %dn", Book.book_id);
return 0;
}
Book title : C Programming
Book author : Aptech
Book subject : C Programming
Book book_id : 6495407
Output :
Thank you..
Ad

More Related Content

What's hot (20)

Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
String in c programming
String in c programmingString in c programming
String in c programming
Devan Thakur
 
C keywords and identifiers
C keywords and identifiersC keywords and identifiers
C keywords and identifiers
Akhileshwar Reddy Ankireddy
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
Data types in C
Data types in CData types in C
Data types in C
Tarun Sharma
 
Data types
Data typesData types
Data types
Nokesh Prabhakar
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
C tokens
C tokensC tokens
C tokens
Manu1325
 
Arrays in c
Arrays in cArrays in c
Arrays in c
Jeeva Nanthini
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
Data types
Data typesData types
Data types
Syed Umair
 
C++ string
C++ stringC++ string
C++ string
Dheenadayalan18
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
MohammadSalman129
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
programming9
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
Way2itech
 
Functions in c
Functions in cFunctions in c
Functions in c
sunila tharagaturi
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Strings
StringsStrings
Strings
Mitali Chugh
 

Similar to C data types, arrays and structs (20)

Programming Fundamentals lecture 6
Programming Fundamentals lecture 6Programming Fundamentals lecture 6
Programming Fundamentals lecture 6
REHAN IJAZ
 
Arrays
ArraysArrays
Arrays
RaziyasultanaShaik
 
data types in c programming language in detail
data types in c programming language in detaildata types in c programming language in detail
data types in c programming language in detail
atulk4360
 
Data types
Data typesData types
Data types
Sachin Satwaskar
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
AnirudhaGaikwad4
 
Arrays in c
Arrays in cArrays in c
Arrays in c
vampugani
 
C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
HNDE Labuduwa Galle
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
Mohammad Imam Hossain
 
Session 4
Session 4Session 4
Session 4
Shailendra Mathur
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
variablesfinal-170820055428 data type results
variablesfinal-170820055428 data type resultsvariablesfinal-170820055428 data type results
variablesfinal-170820055428 data type results
atifmugheesv
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
6.array
6.array6.array
6.array
Shankar Gangaju
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
Munazza-Mah-Jabeen
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
Dr.Subha Krishna
 
slideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdfslideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdf
HimanshuKansal22
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
PriyadarshiniS28
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt
AqeelAbbas94
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.ppt
NamakkalPasanga
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejejeUnit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
Programming Fundamentals lecture 6
Programming Fundamentals lecture 6Programming Fundamentals lecture 6
Programming Fundamentals lecture 6
REHAN IJAZ
 
data types in c programming language in detail
data types in c programming language in detaildata types in c programming language in detail
data types in c programming language in detail
atulk4360
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
Appili Vamsi Krishna
 
variablesfinal-170820055428 data type results
variablesfinal-170820055428 data type resultsvariablesfinal-170820055428 data type results
variablesfinal-170820055428 data type results
atifmugheesv
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
slideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdfslideset 7 structure and union (1).pdf
slideset 7 structure and union (1).pdf
HimanshuKansal22
 
5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt5-Lec - Datatypes.ppt
5-Lec - Datatypes.ppt
AqeelAbbas94
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.ppt
NamakkalPasanga
 
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejejeUnit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
Unit-4-1.pptxjtjrjfjfjfjfjfjfjfjrjrjrjrjejejeje
KathanPatel49
 
Ad

Recently uploaded (20)

Pharmacologically active constituents.pdf
Pharmacologically active constituents.pdfPharmacologically active constituents.pdf
Pharmacologically active constituents.pdf
Nistarini College, Purulia (W.B) India
 
Water Pollution control using microorganisms
Water Pollution control using microorganismsWater Pollution control using microorganisms
Water Pollution control using microorganisms
gerefam247
 
Black hole and its division and categories
Black hole and its division and categoriesBlack hole and its division and categories
Black hole and its division and categories
MSafiullahALawi
 
An upper limit to the lifetime of stellar remnants from gravitational pair pr...
An upper limit to the lifetime of stellar remnants from gravitational pair pr...An upper limit to the lifetime of stellar remnants from gravitational pair pr...
An upper limit to the lifetime of stellar remnants from gravitational pair pr...
Sérgio Sacani
 
Anatomy Lesson by Slidesgo.pptx anatomia hunmana
Anatomy Lesson by Slidesgo.pptx anatomia hunmanaAnatomy Lesson by Slidesgo.pptx anatomia hunmana
Anatomy Lesson by Slidesgo.pptx anatomia hunmana
arturorbal22
 
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptxCleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
zainab98aug
 
Animal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptxAnimal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptx
MahitaLaveti
 
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptxA CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
ANJALICHANDRASEKARAN
 
Funakoshi_ZymoResearch_2024-2025_catalog
Funakoshi_ZymoResearch_2024-2025_catalogFunakoshi_ZymoResearch_2024-2025_catalog
Funakoshi_ZymoResearch_2024-2025_catalog
fu7koshi
 
Eric Schott- Environment, Animal and Human Health (3).pptx
Eric Schott- Environment, Animal and Human Health (3).pptxEric Schott- Environment, Animal and Human Health (3).pptx
Eric Schott- Environment, Animal and Human Health (3).pptx
ttalbert1
 
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptxSiver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
PriyaAntil3
 
Coral_Reefs_and_Bleaching_Presentation (1) (1).pptx
Coral_Reefs_and_Bleaching_Presentation (1) (1).pptxCoral_Reefs_and_Bleaching_Presentation (1) (1).pptx
Coral_Reefs_and_Bleaching_Presentation (1) (1).pptx
Nishath24
 
Subject name: Introduction to psychology
Subject name: Introduction to psychologySubject name: Introduction to psychology
Subject name: Introduction to psychology
beebussy155
 
Hypothalamus_structure_nuclei_ functions.pptx
Hypothalamus_structure_nuclei_ functions.pptxHypothalamus_structure_nuclei_ functions.pptx
Hypothalamus_structure_nuclei_ functions.pptx
klynct
 
Proprioceptors_ receptors of muscle_tendon
Proprioceptors_ receptors of muscle_tendonProprioceptors_ receptors of muscle_tendon
Proprioceptors_ receptors of muscle_tendon
klynct
 
Somato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptxSomato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptx
klynct
 
CORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptxCORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptx
DharaniJajula
 
Astrobiological implications of the stability andreactivity of peptide nuclei...
Astrobiological implications of the stability andreactivity of peptide nuclei...Astrobiological implications of the stability andreactivity of peptide nuclei...
Astrobiological implications of the stability andreactivity of peptide nuclei...
Sérgio Sacani
 
Secondary metabolite ,Plants and Health Care
Secondary metabolite ,Plants and Health CareSecondary metabolite ,Plants and Health Care
Secondary metabolite ,Plants and Health Care
Nistarini College, Purulia (W.B) India
 
Euclid: The Story So far, a Departmental Colloquium at Maynooth University
Euclid: The Story So far, a Departmental Colloquium at Maynooth UniversityEuclid: The Story So far, a Departmental Colloquium at Maynooth University
Euclid: The Story So far, a Departmental Colloquium at Maynooth University
Peter Coles
 
Water Pollution control using microorganisms
Water Pollution control using microorganismsWater Pollution control using microorganisms
Water Pollution control using microorganisms
gerefam247
 
Black hole and its division and categories
Black hole and its division and categoriesBlack hole and its division and categories
Black hole and its division and categories
MSafiullahALawi
 
An upper limit to the lifetime of stellar remnants from gravitational pair pr...
An upper limit to the lifetime of stellar remnants from gravitational pair pr...An upper limit to the lifetime of stellar remnants from gravitational pair pr...
An upper limit to the lifetime of stellar remnants from gravitational pair pr...
Sérgio Sacani
 
Anatomy Lesson by Slidesgo.pptx anatomia hunmana
Anatomy Lesson by Slidesgo.pptx anatomia hunmanaAnatomy Lesson by Slidesgo.pptx anatomia hunmana
Anatomy Lesson by Slidesgo.pptx anatomia hunmana
arturorbal22
 
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptxCleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
Cleaned_Expanded_Metal_Nanoparticles_Presentation.pptx
zainab98aug
 
Animal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptxAnimal Models for Biological and Clinical Research ppt 2.pptx
Animal Models for Biological and Clinical Research ppt 2.pptx
MahitaLaveti
 
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptxA CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
A CASE OF MULTINODULAR GOITRE,clinical presentation and management.pptx
ANJALICHANDRASEKARAN
 
Funakoshi_ZymoResearch_2024-2025_catalog
Funakoshi_ZymoResearch_2024-2025_catalogFunakoshi_ZymoResearch_2024-2025_catalog
Funakoshi_ZymoResearch_2024-2025_catalog
fu7koshi
 
Eric Schott- Environment, Animal and Human Health (3).pptx
Eric Schott- Environment, Animal and Human Health (3).pptxEric Schott- Environment, Animal and Human Health (3).pptx
Eric Schott- Environment, Animal and Human Health (3).pptx
ttalbert1
 
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptxSiver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
Siver Nanoparticles syntheisis, mechanism, Antibacterial activity.pptx
PriyaAntil3
 
Coral_Reefs_and_Bleaching_Presentation (1) (1).pptx
Coral_Reefs_and_Bleaching_Presentation (1) (1).pptxCoral_Reefs_and_Bleaching_Presentation (1) (1).pptx
Coral_Reefs_and_Bleaching_Presentation (1) (1).pptx
Nishath24
 
Subject name: Introduction to psychology
Subject name: Introduction to psychologySubject name: Introduction to psychology
Subject name: Introduction to psychology
beebussy155
 
Hypothalamus_structure_nuclei_ functions.pptx
Hypothalamus_structure_nuclei_ functions.pptxHypothalamus_structure_nuclei_ functions.pptx
Hypothalamus_structure_nuclei_ functions.pptx
klynct
 
Proprioceptors_ receptors of muscle_tendon
Proprioceptors_ receptors of muscle_tendonProprioceptors_ receptors of muscle_tendon
Proprioceptors_ receptors of muscle_tendon
klynct
 
Somato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptxSomato_Sensory _ somatomotor_Nervous_System.pptx
Somato_Sensory _ somatomotor_Nervous_System.pptx
klynct
 
CORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptxCORONARY ARTERY BYPASS GRAFTING (1).pptx
CORONARY ARTERY BYPASS GRAFTING (1).pptx
DharaniJajula
 
Astrobiological implications of the stability andreactivity of peptide nuclei...
Astrobiological implications of the stability andreactivity of peptide nuclei...Astrobiological implications of the stability andreactivity of peptide nuclei...
Astrobiological implications of the stability andreactivity of peptide nuclei...
Sérgio Sacani
 
Euclid: The Story So far, a Departmental Colloquium at Maynooth University
Euclid: The Story So far, a Departmental Colloquium at Maynooth UniversityEuclid: The Story So far, a Departmental Colloquium at Maynooth University
Euclid: The Story So far, a Departmental Colloquium at Maynooth University
Peter Coles
 
Ad

C data types, arrays and structs

  • 1. C-Data Types, Arrays and Structs PREPARED BY SAAD SHAIKH.
  • 2. Data Types  The basic definition of a data type is a data storage format that can contain a specific type or range of values.  When computer programs store data in variables, each variable must be assigned a specific data type.
  • 3. Types of Data Types  Primary Data Types  They are arithmetic types and are further classified into: (a) Integer types, (b) Character and (c) Floating-point types.  Derived Data Types:  They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types.  User Defined Data Types:  They include TypeDef and ENUM.
  • 4. Integer Type  Integers are a commonly used data type in computer programming. An integer is a whole number (not a fraction) that can be positive, negative, or zero.  It is denoted by “int” . Type Storage Size Value Range Int 2 or 4 bytes -32,768 to 32,767 or - 2,147,483,648 to 2,147,483,647 unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 long 4 bytes -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295
  • 5. Floating Point Type  As the name implies, floating point numbers are numbers that contain floating decimal points. For example, the numbers 5.5, 0.001, and - 2,345.6789 are floating point numbers.  Denoted by keyword “float”. Type Storage size Value Range Precision float 4 byte 1.2E-38 to 3.4E+38 6 decimal places double 8 byte 2.3E-308 to 1.7E+308 15 decimal places long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
  • 6. Character Data Types  Character data type allows a variable to store only one character.  “char” keyword is used to refer character data type. Type Storage size Value range char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127
  • 7. Example Code: #include <stdio.h> void main() { int i = 20; float f = 3.1415; char c; c = 'd'; printf("This is my float: %f n", f); printf("This is my integer: %d n", i); printf("This is my character: %c n", c); }
  • 8. VOID DATA TYPE  The void type has no values therefore we cannot declare it as variable as we did in case of integer and float.  The void data type is usually used with function to specify its type.
  • 9. User Defined Data Types  User defined data types are those data types which are created by the user to characterize the existing data types.  This user defined data type can later be used to declare variables.  In other words we are redefining the name of existing data types.
  • 10. User Defined Data Types-Enum:  An enumeration is a user-defined data type consists of integral constants and each integral constant is give a name. Keyword enum is used to defined enumerated data type.  Syntax: enum type_name{ value1, value2,...,valueN };  Here, type_name is the name of enumerated data type or tag. And value1, value2,....,valueN are values of type type_name.  By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change the default value.
  • 11. Example: #include<stdio.h> #include<conio.h> Enum Weekday { Sun,Mon,Tues,Wed,Thus,Fri,Sat }; Int main () { enum Weedkday wd; wd = Thus; printf(“%d”,wd): } 4 Output
  • 12. User Defined Data Types-typedef The C programming language provides a keyword called typedef, which you can use to give a type, a new name.  Syntax: typedef <type><identifier>;  Example: typedef int score; Score player1,player2;
  • 13. Derived Data Types: ARRAY  Array is a kind of data structure that can store a fixed-size sequential collection of elements of the same type.  An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.  All arrays consist of contiguous memory locations. First Element Last Element a[1]a[0] a[2] a[3] a[4] a[5] a[6] a[7] a[n]
  • 14. Declaring Arrays  To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows : type arrayName [ arraySize ];  For example we can declare a 10 element array like: int marks [10];
  • 15. Initializing Array  We can initialize an array in C either one by one or using a single statement as follows: double price[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};  The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].
  • 16. Example: #include <stdio.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; /* set element at location i to i + 100 */ } /* output each array element's value */ for (j = 0; j < 10; j++ ) { printf("Element[%d] = %dn", j, n[j] ); } return 0; } Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 Output
  • 17. Multidimensional Arrays  Array having more than one subscript variable is called multidimensional array.  Multidimensional array is also called as matrix  To declare a two-dimensional integer array of size [x][y], you would write something as follows: type arrayName [ x ][ y ];  To initialize multidimensional array we specify bracketed value of each row; for example: int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ };
  • 18. Example: #include <stdio.h> int main () { /* an array with 5 rows and 2 columns*/ int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8} }; int i, j; /* output each array element's value */ for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) { printf("a[%d][%d] = %dn", i,j, a[i][j] ); } } return 0; } a[0][0]: 0 a[0][1]: 0 a[1][0]: 1 a[1][1]: 2 a[2][0]: 2 a[2][1]: 4 a[3][0]: 3 a[3][1]: 6 a[4][0]: 4 a[4][1]: 8 Output :
  • 19. Structures  Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C that allows to combine data items of different kinds.  Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book like: Title Author Subject Book ID
  • 20. Defining Structures  To define a structure, you must use the struct statement.  The format is as follows: struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables]; Example: struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book;
  • 21. Accessing Structure Members  To access any member of a structure, we use the member access operator (.).
  • 22. Example: #include <stdio.h> #include <string.h> struct Books { char title[50]; char author[50]; char subject[100]; int book_id;}; int main( ) { struct Books Book; /* Declare Book of type Book */ /* book specification */ strcpy( Book.title, "C Programming"); strcpy( Book.author, "Aptech"); strcpy( Book.subject, "C Programming"); Book.book_id = 6495407; /* print Book info */ printf( "Book title : %sn", Book.title); printf( "Book author : %sn", Book.author); printf( "Book subject : %sn", Book.subject); printf( "Book book_id : %dn", Book.book_id); return 0; } Book title : C Programming Book author : Aptech Book subject : C Programming Book book_id : 6495407 Output :
  翻译: