ProgDasCh07 Tipe Data

Preview:

DESCRIPTION

tipe data

Citation preview

Data TransformationData TransformationData is the representation of information in a manner suitable for

communication or analysis by humans or machinesData is stored in the memory as a string of binary digits (0 and 1) having finite

length. In a machine instruction, a memory location is identified by its address.Data can be read from a memory location and a memory location can also be

updatedPrograms transform data from one form to another

Input data Output dataStimulus Response

Programming languages store and process data in various ways depending on the type of the data; consequently, all data read, processed, or written by a program must have a type

Two distinguishing characteristics of a programming language are the data types it supports and the operations on those data types

Data TypesData TypesData types (or sometimes just called ‘types’)are the

descriptions of the containers of the dataThe basic idea of typing data is to give some useful

meaning to what is ultimately just binary digits.Describing this data using types makes it easier to

understand, manipulate or retrieve.Data is held within the computers RAM until needed by

the program. The amount of RAM needed to hold each data type

depends on what type of data type is being used

A Data Type A Data Type A data type is

A set of values ANDA set of operations on those values

A data type is used toIdentify the type of a variable when the variable is declaredIdentify the type of the return value of a functionIdentify the type of a parameter expected by a function

A Data A Data TypeType

When the compiler encounters a declaration for a variable, it sets up a memory location for it

An operator used on a variable or variables is legal only ifThe operator is defined in that programming language for a

variable of that typeThe variable or variables involved with the operator are of

the same or compatible types

Rules for Constructing Identifiers in C

Capital letters A-Z, lowercase letters a-z, digits 0-9, and the underscore character

First character must be a letter or underscoreUsually only the first 32 characters are significantThere can be no embedded blanksKeywords cannot be used as identifiersIdentifiers are case sensitive

Identifiers refer to the names of data types, constants, variables, and functions

C programming language which has the ability to divide the data into different types. The type of a variable determine the what kind of values it may take on. The various data types are

Fundamental Data type Integer, Float, Void, Char,

enumAdress pointerComposite

struct, union, array, strings

Classifications of Data TypesClassifications of Data Types

Built-In Data TypesBuilt-In Data Types

Composite

StructuredArray, string

Address

pointer reference

Fundamental/Basic

Integral Floating

char short int long enum

float double long double

Void

Unstructuredstruct, union

Fundamental Data Fundamental Data TypesTypes

void – used to denote the type with no values int – used to denote an integer typechar – used to denote a character typefloat, double – used to denote a floating point typeenum -

Composite Data TypesComposite Data TypesStructure – a collection of related

variables of the same and/or different data types. The structure is called a record and the variables in the record are called members or fields

UnionArray – a finite sequence (or table) of variables of the

same data typeString – an array of character variables

Integral Types

Integers are stored in various sizes. They can be signed or unsigned.

Example Suppose an char integer is represented by a byte (8 bits).

Leftmost bit is sign bit. If the sign bit is 0, the number is treated as positive.

The largest positive number is 01111111 = 27 – 1 = 127. Bit pattern 01001011 = 75 (decimal). Negative numbers are stored as two’s complement or as one’s complement. -75 = 10110100 (one’s complement). -75 = 10110101 (two’s complement).

Basic Data TypesBasic Data TypesIntegral Types

char Stored as 8 bits. Unsigned 0 to 255. Signed -128 to 127.

short int Stored as 16 bits.

int Stored as 16 bits. Unsigned 0 to 65535

Signed -32768 to 32767 (-215 to +215-1).

long int Stored as 32 bits. Unsigned 0 to 4294967295.

Signed -2147483648 to 2147483647

2-13

Integer Types in CInteger Types in C

Type Range in Typical Microprocessor Implementation

short -32767 ~ 32767

unsigned short

0 ~ 65535

int -32767 ~ 32767

unsigned 0 ~ 65535

long -2147483647 ~ 2147483647

unsigned long

0 ~ 4294967295

unsigned int u;scanf(“%u”, &u); /* reads u in base 10 */printf(“%u”, u); /* writes u in base 10 */scanf(“%o”, &u); /* reads u in base 8 */printf(“%o”, u); /* writes u in base 8 */scanf(“%x”, &u); /* reads u in base 16 */printf(“%x”, u); /* writes u in base 16*/

short int x;scanf(“%hd”, &x); printf(“%hd”, x);

long int x;scanf(“%ld”, &x); printf(“%ld”, x);

Floating Point NumbersFloating point numbers are rational numbers. Always signed

numbers.float Approximate precision of 6 decimal digits .

