21
UNIT 1 C, C++ and Data Structures Introduction C is a general-purpose programming language. It has been closely associated with the UNIX operating system where it was developed, since both the system and most of the programs that run on it are written in C. The language, however, is not tied to any one operating system or machine; and although it has been called a “system programming language'' because it is useful for writing compilers and operating systems, it has been used equally well to write major programs in many different domains. History: Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The influence of BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson in 1970 for the first UNIX system on the DEC PDP7. BCPL and B are ``typeless'' languages. By contrast, C provides a variety of data types. C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It was designed and written by a man named Dennis Ritchie by 1973 UNIX OS almost totally written in ``C''. C is often called a "Middle Level" programming language because it contains the features of both high level and low level language features. Characteristics of C We briefly list some of C's characteristics that define the language and also have lead to its popularity as a programming language. Naturally we will be studying many of these aspects throughout the course. Small size Extensive use of function calls Loose typing -- unlike PASCAL Structured language Low level (BitWise) programming readily available Pointer implementation - extensive use of pointers for memory, array, structures and functions. Fundamentals of C language: C Character Set: There are 256 characters in C. The character set in C Language can be grouped into the following categories. A character denotes any alphabet, digit or special symbol used to represent information. Figure 1.2 shows the valid alphabets, numbers and special symbols allowed in C. Al ph abets a,b,c,…..,x, y, z, A, B,C,….,X,Y,Z Digits 1,2,3,4,5,6,7,89,0 Special Symbols ~ ! @ # $ % ^ & * ( ) _ - + = | \ { } [ ] : ; ‘ < > , . ? / White Spaces White Spaces are ignored by the compiler until they are a part of string constant. White Space may be used to separate words, but are strictly prohibited while using between characters of keywords or identifiers. Identifier: M.Sc Integrated Nano Technology Page 1

Nano Unit I Notes

Embed Size (px)

Citation preview

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 1/21

UNIT – 1 C, C++ and Data Structures

IntroductionC is a general-purpose programming language. It has been closely associated with the UNIXoperating system where it was developed, since both the system and most of the programsthat run on it are written in C. The language, however, is not tied to any one operatingsystem or machine; and although it has been called a “system programming language''because it is useful for writing compilers and operating systems, it has been used equally

well to write major programs in many different domains.

History:Many of the important ideas of C stem from the language BCPL, developed by MartinRichards. The influence of BCPL on C proceeded indirectly through the language B, whichwas written by Ken Thompson in 1970 for the first UNIX system on the DEC PDP−7.BCPL and B are ``typeless'' languages. By contrast, C provides a variety of data types.C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It wasdesigned and written by a man named Dennis Ritchie by 1973 UNIX OS almost totallywritten in ``C''.C is often called a "Middle Level" programming language because it contains the features of both high level and low level language features.

Characteristics of C

We briefly list some of C's characteristics that define the language and also have lead to itspopularity as a programming language. Naturally we will be studying many of these aspectsthroughout the course.

• Small size• Extensive use of function calls• Loose typing -- unlike PASCAL• Structured language• Low level (BitWise) programming readilyavailable• Pointer implementation - extensive useof pointers for memory, array, structures and functions.

Fundamentals of C language:

C Character Set:

There are 256 characters in C. The character set in C Language can be grouped into thefollowing categories.A character denotes any alphabet, digit or special symbol used to represent information.Figure 1.2 shows the valid alphabets, numbers and special symbols allowed in C.Alphabets a,b,c,…..,x,y,z,A,B,C,….,X,Y,ZDigits 1,2,3,4,5,6,7,89,0Special Symbols ~ ! @ # $ % ̂ & * ( ) _ - + = | \ { } [ ] : ; “ ‘ < > , . ? /White Spaces

White Spaces are ignored by the compiler until they are a part of string constant. WhiteSpace may be used to separate words, but are strictly prohibited while using betweencharacters of keywords or identifiers.

Identifier:

M.Sc Integrated Nano Technology Page 1

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 2/21

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 3/21

UNIT – 1 C, C++ and Data Structures

Hexadecimal integer constant is preceded by OX or Ox, they may contain alphabets from Ato F or a to f. The alphabets A to F refers to 10 to 15 in decimal digits. Example of validhexadecimal integers are

OX2 OX8C OXbcd Ox

Real ConstantsReal Constants consists of a fractional part in their representation. Integer constants areinadequate to represent quantities that vary continuously. These quantities are representedby numbers containing fractional parts like 26.082. Example of real constants are

0.0026-0.97 435.29+487.0