Typically stored in 4 bytes with 24 bits of signed mantissa and 8 bits of signed exponent.

doubleApproximate precision of 14 decimal digits.Typically stored in 8 bytes with 56 bits of signed mantissa

and 8 bits of signed exponent.Long Approximate precision of 18 decimal digits

Typically stored in 10 bytes with 72 bits of signed mantissa and 8 bits of signed exponent.

Historically, floating-points have been stored in a variety of formats

Same basic components: sign, fraction/mantissa, exponent

Example : 4.0 = 0010 * 20001 = 2 * 21

In 1985, IEEE floating-point formats were standardized

1 8 23 bits

1 11 52 bits

sign exponent fraction

(sign) fraction x 2exponent

2-17

Floating-Point Types in CFloating-Point Types in CType Approxima

te Range*Significant Digits*

Float(32 bit) 10-37 ~1038 6Double(64 bit)

10-307 ~10308

15

long double(80 bit)

10-4931 ~104932

19

float single-precision floating-pointdouble double-precision floating-point long double extended-precision floating-point

double x; long double x;scanf(“%lf”, &x); scanf(“%Lf”, &x);printf(“%lf”, x); printf(“%Lf”, x);

2-19

Type Type doubledouble Constants Constants

Valid double Constants

Invalid double Constants

3.14159 150 (no decimal point)

0.005 .12345e(missing exponent)

12345.0 15e-0.3(0.3 is invalid)

15.0e-04 (0.0015)

2.345e2 (234.5) 12.5e.3(.3 is invalid)

1.15e-3 (0.00115) 34,500.99(, is not allowed)

12e+5 (1200000.0)

Floating Point ArithmeticFloating Point ArithmeticRepresentation

All floating point numbers are stored as

such that d1 is nonzero. B is the base. p is the precision or number of significant digits. e is the exponent. All these put together have finite number of bits (usually 32 or 64 bits ) of storage.

ExampleAssume B = 10 and p = 3.23.7 = +0.237E223.74 = +0.237E237000 = +0.370E537028 = +0.370E5-0.000124 = -0.124E-4

ep Bddd 21.0

Floating Point ArithmeticFloating Point ArithmeticRepresentation

Sk = { x | Bk-1 <= x < Bk }. Number of elements in each Sk is same. In the previous example it is 900.

Gap between seuccessive numbers of Sk is Bk-p.B1-p is called machine epsilon. It is the gap between 1 and next

representable number.Underflow and Overflow occur when number cannot be

represented because it is too small or too big.Two floating points are added by aligning decimal points.Floating point arithmetic is not associative and distributive.

Data Type char (8 bit)Rrepresent an individual character valueinclude a letter, a digit, a special symbolExample ‘A’ ‘z’ ‘2’ ‘9’ ‘ * ’ ‘ : ’ ‘ ” ’ ‘ ‘‘a‘, ‘\t’, ‘\n’, ‘\0’, etc. are character constantsThere are signed and unsigned chars; both occupy 1

byte each, but having different ranges. Unsigned characters have values between 0 and 255,signed characters have values from –128 to 127.

char ch;int i;i = ‘a’; /* i is now 97 */ch = 65; /* ch is now ‘A’ */ch = ch + 1; /* ch is now ‘B’ */ch++; /* ch is now ‘C’ */

if(‘a’ <= ch && ch <= ‘z’)

for(ch = ‘A’; ch <= ‘Z’; ch++)

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.

enum - Enumeration ConstantsEnum is another user-defined type consisting of a set of named

constants called enumerators.Using a keyword enum, it is a set of integer constants

represented by identifiers.As said before, by default, the first enumerator has a value of 0,

and each successive enumerator is one larger than the value of the previous one, unless you explicitly specify a value for a particular enumerator.

Enumerators needn't have unique values within an enumeration.

The name of each enumerator is treated as a constant and must be unique within the scope where the enum is defined

Enumeration

Enumeration is a user-defined data type. It is defined using the keyword enum and the syntax is:

enum tag_name {name_0, …, name_n} ;

The tag_name is not used directly. The names in the braces are symbolic constants that take on integer values from zero through n. As an example, the statement:

enum colors { red, yellow, green } ; creates three constants. red is assigned the value 0,

yellow is assigned 1 and green is assigned 2.

The values in an enumstart with 0, unless specified otherwise, and are incremented by 1. For example, the following enumeration,

enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};Creates a new data type, enum days, in which the identifiers

are set automatically to the integers 0 to 6.To number the days 1 to 7, use the following enumeration,

enum days {Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun};Or we can re-arrange the order,

enum days {Mon, Tue, Wed, Thu = 7, Fri, Sat, Sun};

enum - Enumeration Constants

28

Computers store data in memory slotsEach slot has an unique addressVariables store their values like this:

Altering the value of a variable is indeed changing the content of the memory e.g. i = 40;

Addr

Content

Addr

Content Addr

Content

Addr

Content

1000 i: 37 1001 j: 33 1002 k: 58 1003 m: 74

1004 ptr: 1001

1005 1006 1007

Address Data TypesAddress Data Types

Addr

Content

Addr

Content Addr

Content

Addr

Content

1000 i: 40 1001 j: 33 1002 k: 58 1003 m: 74

1004 ptr: 1001

1005 1006 1007

29

Addressing ConceptPointer stores the address of another entityIt refers to a memory location

int i = 5; /* declare integer variable I */

int *ptr; /* declare a pointer variable */

ptr = &i; /* store address-of i to ptr */

printf(“*ptr = %d\n”, *ptr); /* refer to referee of ptr */

30

What actually ptr is?ptr is a variable storing an addressptr is NOT storing the actual value of i

int i = 5;

int *ptr;

ptr = &i;

printf(“i = %d\n”, i);

printf(“*ptr = %d\n”, *ptr);

printf(“ptr = %p\n”, ptr);5i

address of iptr

Output:

i = 5

*ptr = 5

ptr = effff5e0

value of ptr = address of i

in memory

Pointer Variable Declarations and Initialization

Pointer declarations* used with pointer variables

int *ptr;

Declares a pointer to an int (pointer of type int *)

Multiple pointers require using a * before each variable declaration

int *ptr1, *ptr2;

Can declare pointers to any data typeInitialize pointers to 0, NULL, or an address

0 or NULL – points to nothing (NULL preferred)

Pointer Operators& (address operator)

Returns address of operandint i = 5;

int *ptr;

ptr = &i; // ptr gets address of i

ptr “points to” i

ptr

i5

ptr

500000 600000

i

600000 5

Address of i is value of ptr

Twin Operators&: Address-of operator

Get the address of an entity e.g. ptr = &j;

*: De-reference operatorRefer to the content of the referee

e.g. *ptr = 99;

Addr

Content

Addr

Content Addr

Content

Addr

Content

1000 i: 40 1001 j: 33 1002 k: 58 1003 m: 74

1004 ptr: 1001

1005 1006 1007

Addr

Content

Addr

Content Addr

Content

Addr

Content

1000 i: 40 1001 j: 99 1002 k: 58 1003 m: 74

1004 ptr: 1001

1005 1006 1007

1 /* Fig. 7.4: fig07_04.c

2 Using the & and * operators */3 #include <stdio.h>45 int main()6 {7 int a; /* a is an integer */8 int *aPtr; /* aPtr is a pointer to an integer */910 a = 7;11 aPtr = &a; /* aPtr set to address of a */1213 printf( "The address of a is %p" 14 "\nThe value of aPtr is %p", &a, aPtr );1516 printf( "\n\nThe value of a is %d" 17 "\nThe value of *aPtr is %d", a, *aPtr );1819 printf( "\n\nShowing that * and & are inverses of "20 "each other.\n&*aPtr = %p" 21 "\n*&aPtr = %p\n", &*aPtr, *&aPtr );2223 return 0;24 }

The address of a is 0012FF88The value of aPtr is 0012FF88 The value of a is 7The value of *aPtr is 7Shoving that * and & are complements of each other.&*aPtr = 0012FF88*&aPtr = 0012FF88

The address of a is the value of aPtr.

The * operator returns an alias to what its operand

points to. aPtr points to a, so *aPtr returns a.

Notice how * and & are inverses

Two Forms of Composite Data TypesTwo Forms of Composite Data Types

Components are not organized with respect to one another.

The organization determines method used to access individual data components.

UNSTRUCTURED

STRUCTURED

EXAMPLES: arrays, string

35

EXAMPLES : structs, union

SStructure / tructure / Records Records A structure is a user defined data type that groups logically

related data items of different data types into a single unit. All the elements of a structure are stored at contiguous memory

locations. A variable of structure type can store multiple data items of

different data types under the one name.Structures hold data that belong together. Examples:

Student record: student id, name, major, gender, start year, …

Bank account: account number, name, currency, balance, …Address book: name, address, telephone number, …

In database applications, structures are called records.

36

37

StructuresIndividual components of a struct type are