Real Numbers can also be represented by exponential notation. The general form forexponential notation is mantissa exponent. The mantissa is either a real number expressedin decimal notation or an integer. The exponent is an integer number with an optional plusor minus sign.

Single Character ConstantsA Single Character constant represent a single character which is enclosed in a pair of quotation symbols.Example for character constants are'5' 'x' ';' ' 'All character constants have an equivalent integer value which are called ASCII Values.

String ConstantsA string constant is a set of characters enclosed in double quotation marks. The charactersin a string constant sequence may be a alphabet, number, special character and blankspace. Example of string constants are

"SURYA KAMESWARI" "1234""God Bless" "!.....?"

Backslash Character Constants [Escape Sequences]Backslash character constants are special characters used in output functions. Althoughthey contain two characters they represent only one character. Given below is the table of escape sequence and their meanings.

Constant Meaning

 ‘\a’ Audible alert (Bell) ‘\b’ back space ‘\f’ form feed ‘\n’ new line ‘\r’ carriage return

 ‘\t’ horizontal tab ‘\v’ Vertical tab ‘\’’ Single quote ‘\”’ Double quote ‘\?’ question mark ‘\\’ back slash ‘\0’ null

M.Sc Integrated Nano Technology Page 3

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 4/21

UNIT – 1 C, C++ and Data Structures

Data types:The type of a variable determines what kinds of values it may take on.Data types are distinguished as

a) Intrinsic or basic data types: int, char, float , double etc.,b) Derived data types: array , pointer etc.,c) User defined data types: structures, unions etc.,

A type modifier alters the meaning of the base data type to yield a new type. Each of thesetype modifiers can be applied to the base type int. The modifiers signed and unsigned canalso be applied to the base type char. In addition, long can be applied to double. When thebase type is omitted from a declaration, int is assumed.Type Length Rangeunsigned char 8 bits 0 to 255char 8 bits -128 to 127enum 16 bits -32,768 to 32,767unsigned int 16 bits 0 to 65,535short int 16 bits -32,768 to 32,767int 16 bits -32,768 to 32,767unsigned long 32 bits 0 to 4,294,967,295long 32 bits -2,147,483,648 to 2,147,483,647float 32 bits 3.4 * (10**-38) to 3.4 * (10**+38)double 64 bits 1.7 * (10**-308) to 1.7 * (10**+308)long double 80 bits 3.4 * (10**-4932) to 1.1 * (10**+4932)

Variables

A variable is a value that can change any time. It is a memory location used to store a datavalue. A variable name should be carefully chosen by the programmer so that its use isreflected in a useful way in the entire program. Variable names are case sensitive.Example of variable names are Sum1 number Salary Emp_nameAny variable declared in a program should confirm to the following1. They must always begin with a letter, although some systems permit underscore as thefirst character.

2. The length of a variable must not be more than 8 characters.3. White space is not allowed and4. A variable should not be a Keyword5. It should not contain any special characters.Examples of Invalid Variable names are123 (area) 6th %abc

Declaration of Variables:

In C language all variables must be declared before they are used. Declaration meansmapping the association between the variable and data types.Syntax: storage-class datatype variable;Example: static int a;

float b;int x,y,z;

Symbolic Constants:

A symbolic name substitutes a sequence of characters or numerical value that follows it.# define PI 3.14159# define MAX 50

M.Sc Integrated Nano Technology Page 4

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 5/21

UNIT – 1 C, C++ and Data Structures

Use of #define in the program makes easy to read. That is it makes easy to recognizeconstants. For example substituting PI for 3.1415 makes the program to read easier. Here itis easy to recognize the constant 3.1415.

Assignment Statement:

a statement is simply a single line of code that performs some action. Remember that

another word for a statement is an expression.Each statement performs a different action—but it does perform some action—and it endswith a semicolon. The first statement/expression simply declares a variable. The secondstatement/expression sets that variable equal to some value. Finally, the laststatement/expression performs addition and puts the answer in the variable that waspreviously declared.The commonly used assignment operator is = Assignment expressions that make use of thisoperator are written in the form

Identifier = expressionHere identifier represents a variable and expression represents a constant, a variable or amore complex expression e.g. Here are some typical assignment expressions that make useof the = operatora = 3x = ysum = a+barea = length * width.

Storage Classes:

strong class provides information about their location and visibility.The storage classdecides the portion of the program within which the variables are recognized. A variablesstorage class tells us

1.where the variables would be stored.