called members (or fields).Members can be of different types (simple,

array or struct).A struct is named as a whole while individual

members are named using field identifiers.Complex data structures can be formed by

defining arrays of structs.

38

struct basicsDefinition of a structure:struct <struct_name>{

<type> <variable_name>;<type> <variable_name>;...

} ;

Example:struct Date {

int day;int month;int year;

} ;

The “Date” structure has 3 members,

day, month & year.

Each variabledefines a member

of the structure.

Example Struct To store and process a student’s record with the elements chIdNum(identification number), chName, chGenderand nAge, We can declare the following structure :

struct student{char chIdNum[5];char chName[10];char chGender;int nAge;};

The previous sample template for the structure can be illustrated as follow (note the different data sizes),

The struct MyEmployee structure has three members: chName, nIdNum, and nDepatment.

The chName member is a 20-element array, and nIdNum and nDepatment are simple members with int and long types, respectively.

The identifier MyEmployee is the structure identifier.Declaring structure variables can be done in the following way,

Then we can declare variables of type struct MyEmployeelike the following,struct MyEmployee student, staff, academician;

struct MyEmployee { char chName[20]; int nIdNum; long nDepatment; } EmpData; // defines a structure variable named EmpData

Define the structure

Declare the variabel of structureStruct StudentRecord student1; newStudent student1;

// declare a structure

struct StudentRecord{char Name[22];int Id;char Dept[22];char Gender;};

// declare a structure

struct StudentRecord{char Name[22];int Id;char Dept[22];char Gender;}; newStudent

Define, declare and initializeDefine, declare and initialize Struct Struct

All the structure program examples in the previous structure section can be simplified using typedef. The typedef keyword can be used to create a synonym for a data type. It is most often used to simplify the

naming and use of record types (i.e., structure types).Define the typedef

Declare the variabel of structureStruct StudentRecord student1; newStudent student1;

// declare a structure

typedef struct StudentRecord{char Name[22];int Id;char Dept[22];char Gender;};

// declare a structure

Typedef struct {char Name[22];int Id;char Dept[22];char Gender;}; newStudent

Struct TypedefStruct Typedef

AccessingAccessing struct struct members members

The member selection operator (.) is used between the variable name and the member identifier to access individual members of a struct type variable.

EXAMPLESstudent1.Name;student1.Id;student1.Dept;student1.Gender;

43

student1.Name = “Silmi Fauziati “;student1.Id = 1234;student1.Dept = “Technology Informaion”;student1.Gender = ‘F’;

printf (“The name of student is : %s”, student1.Name); printf (“The ID of student is : %d”, student1.Id); printf (“The Department of student is : %s”, student1.Dept); printf (“The Gender of student is : %c”, student1.Gender);

Example of Structure

The structure of Employee is declared as struct employee{int emp_id;char name[20];float salary;char address[50];int dept_no;int age; };

Memory Space Allocation

80008002

80228024

807480768078 employee

emp_id

name[20]

salary

address[50]

dept_no

age

The members of individual structure variable is initialize one by one or in a single statement.

The example to initialize a structure variable is

1)struct employee e1 = {1, “Hemant”,12000, “3 vikas colony new delhi”,10, 35};

2)e1.emp_id=1; e1.dept_no=1 e1.name=“Hemant”; e1.age=35;

e1.salary=12000;

e1.address=“3 vikas colony new delhi”;

Initializing a Structure Members Initializing a Structure Members

#include <stdio.h>#include <conio.h>

struct employee{

int emp_id;char name[20];float salary;char address[50];int dept_no;int age;

};

Program to implement the StructureProgram to implement the Structure

void main ( ) { struct employee e1,e2; printf (“Enter the employee id of employee”); scanf(“%d”,&e1.emp_id); printf (“Enter the name of employee”); scanf(“%s”,e1.name); printf (“Enter the salary of employee”); scanf(“%f”,&e1.salary); printf (“Enter the address of employee”); scanf(“%s”,e1.address); printf (“Enter the department of employee”); scanf(“%d”,&e1.dept_no); printf (“Enter the age of employee”);

scanf(“%d”,&e1.age); printf (“Enter the employee id of employee”); scanf(“%d”,&e2.emp_id); printf (“Enter the name of employee”); scanf(“%s”,e2.name); printf (“Enter the salary of employee”); scanf(“%f”,&e2.salary); printf (“Enter the address of employee”); scanf(“%s”,e2.address); printf (“Enter the department of employee”); scanf(“%d”,&e2.dept_no); printf (“Enter the age of employee”); scanf(“%d”,&e2.age);

printf (“The employee id of employee is : %d”, e1.emp_id); printf (“The name of employee is : %s”, e1.name); printf (“The salary of employee is : %f”, e1.salary); printf (“The address of employee is : %s”, e1.address); printf (“The department of employee is : %d”, e1.dept_no); printf (“The age of employee is : %d”, e1.age);

printf (“The employee id of employee is : %d”, e2.emp_id); printf (“The name of employee is : %s”, e2.name); printf (“The salary of employee is : %f”, e2.salary); printf (“The address of employee is : %s”, e2.address); printf (“The department of employee is : %d”, e2.dept_no); printf (“The age of employee is : %d”,e2.age); getch(); }

Enter the employee id of employee 1 Enter the name of employee Rahul Enter the salary of employee 15000 Enter the address of employee 4,villa area, Delhi Enter the department of employee 3 Enter the age of employee 35 Enter the employee id of employee 2 Enter the name of employee Rajeev Enter the salary of employee 14500 Enter the address of employee flat 56H, Mumbai Enter the department of employee 5 Enter the age of employee 30

Output of Program Output of Program

The employee id of employee is : 1 The name of employee is : Rahul The salary of employee is : 15000 The address of employee is : 4, villa area, Delhi The department of employee is : 3 The age of employee is : 35 The employee id of employee is : 2 The name of employee is : Rajeev The salary of employee is : 14500 The address of employee is : flat 56H, Mumbai The department of employee is : 5 The age of employee is : 30

AAnonymous structnonymous structAnother example, anonymous struct(struct without tag),Struct { /* defines an anonymous struct and a */

/* structure variable named area */float fwidth, flength;} area;

The area structure has two members with float type, fwidth and flength.

The structure type has no tag and is therefore is unnamed or anonymous.

The nested structures, called anonymous structures allows you to declare a structure variable within another structure without giving it a name.

AAnonymous structnonymous structAnonymous structures can be useful when the tag named is not

needed.This is the case when one declaration defines all structure instances.Embedded or nested structures are often anonymous.

For example,struct MyCube {

struct /* anonymous structure */{

int width, length;} area;

int height;} CubeData;

• A union is similar to a structure, except that its members are overlaid (located at the same memory address).• Example:

union {int i;double d;} u;

• The members of a union are accessed in the same way as members of a structure:u.i = 15;oru.d = 8.89;

Since u.i and u.d have the same memory address, changing the value of one alters the value of the other.

• Unions have the same properties as structures:

Unions can be initialized (the initializer specifies the value of the first member).Unions can be identified by tags or type names.Unions can be assigned, passed to functions, and returned by functions.

The union data type allocate the space equal to space need to hold the largest data member of union

The memory occupied by structure variable is the sum of sizes of all the members but memory occupied by union variable is equal to space hold by the largest data member of a union.

61

ArraArrayy

A collection of objects of the same type stored contiguously in memory under one name

May be type of any kind of variableMay even be collection of arrays!

For ease of access to any member of arrayFor passing to functions as a groupMany, many uses of all kinds

Collections of all kinds of dataInstant access to any element

62

ArraArrayy

63

Examples Examples arrayarray

int A[10]An array of ten integersA[0], A[1], …, A[9]

double B[20]An array of twenty long floating point numbersB[0], B[1], …, B[19]

Arrays of structs, unions, pointers, etc., are also allowedArray indexes always start at zero in C

C uses 0 -> (n-1) as the array bounds.float values[10]; // ‘values’ goes from 0 -> 9

int C[]An array of an unknown number of integers (allowable in a

parameter of a function) C[0], C[1], …, C[max-1]

64

Array Array ElementElement

May be used wherever a variable of the same type may be used In an expression (including arguments)On left side of assignment

Examples :A[3] = x + y;x = y – A[3];z = sin(A[i]) + cos(B[j]);

Array elements are commonly used in loopsE.g.,

for(i=0; i < max; i++)A[i] = i*i;

for(sum = 0, j=0; j < max; j++)sum += B[j];

70

90

80

90

100

//deklarasi array int nilai_tes[5]

// mengisi array nilai_tes[3] = 90;

// menampilkan isi array printf(“%d”, nilai_tes[3]);

For elemen array i=2;

*(A+2) or A[2]

printf(“%d”,A[2]) or printf(“%d\n”,*(A+2));

Accessing Accessing Elemen Elemen ArrayArray

Alamat elemen Array

0 1 2 3 4 5 6 7

21da 21db 21dc 21dd 21de 21df 21e0 21e1