2.What will be the initial value of the variable,if the initial value is not specifically assigned.3.What is the scope of the variable i.e., which functions the value of the variable would beavailable.4.What is the lifetime of the variable, i.e., how long the variable exist.There are 4 types of storage classes in C.

1. Automatic

The auto variables stored in memory.Its default initial value is garbage value.Scope of the variable is within the function in which it is declared/defined.Lifetime: Till the control remains in the block in which the variable is defined.ex1: main()

{

auto int x,y;printf("%d" \t %d", x,y);}

Output: Some garbage values we getSo that different times of running this program, we can get different outputs. To

examine scope and lifetime of variable (auto)

Ex:

M.Sc Integrated Nano Technology Page 5

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 6/21

UNIT – 1 C, C++ and Data Structures

main(){auto int i=1;{auto int i=2;{

auto int i=3;printf("%d \n", i);}printf("%d \n", i);}printf("%d \n", i);}

Output: 321

2. Static

The static variables are stored in memory.Its default initial value is Zero.Scope of this variable is local to the variable in which it is defined.Lifetime: value of the variable persists between different function calls.

Once the variable is declared as static, if the control comes back to the same function againthe static variables have the same values they had last time around.

Ex:main(){

increment();

increment();increment();

}increment(){static int i=1;printf("%d \n", i);i=i+1;

}Output:123

Once the variableis declared as static, that variable is initialized only oncew though formany function calls. In the above exampl, for the first function call of increment(), i=1theni=1 is printed then i value incremented to 2. Then for second functioncall, the firststatement initialization of i is not executed, o/p is 2 then i is incremented to 1 becomes3,for third function call,again 3 gets printed on screen.The advantage of defining thevariable as stati is the value of variable can persist for different function calls. The differentbetween a static external variable and a simple external variable is that the static external

M.Sc Integrated Nano Technology Page 6

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 7/21

UNIT – 1 C, C++ and Data Structures

variable is available only within the file where it is defined while the simple externalvariable can be accessed by other files

3. External 

External type of variable is also stored in memory.Its default initial value is Zero.Scope of the variable is global.

Lifetime: As long as the program's execution doesnt come to an end.External variables are declared outside all functions, hence available to all functions.

Variables that are both alive and active throughout program are known as externalvariables. They are also known as global variables.

Ex:int x;main(){x=10;printf("%d", x);printf("x=%d \n" fun1());printf("x=%d \n" fun2());printf("x=%d \n" fun3());}fun1(){x=x+10;return(x);}fun2(){int x;x=1;return(x);

}fun3(){x=x+10;return(x);}Output:10x=20x=1x=30 

Once a variable has been declared as global, any function can use it and change its value.

Then, subsequent functions can reference only that new value. Because of this property, weshould try to use global variables only for tables or for variables shared between functionswhen it is inconvenient to pass them as variables. Other aspect of global variable is that isonly visible from the point of declaration to the end of the program.

Ex:

main()

M.Sc Integrated Nano Technology Page 7

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 8/21

UNIT – 1 C, C++ and Data Structures

{y=5;printf("%d", y);fun1();}int y;

fun1(){y=y+1;printf("%d", y);}

In main function, y is not defined. So the compiler will issue an error message. As globalvariable are initialized to zero in fun1(), y=0 hence output is 1. In this above program, themain cannot access the variable y as it declared after main. This problem can be solved bydeclaring the variable with the storage class extern. Take above example again it can bemodified as

main(){extern int y=5; /* declaration */printf("%d", y);fun1();}int y;fun(){y=y+1;printf("%d",y);}

Now, no compiler time error occurs as y is declared as extern in main function. Theexternal declaration of y inside the functions informs the compiler that y is declared

somewhere else in the program. Note that, the external declaration does not allocatestorage space for variables. In case of arrays, the definition should include their size as well.

Functions are extern by default; we declare them without the qualifier extern. Forfunctions also memory is allocated when it is defined with its parameters and function body.Void print(); is equivalent to extern void print()

4.Register

The values of the variables are stored in CPU registers.Its default initial value is garbage value.Its scope is local to the block in which variable is defined.Lifetime of the variable is till the control remains within the block in which the variable isdefined.

If the variable is used at many places in a program, it is better to declare variable as

register as the value stored in CPU register can always be accessed faster than the onewhich is stored in memory.

As the value of variable is stored in CPU registers, accessing the value of that variable isfast Hence generally loop variables are declared as registers to improve the execution(accessing) speed.

Ex: main(){

M.Sc Integrated Nano Technology Page 8

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 9/21

UNIT – 1 C, C++ and Data Structures

register int i;for(i=1;i<=10;i++)printf("\n %d",i);

}

Output:

1234567

89

10Sometimes even though the variable is declared as register, if registers are not available

(as the numbers of registers are limited in CPU) the variable works as if its storage class isauto. We cannot use register storage class for all types of variables.

Ex:register float a;register float b;register float c;All above declarations are wrong because the CPU registers in micro computers are

usually 16 bit registers and therefore cannot hold a float or double (8 bytes) or long (8bytes). Though above declarations are wrong the compiler does not generate any error, itdeclares the variables a,b,c as auto storage class.

OPERATORS

• ARITHMETIC OPERATORS

There are five arithmetic operators in C . They areOperator Purpose+ Addition - Subtraction * Multiplication / Division% Remainder after integer division. (modulus operator)Type cast

The value of an expression can be converted to a different data type. If desired to do so theexpression must be preceded by the name of the desired data type enclosed in parentheses.(data type) expressionThis type of construction is known as a cast ( It is also called a type cast.) Suppose that i isan integer variable whose value is 7, and f is floating- point variable whose value is 8.5. The

expression (i +f) % 4 is invalid because the first operand (i + f) is floating point rather thaninteger. However the expression ((int) (i + f)) % 4 forces the first operand to be an integerand is therefore valid, resulting in the integer remainder 3.

• UNARY OPERATORS

C includes a class of operators that act upon a single operand to produce a new value suchoperators are known as unary operators. Unary operators usually precede their singleoperands, though some unary operators are written after their operands.

(i) UNARY MINUS

M.Sc Integrated Nano Technology Page 9

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 10/21

UNIT – 1 C, C++ and Data Structures

Unary minus is a unary operator where a minus sign precedes a numerical constant,a variable or an expression. In C, all numeric constants are positive. Thus a negativenumber is actually an expression consisting of the unary minus operator followed bya positive number.e.g. - 743, -0 X 7FFF, -0.2, -5E -8, -root 1, -(x +y) -3 * (x+y)(ii) INCREMENT OPERATOR AND DECREMENT OPERATOR 

The increment operator (++) causes its operand to be increased by one where asthe decrement operator causes its operand to be decreased by one. The operandused with each of this operator must be a single variable.e.g. Suppose i is an integer variable that has been assigned a value of 5. Theexpression ++i, causes the value of i to be increased by one, Whereas thedecrement operator causes thevalue to be decreased by 1 so, now the new variable of i will be 4i ++ means i = i + 1— i means i = i-1The increment and decrement operators can each be utilized in two different ways,depending on whether the operator is written before or after the operand. If theoperator precedes the operand (e.g. ++ i) then the operand will be altered in valuebefore it is utilized for its intended purpose within the program. If however, theoperator follows the operand (e.g i ++) then the value of the operand will be alteredafter it is utilizede.g. printf (“ i = %d\n”, i);printf (“ i = % d\n”, ++i);printf (“ i = %d\n”, i);There printf statements will generate following three lines of out puti = 1i = 2i =2Now let us take the second caseprintf (“ i = %d\n”, i);printf (“ i = %d\n”, i++);

printf ( i = %d\n”, i )The statement will generate the following three lines of outputi = 1i = 1i = 2

• LOGICAL OPERATORS

There are two logical operators also available in C. They areOperator Meaning&& and|| orThe result of a logical and operation will be true only if both operands are true where as the

result of a logical or operation will be true if either operand is true or if both operands aretrue. In other words the result of a logical or operation will be false only if both operandsare false. Suppose i is an integer variable whose value is 7, f is a floating point variablewhose value is 5.5 and C is a character variable that represents the character ‘w’, severalcomplex logical expressions that make use of these variables are shown below:Expression Interpretation Value(i > = 6)&&(c = = 'w') true 1(i >= 6)&&(c = = 119) true 1

M.Sc Integrated Nano Technology Page 10

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 11/21

UNIT – 1 C, C++ and Data Structures

(f < 11) && (i > 100) false 0(c = 'p') || ((i + f) < =10) true 1

• RELATIONAL AND LOGICAL OPERATORS

These are four relational operators in C. They are

Operator Meaning< Less than<= Less than or equal to> Greater than>= Greater than or equal to

• EQUALITY OPERATORS

There are two equality operators in C which are as followsOperators Meaning= = Equal to! = Not equal toThe six operators mentioned above are used to form logical expressions representingconditions that are either true or false.The resulting expression will be of type integer, since true is represented by the integervalue 1 and false is represented by the value 0.e.g . Let us suppose i, j and k are integer variables whose values are 1,2 and 3 respectively.Several logical expressions involving these variables are shown below.Expression Interpretation Valuei < j true 1(i + j) > = k true 1(j + k) > (i + 5) false 0k ! = 3 false 0 j = = 2 true 1Expression Interpretation Value(i > = 6)&&(c == 'w') true 1

(i > = 6) || (c = = 119) true 1(f < 11) && (i > 100) false 0(c1 == 'p') || ((i + f) < = 10) true 1Both operands are true hence expression is trueBoth operands are true hence expression is trueSecond operand is false hence expression is falseFirst operand is true hence expression is true

• ASSIGNMENT OPERATORS

The commonly used assignment operator is = Assignment expressions that make use of thisoperator are written in the formIdentifier = expressionHere identifier represents a variable and expression represents a constant, a variable or amore complex expression e.g. Here are some typical assignment expressions that make useof the = operatora = 3x = ysum = a+barea = length * width. In addition, C has a set of shorthand assignment operators of the form.

var oper = exp;

M.Sc Integrated Nano Technology Page 11

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 12/21

UNIT – 1 C, C++ and Data Structures

Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. Theoperator oper = is known as shorthand assignment operatorExample

x + = 1 is same as x = x + 1The commonly used shorthand assignment operators are as follows

Statement with simpleassignment operator

Statement withshorthand operator

a = a + 1 a += 1

a = a – 1 a -= 1

a = a * (n+1) a *= (n+1)

a = a / (n+1) a /= (n+1)

a = a % b a %= b

• THE CONDITIONAL OPERATOR 

Conditional operator is (?:) A expression that makes use of the conditional operator is calleda conditional expressionfor e.g. expression 1? expression 2 : expression 3When evaluating a conditional expression, expression 1 is evaluated first. If the expression1 is true then expression 2 is evaluated and this becomes the value of conditionalexpression However, if expression 1 is false then expression 3 is evaluated and this

becomes the value of the conditional expression e.g. In the conditional expression shownbelow suppose f and g are floating point variables. The conditional expression is (f < g)?f: gIt takes the value f if f is less than g otherwise the conditional expression takes on the valueof g. In other words conditional expression returns the value of the smaller of the twovariables.

BITWISE OPERATORS:

C has a distinction of supporting special operators known as bitwise operators formanipulation data at bit level. A bitwise operator operates on each bit of data. Thoseoperators are used for testing, complementing or shifting bits to the right on left. Bitwiseoperators may not be applied to a float or double.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise Exclusive

M.Sc Integrated Nano Technology Page 12

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 13/21

UNIT – 1 C, C++ and Data Structures

<< Shift left

>> Shift right

• SPECIAL OPERATORS

C supports some special operators of interest such as comma operator, size of operator,pointer operators (& and *) and member selection operators (. and ->). The size of and thecomma operators are discussed here. The remaining operators are discussed in forthcoming chapters.

THE COMMA OPERATOR The comma operator can be used to link related expressions together. Comma-linked lists of expressions are evaluated left to right and value of right most expression is the value of thecombined expression.

For example the statement

value = (x = 10, y = 5, x + y);First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowestprecedence in operators the parenthesis is necessary. Some examples of comma operatorare

In for loops:for (n=1, m=10, n <=m; n++,m++)In while loopsWhile (c=getchar(), c != ‘10’)Exchanging valuest = x, x = y, y = t;

THE sizeof OPERATOR 

The operator size of gives the size of the data type or variable in terms of bytes occupied inthe memory. The operand may be a variable, a constant or a data type qualifier.Examplem = sizeof (sum);n = sizeof (long int);k = sizeof (235L);The size of operator is normally used to determine the lengths of arrays and structureswhen their sizes are not known to the programmer. It is also used to allocate memory spacedynamically to variables during the execution of the program.

OPERATOR PRECEDENCE:

Table summarizes the rules for precedence and associatively of all operators. Operators on

the same line have the same precedence; rows are in order of decreasing precedence, so,for example, *, /, and % all have the same precedence, which is higher than that of binary+ and −. The ``operator” () refers to function call. The operators −> and . are used toaccess members of structures.

Operator Description Associativity

() Parentheses (function call) (see Note 1) left-to-right

M.Sc Integrated Nano Technology Page 13

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 14/21

UNIT – 1 C, C++ and Data Structures

[].

->++ --

Brackets (array subscript)Member selection via object nameMember selection via pointerPostfix increment/decrement (see Note 2)

++ --

+ -! ~

(type)*& 

sizeof 

Prefix increment/decrement

Unary plus/minusLogical negation/bitwise complementCast (change type)DereferenceAddressDetermine size in bytes

right-to-left

* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <=> >=

Relational less than/less than or equal toRelational greater than/greater than or equal to

left-to-right

== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

=+= -=

*= /=%= &=^= |=

<<= >>=

AssignmentAddition/subtraction assignment

Multiplication/division assignmentModulus/bitwise AND assignmentBitwise exclusive/inclusive OR assignmentBitwise shift left/right assignment

right-to-left

, Comma (separate expressions) left-to-right

Note 1: Parentheses are also used to group expressions to force a different order of evaluation; such parenthetical expressions can be nested and are evaluatedfrom inner to outer

Note 2: Postfix increment/decrement have high precedence, but the actual incrementor decrement of the operand is delayed (to be accomplished sometime beforethe statement completes execution). So in the statement y = x * z++; thecurrent value of z is used to evaluate the expression (i.e., z++ evaluates toz) and z only incremented after all else is done.

M.Sc Integrated Nano Technology Page 14

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 15/21

UNIT – 1 C, C++ and Data Structures

DATA-TYPE CONVERSIONS:

Many C operators cause implicit type conversions, which change the type of an expression.

C performs data-type conversions in the following four situations:

• When two or more operands of different types appear in an expression.• When arguments of type char, short, and float are passed to a function using the old

style declaration.• When arguments that do not conform exactly to the parameters declared in a

function prototype are passed to a function.• When the data type of an operand is deliberately converted by the cast operator

Usual Arithmetic Conversions

The following rules-referred to as the usual arithmetic conversions- govern the conversionof all operands in arithmetic expressions. The effect is to bring operands to a common type,which is also the type of the result. The rules govern in the following order:

1. If either operand is not of arithmetic type, no conversion is performed.

2.If either operand has type long double , the other operand is converted to longdouble .

3. Otherwise, if either operand has type double , the other operand is converted todouble .

4. Otherwise, if either operand has type float , the other operand is converted to float .5. Otherwise, the integral promotions are performed on both operands, and the

following rules apply:1. If either operand has type unsigned long int , the other operand is converted

to unsigned long int .2. Otherwise, if one operand has type long int and the other has type unsigned

int , and if a long int can represent all values of an unsigned int , the operandof type unsigned int is converted to long int . If a long int cannot represent allthe values of an unsigned int , both operands are converted to unsigned long

int .3. Otherwise, if either operand has type long int , the other operand is converted

to long int .4. Otherwise, if either operand has type unsigned int , the other operand is

converted to unsigned int .5. Otherwise, both operands have type int .

The following sections elaborate on the usual arithmetic conversion rules.

Characters and Integers

A char, short int , or int bit field, either signed or unsigned, or an object that hasenumeration type, can be used in an expression wherever an int or unsigned int is

permitted. If an int can represent all values of the original type, the value is converted to anint . Otherwise, it is converted to an unsigned int . These conversion rules are called theintegral promotions.This implementation of integral promotion is called value preserving, as opposed tounsigned preserving in which unsigned char and unsigned short widen to unsigned int . DECC uses value- preserving promotions, as required by the ANSI C standard, unless thecommon C mode is specified.To help locate arithmetic conversions that depend on unsigned preserving rules, DEC C,with the check option enabled, flags any integral promotions of unsigned char and unsigned

M.Sc Integrated Nano Technology Page 15

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 16/21

UNIT – 1 C, C++ and Data Structures

short to int that could be affected by the value-preserving approach for integralpromotions.All other arithmetic types are unchanged by the integral promotions.In DEC C, variables of type char are bytes treated as signed integers. When a longer integeris converted to a shorter integer or to char, it is truncated on the left; excess bits arediscarded. For example:

int i;char c;

i = 0xFFFFFF41;c = i;This code assigns hex 41 (‘A’) to c. The compiler converts shorter signed integers to longerones by sign extension.

Signed and Unsigned IntegersConversions also take place between the various kinds of integers.When a value with an integral type is converted to another integral type (such as intconverted to long int) and the value can be represented by the new type, the value isunchanged.When a signed integer is converted to an unsigned integer of equal or greater size, and thesigned integer value is nonnegative, its value is unchanged. If the signed integer value isnegative, then:

• If the unsigned integer type is larger, the signed integer is first promoted to thesigned integer that corresponds to the unsigned integer; then the value is convertedto unsigned by adding to it one greater than the largest number that can berepresented in the unsigned integer type.

• If the unsigned integer type is equal or smaller than the signed integer type, thenthe value is converted to unsigned by adding to it one greater than the largestnumber that can be represented in the unsigned integer type.

When an integer value is demoted to an unsigned integer of smaller size, the result is thenonnegative remainder of the value divided by the number one greater than the largest

represent able unsigned value for the new integral type.When an integer value is demoted to a signed integer of smaller size, or an unsignedinteger is converted to its corresponding signed integer, the value is unchanged if it is smallenough to be represented by the new type. Otherwise, the result is truncated; excess high-order bits are discarded and precision is lost.Conversion between integral types of the same size, whether signed or unsigned, results inno machine-level representation change.

Floating and Integral

When a floating-type operand is converted to an integer, the fractional part is discarded.When a floating-type value is to be converted at compile time to an integer or anotherfloating type, and the result cannot be represented, the compiler reports a warning in thefollowing instances:

• The conversion is to unsigned int and the result cannot be represented by theunsigned int type.

• The conversion is to a type other than unsigned int , and the result cannot berepresented by the int type.

When a value of integral type is converted to floating type, and the value is in the range of values that can be represented, but not exactly, the result of the conversion is either thenext higher or next lower value, whichever is the natural result of the conversion on thehardware.

M.Sc Integrated Nano Technology Page 16

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 17/21

UNIT – 1 C, C++ and Data Structures

Floating TypesIf an operand of type float appears in an expression, it is treated as a single-precision objectunless the expression also involves an object of type double or long double , in which casethe usual arithmetic conversion applies.When a float is promoted to double or long double, or a double is promoted to long double ,its value is unchanged.

The behavior is undefined when a double is demoted to float, or a long double to double orfloat , if the value being converted is outside the range of values that can be represented.If the value being converted is inside the range of values that can be represented, but notexactly, the result is rounded to either the next higher or next lower represent able floatvalue.

Operand Type Conversion

One operand has long double type The other operand is converted to long

double.One operand has double type The other operand is converted to

double.

One operand has float type The other operand is converted to float.One operand has unsigned long long int

typeThe other operand is converted tounsigned long long int 

One operand has long long type. The other operand is converted to long

long.One operand has unsigned long int type The other operand is converted to

unsigned long int.

One operand has unsigned int type andthe other operand has long int type andthe value of the unsigned int can be

represented in a long int 

The operand with unsigned int type isconverted to long int.

One operand has unsigned int type andthe other operand has long int type andthe value of the unsigned int cannot berepresented in a long int 

Both operands are converted to unsignedlong int.

One operand has long int type The other operand is converted to long

int.One operand has unsigned int type The other operand is converted to

unsigned int.Both operands have int type The result is type int.

Mathematical Functions:

C language has many pre defined or library functions. Mathematical functions available in Care:

(i) abs (): absolutegets the absolute value of an integer

abs(x) where x is an integerprototype: int abs(int);

M.Sc Integrated Nano Technology Page 17

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 18/21

UNIT – 1 C, C++ and Data Structures

ex: int a=abs(-54)o/p: 54

(ii) floor: rounds downreturns the largest integer less than or equal to given double value.prototype: double floor(double);

ex: double d=floor(56.745);o/p: 56

(iii) ceil: rounds upreturns the smallest integer greater than or equal to given double value.Prototype: double ceil(double);

Ex: double d=floor(56.745);o/p: 57

(iv) exp: calculate e to the x’th powerprototype: double exp(double);

ex: double d=exp(3)o/p: 20.08554

(v) pow: power function, x to the ydouble pow(double, double);

ex: double d=pow(5,4.5)o/p: 1397.542486

(vi) sqrt: calculates square rootIt returns the square root of x.double sqrt(double);

ex: double d=sqrt(8);o/p: 2.828427125

SINGLE CHARACTER INPUT - THE getchar( ) FUNCTION

Single characters can be entered in to the computer using the C library function getchar( ).The getchar function is a part of the standard C Language i/o Library. It returns a singlecharacter from a standard input device. The function does not require any arguments,though a pair of empty parentheses must follow the word getchar. In general terms areference to the getchar function is written as

character variable = getchar( );

Here character variable refers to some previously declared character variable

SINGLE CHARACTER OUTPUT-THE putchar( ) FUNTION

The putchar( ) function, like getchar( ), is a part of the standard C language i/o library. Ittransmits a single character to a standard output device. The character being transmittedwill normally be represented as a character- type variable. It must be expressed as anargument to the function enclosed in parentheses following the word putchar. In general areference to the putchar function is written as .

M.Sc Integrated Nano Technology Page 18

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 19/21

UNIT – 1 C, C++ and Data Structures

putchar( char var )

e.q A C-Program contains the following statement :char C; __ _ __ _

 __ _ __ _putchar(C);

The first statement declares that C is a character type variable. The second statementcauses the current value of C to be transmitted to the standard output device.

ENTERING INPUT DATA THE scanf( ) FUNTION

Input data can be entered into the computer from a standard input device by means of theC library function scanf().In general terms, the scanf function is written as

scanf(Control string, arg1,arg2,.....,argn)

Here control string refers to a string containing certain required formatting information, andarg1, arg2,...arg n are arguments that represent the individual input data items. Thearguments represent pointers that indicate the addresses of the data item within thecomputers memory.The control string comprises individual groups of characters with one character group foreach input data item. Each character group must begin with a a percent sign( % ). In itssimplest form a single character group will consist of the percent sign, followed by aconversion character which indicates the type of the corresponding data item.

COMMONLY USED CONVERSION CHARACTERS FOR DATA INPUT

Meaning

%c data item is a single character%d data item is a decimal integer%f data item is a floating point value%h data item is a short integer%I data item is a decimal, hexadecimal or octal integer%o data item is an octal integer%s data item is a string followed by white space character%u data item is an unsigned decimal integer%x data item is a hexadecimal integere.q of scanf function# include <stdio.h>main( ){

char item [20];int partno;float cost;. . .

scanf(“%s% d % f”, item, &partno, & cost);. . .

}

M.Sc Integrated Nano Technology Page 19

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 20/21

UNIT – 1 C, C++ and Data Structures

The first character group % s indicates that the first argument (item) represents a stringthe second character group, %d indicates that the second argument ( & partno) representsa decimal integer value. The third character group % f, indicates that the third argument (& cost) represents a floating point value.e.q. consider the skeleton of the following program# include <stdio.h>

main( ){char item [20];int partno;float cost;. . .

scanf(“%s%d%f”, item, &partno, &scost);}The following data items could be entered from the standard input device when the programis executed.fastener 12345 0.05orfastener123450.0 5Now let us again consider the skeleton structure of a C program# include <stdio.h>main ( ){int a,b,c;. . .scanf (“%3d %3d %3d”, & a, & b, & c);. . .}Suppose the input data items are entered as

1 2 3Then the following assignment is will resulta = 1, b = 2, c = 3It data is entered as123 456 789The following assignments would bea = 123, b = 456, c = 789Now suppose that the data had been entered as123456789The assignments would bea = 123, b = 456, c = 789Again consider the following example# include <stdio.h>

main ( ){ int i ;float x;char c ;. . .scanf (“%3d %5f %c”, & i, & x, & c);. . .}

M.Sc Integrated Nano Technology Page 20

8/8/2019 Nano Unit I Notes

http://slidepdf.com/reader/full/nano-unit-i-notes 21/21

UNIT – 1 C, C++ and Data Structures

If the data item are entered as10256.875 TThese when the program will be executed 10 will be assigned to I 256.8 will be assigned tox and the character 7 will be assigned to c. the remaining two input characters (5 and T)will be ignored.

WRITING OUTPUT DATA - THE printf( ) FUNCTION

Output data can be written from the computer on to a standard output device using thelibrary function printf the general form of printf function is

printf(control string, arg 1, arg 2, . . ., argn)

where control string refers to a string that contains formatting information.arg1, arg 2, . . ., argn are arguments that represent the individual output data items.

e.g:- Following is a simple program that makes use of the printf function.# include <stadio.h># include <math.h>main ( ) /* Print several floating-point numbers */{float i = 2.0, j = 3.0 ;printf (“%f %f %f %f”, i, j, i+j, sqrt (i + j ));}Executing the program produces the following output2.000000 3.000000 5.000000 2.236068

The gets( ) and puts( ) FUCTIONS

The gets and puts are the functions which facilitate the transfer of strings between thecomputer and the standard input/output devices. Each of these functions accepts a single

argument. The argument must be a data item that represents a string (e.g, a characterarray). The string may include white space characters. In the case of gets, the string will beentered from the keyboard and will terminate with a newline character (“i’e” the string willend when the user presses the RETURN key).# include <stdio.h>main ( ){char line [80];gets(line);puts(line);}Now suppose following string is entered from the standard input deviceI am happy

Now the output of the program will beI am happy

M.Sc Integrated Nano Technology Page 21