index

value

address

%x is hexadesimal

/* ------------------------------------------------ */ /* Contoh pengaksesan array satu dimensi */ /* ------------------------------------------------ */ #include <stdio.h> #define maks_tes 5 main() {

int i; float nilai_tes[maks_tes];

/* deklarasi array *//* Membaca data dari keyboard */

for (i=0;i<maks_tes;i++) {

printf("Nilai tes ke-%d: ",i+1); scanf("%f", &nilai_tes[i]);

} /* Menampilkan data yang telah dimasukkan */

for (i=0;i<maks_tes;i++) {

printf("Nilai tes ke-%d: %f",i+1,nilai_tes[i]); }

}

What is a String?What is a String?Arrays : data structures that contain a collection of data objects of

the same data typeStrings are really just arrays of charactersA string is an array of characters terminated by the NUL character

Data type is array of charactersThe NUL character is a character with a numeric value of zero

In C, it is represented by the escape sequence, \0 (NUL)String constant (or string literal)

Any series of characters enclosed in double quotesEx. "Hello world"

String example program stores a string constantstores individual elements

note: character constantsnote: terminate with '\0‘ to make the character array a string

Strings as zero terminated arrayStrings as zero terminated arrayIn C a string is a zero-terminated array of characters

char s[ ] = "asdf";

71

'a' 's' 'f''d' 0s:

in C, the convention is to store a string as a char array, terminated with ’\0’

char str[] = ”Dave”; str ’D’ ’a’ ’v’ ’e’ ’\0’

What is a String?What is a String?

/* strings1.c */#include <stdio.h>

int main(){ int i; char str1[] = "Hello world"; char str2[5]; str2[0]='M'; str2[1]='E'; str2[2]='3'; str2[3]='0'; str2[4]='\0'; printf("str1==%s\n",str1); for(i=0; i<5; i++) { printf("str2[%d]==%c\n",i,str2[i]); } return 0;}

strings1.c

Initializing String VariablesInitializing String VariablesDeclare as an array of

type charCan initialize implicitly or explicitly

(using a string constant or using individual characters and a terminating NUL character) If explicit, make sure

that:

/* strings1.c */#include <stdio.h>

int main(){ int i; char str1[] = "Hello world"; char str3[12] = "Hello world"; char str2[5]; str2[0]='M'; str2[1]='E'; str2[2]='3'; str2[3]='0'; str2[4]='\0'; printf("str1==%s\n",str1); for(i=0; i<5; i++) { printf("str2[%d]==%c\n",i,str2[i]); } return 0;}1 stringincharselements nn

American Standard Code for Information American Standard Code for Information Interchange (ASCII) TableInterchange (ASCII) Table

Printing Strings to stdoutPrinting Strings to stdoutCan print an entire

string using printf and %s format specification

Can print individual elements of a string by indexing and using %c format specification

/* strings1.c */#include <stdio.h>

int main(){ int i; char str1[] = "Hello world"; char str3[12] = "Hello world"; char str2[5]; str2[0]='M'; str2[1]='E'; str2[2]='3'; str2[3]='0'; str2[4]='\0'; printf("str1==%s\n",str1); for(i=0; i<5; i++) { printf("str2[%d]==%c\n",i,str2[i]); } return 0;}

Manipulating Strings in CManipulating Strings in C

No native support for strings in CUse The Standard Function C Library

for string#include <string.h>

<stdio.h> printf(), scanf(), etc.

<string.h> strcmp(), etc.<ctype.c> isspace(), etc.<stdlib.h> malloc(), etc.<math.h> sqrt(), etc.

Standard function librariesStandard function libraries

Comparing StringsComparing Strings

Use strlen(string)returns length of the string

Finding the Length of a StringFinding the Length of a String

Use strlen(string)returns length of the string

Example: strings3_copy_concat_length.c

Copying and Concatenating StringsCopying and Concatenating Strings

to copy str2 to str1 (order resembles assignment):strcpy(str1, str2);

str1 = str2; /* Will NOT work!! */to add (concatenate) str2 to the end of str1:

strcat(str1, str2); returns the value of str1 with str2 added to the end

Note: it clobbers the /0 at the end of str1Make sure that str1 has room for str2

StringsStringsComparing strings

#include <string.h>if (s1 = = s2) { /* do s1 and s2 point to the same array? */

/* (typically not what you want) */}

if (strcmp(s1,s2) = = 0) { /* do s1 and s2 hold the same characters? */}

Finding the length of a stringint lgt = strlen(s); /* note: goes through the string at run time */

/* looking for the terminating 0 */Copying strings

strcpy(s1,s2); /* copy characters from s2 into s1 *//* be sure that s1 can hold that many

characters *//* and/or use strncpy */

80

Strings – Practice Strings – Practice Declare:

A string variable named me30, and initialize it to hold the string, "ME 30 rocks!"

DetermineThe minimum number of character array elements

needed to store the stringlength of the stringWhat is stored in me30[2]?What is stored in me30[12]?

Strings - Practice 1 - solutionStrings - Practice 1 - solutionDeclare:

char me30[]="ME 30 rocks!" DetermineThe minimum number of character array elements needed to

store the string = 13Length of the string

Try sizeof(me30)/sizeof(char)Or strlen(me30)+ 1

What is stored in me30[2]?me30[2]== space

What is stored in me30[12]?me30[12]== ‘\0’

Numerical ConstantsConstants like 12, 253 are stored as int type. No decimal

point.12L or 12l are stored as long int.12U or 12u are stored as unsigned int.12UL or 12ul are stored as unsigned long int.Numbers with a decimal point (12.34) are stored as double.Numbers with exponent (12e-3 = 12 x 10-3 ) are stored as

double.12.34f or 1.234e1f are stored as float.These are not valid constants:

25,000 7.1e 4 $200 2.3e-3.4 etc.

Character and string constants‘c’ , a single character in single quotes are stored as char.

Some special character are represented as two characters in single quotes.‘\n’ = newline, ‘\t’= tab, ‘\\’ = backlash, ‘\”’ = double quotes.Char constants also can be written in terms of their ASCII code.‘\060’ = ‘0’ (Decimal code is 48).

A sequence of characters enclosed in double quotes is called a string constant or string literal. For example“Charu”“A”“3/9”“x = 5”

const// in C, a const is never a compile time constant const int max = 30;const int x; // const not initialized: ok in C

void f(int v){

int a1[max]; // error: array bound not a constant (max is not a constant!)int a2[x]; // error: array bound not a constant (here you see why)switch (v) {case 1:

// …case max: // error: case label not a constant

// …}

}85

Instead of const use macrosInstead of const use macros#define MAX 30

void f(int v){

int a1[max]; // okswitch (v) {case 1:

// …case max: // ok

// …}

}86

VariableVariabless

Naming a VariableMust be a valid identifier.Must not be a keywordNames are case sensitive.Variables are identified by only first 32 characters.Library commonly uses names beginning with _.Naming Styles: Uppercase style and Underscore stylelowerLimit lower_limitincomeTax income_tax

DeclarationsDeclarationsDeclaring a Variable

Each variable used must be declared.A form of a declaration statement is

data-type var1, var2,…;Declaration announces the data type of a variable and allocates

appropriate memory location. No initial value (like 0 for integers) should be assumed.

It is possible to assign an initial value to a variable in the declaration itself.data-type var = expression;

Examplesint sum = 0;char newLine = ‘\n’;float epsilon = 1.0e-6;

Global and Local VariablesGlobal and Local VariablesGlobal Variables

These variables are declared outside all functions.

Life time of a global variable is the entire execution period of the program.

Can be accessed by any function defined below the declaration, in a file.

/* Compute Area and Perimeter of a circle */

#include <stdio.h>float pi = 3.14159; /* Global */

main() { float rad; /* Local */ printf( “Enter the radius “ ); scanf(“%f” , &rad);

if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad;

printf( “Area = %f\n” , area ); printf( “Peri = %f\n” , peri ); } else printf( “Negative radius\n”);

printf( “Area = %f\n” , area );}

/* Compute Area and Perimeter of a circle */

#include <stdio.h>float pi = 3.14159; /* Global */

main() { float rad; /* Local */ printf( “Enter the radius “ ); scanf(“%f” , &rad);

if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad;

printf( “Area = %f\n” , area ); printf( “Peri = %f\n” , peri ); } else printf( “Negative radius\n”);

printf( “Area = %f\n” , area );}

90

Local VariablesThese variables are

declared inside some functions.

Life time of a local variable is the entire execution period of the function in which it is defined.

Cannot be accessed by any other function.

In general variables declared inside a block are accessible only in that block.

/* Compute Area and Perimeter of a circle */

#include <stdio.h>float pi = 3.14159; /* Global */

main() { float rad; /* Local */ printf( “Enter the radius “ ); scanf(“%f” , &rad);

if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad;

printf( “Area = %f\n” , area ); printf( “Peri = %f\n” , peri ); } else printf( “Negative radius\n”);

printf( “Area = %f\n” , area );}

/* Compute Area and Perimeter of a circle */

#include <stdio.h>float pi = 3.14159; /* Global */

main() { float rad; /* Local */ printf( “Enter the radius “ ); scanf(“%f” , &rad);

if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad;

printf( “Area = %f\n” , area ); printf( “Peri = %f\n” , peri ); } else printf( “Negative radius\n”);

printf( “Area = %f\n” , area );}

Global and Local VariablesGlobal and Local Variables

Mixed Type ExpressionsCalled ‘promotion/coercion and involves type conversionIn any assignment, the ultimate value on the right must be

converted, if necessary, to the type on the left.But in evaluating the expression on the right, or in assigning the

value on the right to the operand on the left, it is very possible that promotion will occur.

Automatic conversions are called ‘implicit type conversions.’

Promotion Hierarchy

long double

double

float

Unsigned long int

long int

unsigned int

int

char c;short int s;int i;unsigned int u;long int l;unsigned long int ul;float f;double d;long double ld;i = i + c; /* c is converted to int */i = i + s; /* s is converted to int */u = u +i; /* i is converted to unsigned int */l = l + u; /* u is converted to long int */ul =ul + l; /* l is converted to unsigned long int */f = f + ul; /* ul is converted to float */d = d + f; /* f is converted to double */ld = ld + d; /* d is converted to long double */

2-95

Type Conversion through CastsType Conversion through Caststype cast

converting an expression to a different type by writing the desired type in parentheses in front of the expression

Application ExampleAvoiding integer division

Average = (double)total_score / (double)num_students;

Rounding a number Rounded_x = (int)(x + 0.5)

( type-name ) expression

float f, frac_part;frac_part = f – (int) f;

float quotient;int dividend, divisor;quotient = (float) dividend / divisor;

typedef int BOOLBOOL flag; /* same as int flag; */

typedef short int Int16typedef long int Int32typedef unsigned char Byte

typedef struct {int age; char *name} person; person people;

(float) a cast operator requires a unary expression.(float) (x + y) evaluates x plus y and then floats the result (float) x + y will float x first and then try to add it to y.

y may need to be coerced to float if it is a more narrow type than float.

average = totalScores / (float) numScores; What happens??

(float) (a / 10) ?? If a = 3 initially?

(Overflow and underflow occur when the value of a variable exceeds the maximum or minimum value that can be stored in the variable. How some systems might respond - maybe not yours - check out the rules of your system!!

(

Example 1:

Suppose we execute the following statements:

float a = 1.0e+20;float b = 2.0e+30;float c;c = a * b;

Say the range of values for variables of type float is 3.4e-38 to 3.4e+38. The values assigned to a & b are within this range. The result of the multiplication is not!

This is not detected during compilation, but rather when the last statement is executed. The program terminates and displays -

floating point error: overflow Abnormal terminationgcc will result in “c = inf” being printed.

Example 2:

Suppose we execute the following statements:

float a = 1.0e-30;float b = 2.0e+20;float c;c = a / b;

The result of the division is 5.0e-51, which is smaller than the minimum value that can be stored in a variable of type float.

This is not detected during compilation, but rather occurs when the last statement is executed.

In this case no error message is displayed. Instead, the result is set equal to zero, and so the variable c will be assigned the value 0.

gcc will result in “c = 0.000000” being printed

(

Some of the more common reasons for overflow and underflow are:• Variables that have not been initialized,• Variables that have been initialized to an incorrect value,• A wrong arithmetic operation is specified,• A denominator having a zero value is used during a division,• When a program that worked correctly on one system is run on

another system (range of values may differ from system to system),

• Usually occur when you are working with very large or very small numbers.

How to correct??

In many cases you can switch to a data type that has a wider range, for example, switch from a float to a double or a long double.

Common Programming ErrorsCommon Programming ErrorsSyntax ErrorsRun-Time ErrorsUndetected ErrorsLogic Errors

2-103

Syntax ErrorsSyntax ErrorsMissing semicolon at the end of the variable

declarationUndeclared variable milesLast comment is not closed because of blank in

*/ close-comment sequenceRun-Time Errors (Figure 2.16)

an attempt to perform an invalid operation, detected during program execution

2-105

Run-Time Errors Run-Time Errors An attempt to perform an invalid operation,

detected during program execution

2-107

Logic ErrorsLogic ErrorsAn error caused by following an incorrect algorithm

2-110

Questions?Questions?

Recommended