64
C ” HISTORY OF “C”: C ” is one of the most popular computing languages today because it is structured, high-level, machine independent language. It allows software developers to develop programs without worrying about the hardware platforms where they will be implemented. The root of all modern languages is “ ALGOL ”, introduced in 1960’s. In 1967, Martin Richards developed a language called “BPCL” (Basic Combined Programming Language). In 1970, Ken Thompson created a language using many features of BPCL and simply called it “B”. B was used to create early versions of UNIX operating systems at “ Bell Laboratories ”. Both BPCL and B were “ typeless ” system programming languages. “ C ” finally evolved from ALGOL, BPCL and B by Dennis Ritchie at Bell Laboratories in 1972. “ C ” is strongly 1

C LANGUAGE

Embed Size (px)

DESCRIPTION

C MATERIAL

Citation preview

Formats for Datatypes:

C

HISTORY OF C:

C is one of the most popular computing languages today because it is structured, high-level, machine independent language. It allows software developers to develop programs without worrying about the hardware platforms where they will be implemented.

The root of all modern languages is ALGOL , introduced in 1960s. In 1967, Martin Richards developed a language called BPCL (Basic Combined Programming Language).

In 1970, Ken Thompson created a language using many features of BPCL and simply called it B. B was used to create early versions of UNIX operating systems at Bell Laboratories . Both BPCL and B were typeless system programming languages.

C finally evolved from ALGOL, BPCL and B by Dennis Ritchie at Bell Laboratories in 1972. C is strongly associated with UNIX as it was developed along with it. The operating system used at Bell Laboratories was coded almost entirely in C .

The language became popular after publication of the book The C Programming Language by Brian Kerningham and Dennis Ritchie in 1978. The book was so popular that the language came to be known as K & R C .ABOUT C LANGUAGE: There are 32 keywords and its strength lies in its built-in functions. C language is case sensitive.

C is a free-form language. That is, the C compiler does not care, where on the line we begin typing.

FORMAT OF A C PROGRAM:Documentation Section

Link Section

Definition Section

Global Declaration Section

main( )

/* Function name

{

/* Start of the program */

Declaration part

/* Function body */

Executable part

}

/* End of program */

Subprogram Section

Function 1

Function 2

/* User-defined functions */

Function n

The Documentation Section consists of a set of comment lines giving the name of the program and other details, which the programmer would like to use later.

The Link Section provides instructions to the compiler to link functions from the system library.

The Definition Section defines all symbolic constants.

Variables used in more than one function are called as Global Variables . These variables can be declared in the Global Declaration Section. This Section is also used to declare all the User-defined functions. Every C program must have one main function section. This section consists of two parts, declaration part and executable part. The declaration part declares all the variables used in the executable part. The program execution begins at the opening brace and ends at the closing brace of the main function.

The Subprogram Section contains all the User-defined functions that are called either in the main function or the in the other User-defined functions.

main( ):

The main( ) is a special function used by C to tell the computer where the programs starts. Every C program must contain main( ) . It is not possible to run the program without main( ) . Its operating system which calls main( ) when program is executed. main( ) is not a reserved word, but a user defined function. It is not stored in any header file.

C permits different forms of main statements. Following are allowed.

main( )

/* These 2 statements are one and the same */

main(void)

void main( )

/* These 2 statements are one and the same */

void main(void)

int main( )

/* These 2 statements are one and the same */

int main(void)

The empty pair of parenthesis indicates that the function has no arguments. This may be also indicated by using the keyword void inside the parentheses. We can specify the keywords int and void before the word main. The keyword void means that the function does not return anything to the operating system and keyword int means that the function returns an integer value to the operating system.DATA TYPES,VARIABLES AND CONSTANTSDATA TYPES:

There are 3 data types in C . They are

1. Primary data types

2. Derived data types

3. User-defines data types

1. Primary data types:

They are 4 types of primary data types, they are

i. Integer data type

ii. Character data type

iii. Floating point data type

iv. Void data type

i. Integer data type:

They are 3 classes of integer storage, namely short int , int , long int in both signed and unsigned forms. Unsigned integers use all the bits for the magnitude of the number and are always positive but this is not the case with Signed integers.ii. Character data type:

Character data type is also of 2 forms namely signed and unsigned .iii. Floating point data type:

Floating point data type is of 3 types, namely float , double , long double.iv. Void data type:

The void type has no values. This is used to specify the type of functions. The type of the function is said to be void if the function does not return any value to the calling function.

Note:All C compilers support 5 fundamental data types namely, int , char , float , double and void .

DATA TYPES THEIR SIZES AND THEIR RANGE:

TYPESIZE (BYTES)RANGE

char (or) signed char1-128 to 127

unsigned char10 to 255

short int (or) signed short int1-128 to 127

unsigned short int10 to 255

int (or) signed int2-32768 to 32767

unsigned int20 to 65535

long int (or) signed long int4-2147483648 to 2147483647

unsigned long int40 to 4294967295

float43.4E-38 to 3.4E+38

double81.7E-308 to 1.7E+308

long double103.4E-4932 to 3.4E+4932

Note:1. For signed numbers first bit is sign bit and others are magnitude bits.

2. For float last 6 bits are used for fractional part.

3. For double last 12 bits are used for fractional part.

4. For long double last 15 bits are used for fractional part.

5. Computer assumes decimal point before the fractional part.

MAXIMUM AND MINIMUM VALUES OF DATA TYPES:

Data typeMaximumMinimumDefined in header file

integerINT_MAX (32767)INT_MIN (-32768)limits.h

longLONG_MAXLONG_MINlimits.h

unsignedUINT_MAX (65535)0limits.h

unsigned longULONG_MAX0limits.h

floatFLT_MAXFLT_MINfloats.h

doubleDBL_MAXDBL_MINfloats.h

long doubleLONGDBL_MAXLONGDBL_MINfloats.h

charCHAR_MAX (127)CHAR_MIN (-128)

unsigned charUCHAR_MAX (255)0

Note:1. We cannot store a value more than the maximum or minimum value. If we try to, cycle repeats. This is for all data types.Eg:If we try to store 32768 in an integer variable, then it gets stored as - 32768

FORMATS FOR DATA TYPES:

S.NoData typeFormat

1short%hd

2unsigned short%uh

3int%d

4unsigned%u

5long %ld

6unsigned long%ul

7char%c

8float%f

9float (To represent exponent value)%e

10float (Either normal float or exponent value)%g

11double%lf

12long double%Lf

13char array%s

Here % is called Format Specifier

2. Derived data types:

The derived data types are arrays, functions, structures and pointers.

3. User-defines data types:

Structures, Unions and Enumerations are User-defined data types.

C supports a feature known as type definition that allows users to define their own data type (identifier) to represent an existing data type. The user-defined data type can later be used to define variables.

Syntax:

typedef type identifier ;Eg 1:typedef int marks ;/* marks symbolizes int data type */

units maths, english ;Eg 2:typedef float avg ;/* avg symbolizes float data type */

avg height, weight ;

Another user-defined data type is enumerated data dype. Keyword is enum .

Syntax:

enum identifier {value 1, value 2, .., value n} ;

The identifier is an user-defined data type which can be later used to declare variables. The values in the braces are called enumeration constants. The above expression is a definition. The identifier now can be used to declare variables as below:

enum identifier V1, V2, .. , Vn ;

The variables V1, V2,., Vn can have only one of the values value 1, value 2,, value n .Eg:enum day {Monday, Tuesday,.., Sunday} ;

enum day week_st, week_end ;

week_st = Monday ;

week_end = Sunday ;

The compiler automatically assigns numbers to all enumeration constants starting from 0 and then incrementing each by 1 , ie. Monday is 0, Tuesday is 1 and so on, ie. values are incremented by 1.

If we define in this way :

enum day {Monday = 1, Tuesday,.., Sunday} ;

Here Monday is 1, Tuesday becomes 2 and so on, ie. values are incremented by 1.The definition and declaration can be combined as one statement as:

enum day {Monday, Tuesday,.., Sunday} week_st, week_end ;KEYWORDS AND IDENTIFIRES:

Keywords (or) Reserved words:

Every C word is classified as either a keyword or an identifier. By pressing F1 key 2 times, we can display all keywords. This is available in only Turbo C .

C Keywords:

autobreakcasecharconstcontinuedefaultdo

doubleelseenumexternfloatforgotoif

intlongregisterreturnshortsignedsizeofstatic

structswitchtypedefunionunsignedvoidvolatilewhile

Identifiers (or) Variables:

Identifiers refer to the name of variables, functions and arrays. They are user-defined names.

Rules for Identifiers:

1. First character must be an alphabet (or underscore).

2. Must consist of only letters, digits or underscore.

3. ANSI recognizes only first 31 characters. However, length should not be more than 8 characters, as only first 8 characters are treated as significant by many compilers.

4. Cannot use a keyword.

5. Must not contain white space.

VARIABLES

DECLARING A VARIABLE:

Creating a variable / array and allocating memory to it is known as declaration statement. Every variable used in the program must be declared to tell the compiler what the variable names are and what type of data they hold. We cant use a variable without declaring it. Declaration statements must be written at the beginning of the program. They are processed by compiler.

Eg 1:int a = 25 ; /* Variable a is created and 2 Bytes of memory is allocated to it */

Eg 2: int x ; /* Variable x is created and it contains garbage value as it is not

initialized*/Eg 3: int a ;

float a ; /* Error, because we cannot declare the same variable by 2 data types */

Declaring Variable As volatile:

Keyword volatile tells the compiler that the value of the variable may be changed at any time by some external sources (from outside the program).

Eg :volatile int date ;

Variable declared as volatile can be modified by the program. If we dont want the variable to be altered by the program while it may be altered by some other process, then we can declare the variable as below:

volatile const int location = 100 ;

CONSTANTS:

There are 2 types of constants, they are

1. Numeric Constants

2. Character Constants

1. Numeric Constants:

They are 2 types of numeric constants, they are

i. Integer Constant

ii. Real or Float Constant

i. Integer Constant:

Its a number without a decimal point. It can be +ve, -ve integer or zero.

There are 3 types of integers, they are

a. Decimal integer

b. Octal integer

c. Hexadecimal integer

a. Decimal integer:

Base is 10 . A decimal number can contain digits 0 to 9. Format is %d .

Eg: 7642

b. Octal integer:

Base is 8 . An octal number can contain digits 0 to 7.Octal number starts with 0 . 8 and 9 are not allowed in octal numbers. Format is %o .

Eg: 07642

c. Hexadecimal integer:

Base is 16 . Hexadecimal number can contain digits 0 to 9 and alphabets A to F. Hexadecimal number starts with 0x .Format is %x .

Eg: 0x7642

ii. Real or Float Constant:

Its a number with a decimal point. There cannot be more than 1decimal point.

We can omit digits before the decimal point or digits after the decimal point.

Eg 1:215., .9526, -.715, +.512 are all valid real numbers..

A real number may also be expressed in exponential or scientific notation as below:

Eg 2:0.65e4 , 12e-2 , 1.5e+5 , 3.18E3 , -1.2E-1

Note:No white space is permitted. And exponents must only be integers.

2. Character Constants:

They are 2 character constants, they are

i. Character Constant

ii. String Constant

iii. Backslash character constantsi. Character Constant:

Its a single character enclosed in single quotes. It can be alphabets, digits or special characters. Each character is internally represented by an ASCII value. There are 256 ASCII values, range is 0 255 .

0 48 , 1 49 ,..., 9 - 57

A 65 , B 66 ,..., Z 90

a 97 , b 98 ,.., z 122

Arithmetic operations can be done on characters based on its ASCII values.ii. String Constant:

Its a collection of characters terminated by \0 called NULL character . Strings must be enclosed in double quotes. Strings may contain alphabets, digits and special characters. String is also known as Alpha numeric. \0 represents end of string. It is system which appends \0 at the end of every string.

Eg: Rajesh , 7892 , +$ , Rama Rao .

Note: 7 integer

25 integer

7 character 25 character

Hyd\0

7 string

25 string

Say string Hyd is internally represented as

There are 4 characters in the above string. The 4th character is \0.

System process strings till \0 is reached.

There is no ASCII value for strings. ASCII value is defined for each value in string, but string has no ASCII value.iii. Backslash character constants:

ConstantMeaning

\aAudible alert (Bell sound)

\bBack space

\f Form feed

\nNew line

\rCarriage return

\tHorizontal tab

\vVertical tab

\ Single quote

\ Double quote

\? Question mark

\\ Backslash

\0Null

DECLARING CONSTANTS:

Constants are declared with the help of keyword const .

Eg 1: const int a = 10;

int b = 20;

a = a + 5;/* Error */

b = b + 5;/* Ok */

Variables can be modified but not constants. a is a constant and its value is 10 for ever.

b is a variable and its value is initially 20 and is later modified to 25 .

DEFAULT VALUES OF CONSTANTS:

Integer constants by default represent int data type. We can override this fault by appending u (or) U or l (or) L or ul (or) UL to represent unsigned or long or unsigned long respectively.

Eg 1:4567U

represents unsigned intEg 2:-56789L

represents long intEg 3:987654UL

represents unsigned long int

Real constants by default represent double data type. We can override this fault by appending f or F or l (or) L to represent float or long double respectively.

Eg 1:-1.2f

represents floatEg 2:1.23456789L

represents long double

INPUT AND OUTPUT OPERATIONSINPUT FUNCTIONS

scanf( ):

Its a I/P function. scanf reads a value at runtime into variables.It is call by address function.We must send address to scanf function but not variables. It is predefined in . Predefined means that it is a function that has already been written and compiled and linked together with our program at the time of linking.

Syntax:

scanf( format strings , &variable1, &variable2, ) ;

The information contained between the parenthesis is called the argument of the function. & is address operator, which is used to accept value to that variable. Format strings are also called as Control strings.Eg 1: scanf(%d, &x) ;

Here an integer value is assigned to x .Note:Assume we have getch( ) ; at the end of the main( ).Now on the O/P window ie the screen, after typing say value of x, we press enter key, once the enter key is pressed the cursor goes to next line and then again on pressing enter key or any other key, we go back to the program menu.

If we dont have getch( ) ; at the end of main( ) the moment we press enter, we go back to the program menu.

Eg 2: scanf(%d %d %d, &x, &y, &z) ;

Here values can entered by a space or using enter key.Eg 3: scanf(%d,%d,%d, &x, &y, &z) ;

Here values should be entered by using a , in between the values.Eg 4:scanf(%d-%d-%d, &x, &y, &z) ;

Here values should be entered by using a - in between the values.

Eg 5:scanf(%d %*d %d, &x, &y, &z) ; Here if we say I/P as 10 20 30.10 is stored in x,20 is discarded and 30 is stored in y. * means not to read that particular value.Eg 6:scanf(%d, x) ;

Here x conatins garbage value but not user value.Eg 7:scanf(%d %f %c, &x, &y, &z) ;

Here we can enter space or enter between integer and float but no space or enter between float and character.

SayI/P is 10 12.25g

Here 10 gets stored in x , 12.25 in y and g in z .Eg 8:char a[40];

scanf(%s, a) ;

Here we should not use & because array name itself is address.Eg 9: x = scanf(%d %f %c, &a, &b, &ch) ;

sf returns 3 as 3 values are read and x is equal to 3 ie x = 3;

Eg 10:x = scanf(%d %d, &a, &b) ;

sf returns 2 as 2 values are read and x is equal to 2 ie x = 2;

Eg 11:x = scanf(%d, &a) ;

sf returns 1 as 1 value is read and x is equal to 1 ie x = 1;

Eg 12:x = scanf(%d %*d %d, &a, &b, &c) ;

sf returns 2 as only 2 values are read and x is equal to 2 ie x = 2;

Eg 13:while(scanf(%c, &ch) ! = -1)

{

St1;

St2;

}

The above loop is executed until user presses (Ctrl + z) . (Ctrl + z) indicates end of input. sf returns -1 when user presses (Ctrl + z) .

(Ctrl + d) for Unix and Linux.Eg 14:scanf(%2d %5d, &num1, &num2) ;

Here num1 accepts a number with field width 2 and num2 with field width 5.

Eg 15:scanf(ws, name) ;

Here the width if equal to or lesser than the number of characters typed in, only then we store the entire sting in name. If the width is lesser than the number of characters typed in, then the excess characters will be truncated and left unread.

Note:1. Input data items must be separated by spaces, tabs or newlines.

2. Punctuation marks do not count as separators.

3. scanf( ) bypasses any white space characters.

4. If we enter a floating point number for an integer, the fractional part may be stripped away and scanf( ) may skip reading further input.

5. scanf( ) terminates reading a value after its field width is reached.

6. Any unread data items will be considered as part of data I/P to the next scanf( ) call.

7. Spaces between %d and %d doesnt make a difference to the computer.

8. Dont use backslash character constants like \n \t etc in scanf.

getchar( ):

getchar( ) reads only a single character into variable. It can be alphabet, digit or special character. It is predefined in .Syntax:

char ch;

ch = getchar( ) ;If user presses h key, h is stored in variable ch. It is similar to scanf(%c, ch) ;Note:getchar( ) accepts any character keyed in including carriage return or tab.gets( ):

gets is used to read a string into an array. It is predefined in .Syntax:

gets( ):Eg:gets( array name) ;fflush(stdin):

fflush( ) is used to flush \n and the then following string overwrites \n . We must call fflush( ) before gets( ), if any other I/P is given from the user from the keyboard, otherwise gets( ) is not executed. System waits for user response when fflush( ) is called ie. rest of the program is executed only after user types a string. fflush( ) is predefined in. stdin in fflush( ) is standard I/P ie keyboard.DIFFERENCES BETWEEN scanf( ) and gets( ):scanf( )gets( )

1.scanf will read only one word.gets will read a full line.

2.scanf is formatted function because %s is used.Gets is an unformatted function`.

3.For scanf space or enter is the end.For gets only enter is the end.

4.scanf is preffered only for integers,float and characters.Gets is preferred for strings

OUTPUT FUNCTIONS

printf( ):

Its an o/p function. It is predefined in . Its call by value function.

Syntax:

printf( format strings , variable1, variable2, ..) ;

Note:Some recommend the inclusion of the statement #include

at the beginning of all programs that use input / output library functions. However this is not necessary for the functions printf and scanf which have been included as part of the C language.Eg 1:printf(%d, x) ;

Here value of x is displayed.Eg 2:printf(%d, &x) ;

Here address of x is displayed.

Eg 3:printf(%d,%f,%c, x, y, z) ;

Here values are displayed by separation of , .

If 3 spaces are there between %d and %f, then in O/P too we will have 3 spaces.

Eg 4:printf(Result is %d, a + b * c) ;

Expression is evaluated and result is displayed after the message in double quotes.

Eg 5: int a = 6782 ;

printf(%d, a) ;

Ans is 6782

printf(%7d, a) ;

Ans is _ _ _ 6782

%7d means display the value in a width of 7 columns with leading spaces.

printf(%07d, a) ;

Ans is 0006782

%07d means display the value in a width of seven columns with leading zeros.

printf(%2d, a) ;

Ans is 6782

2 in %2d is ignored while displaying 6782 as the number should be greater than 4

printf(%-7d, a) ;

Ans is 6782_ _ _

%-7d means display the value left justified in a width of 7 columns.

Eg 6:float = 123.6782 ;

printf(%.2f, a) ;

Ans is 123.67

printf(%.3f, a) ;

Ans is 123.678

printf(%5.2f, a) ;

Ans is 123.67

printf(%f, a) ;

Ans is 123.678200

If nothing is displayed before f in %f like .2 or .3, then by default

we get 6 digits after decimal point .

printf(%10.2e, a) ;

Ans is _ _1.24e+02

Exponents are displayed by using the specification %w.pe , where w

is the width, p is the precision. Default precision is 6. The value will rounded

and displayed in a width of w columns.

To display the field width at runtime the syntax is:

printf(%*.*f, width, precision, number) ;

Eg 7:printf( \ \ n ) ;

\ n is displayed .

Eg 8:printf( \ \ ) ;

\ is displayed .

Eg 9:printf( \ ) ;

is displayed .

Eg 10:printf( % %) ;

% is displayed

Eg 11:printf( \ hi \ hru) ;

hi hru is displayed .

Eg 12:printf(%wc, character) ;

The character will be displayed right-justified in the field of w columns.

Eg 13:printf(%w.ps, string name) ;

The string is displayed right-justified in a field width w and p indicates that only the first p characters of the string are to be displayed. If lesser field width is specified, it is ignored. If p is specified as 0, nothing is printed.Eg 14:printf(%d, scanf(%d %f %c, &a, &b, &ch) ) ; scanf( ) reads 3 values (int, float, char) and returns 3 .The above statement is similar to printf(%d, 3) ;Note: 1. No & in printf( ).

2. Use # (with o or x) to print octal and hexa items with precedence of 0 or 0x respectively.

3. Use # (e, f or g) to cause a decimal point to be present in all floating point numbers, even if it is whole number. Also prevents truncation of trailing zeros in g-type conversion.

4. Minus(-) after the format specifier and before the format causes the printing to be left-justified.

SOME IMPORTANT OUTPUTS:

1. printf(%d, A) ;

Ans is 65

2. printf(%c, A) ;

Ans is A

3. printf(%d, 7) ;

Ans is 55

4. printf(%d, 7) ;

Ans is 7

5. printf(%c, 7) ;

Ans is 7

6. printf(%d, . ) ;

Ans is ascii value of .

7. printf(%d, \n ) ;

Ans is ascii value of \n

8. printf(%d, \0 ) ;

Ans is 0

9. printf(%c, \0 ) ;

no O/P

DIFFERENCES BETWEEN scanf( ) AND printf( ):

scanf( )printf( )

1. This is an I/P functionThis is an O/P function

2.Read a value from keyboard into variableDisplay the value of the variable.

3. It deals with keyboard.It deals with monitor.

4. Call by address function.Call by value function.

5. Dont use \n \t in scanf( ) These characters can be used in printf( )

6. Use only variables in scanf( )We can use messages, variables and expressions.

putchar( ):

putchar( ) displays a character which is stored in a variable. putchar( ) is predefined in .

Syntax:

char ch = h ;

putchar(ch) ;

The above statement displays character h. It is similar to printf(%c, ch) ;Eg 1:putchar(7) ;

Ans is 7 Eg 2:putchar($) ;

Ans is $ Eg 3:putchar(A)

Ans is A Eg 4:putchar(A) ;

This gives error as A is string but not character.

puts( ):

puts( ) is used to display each string in new line. It is predefined in .Syntax:

puts(array name / string) ;Eg 1:puts(Hyd) ; puts(Sec) ;O/P apperars as1st line:Hyd

2nd line:Sec

Note:When we use puts( ) , the cursor after executing puts( ) will go to next line.

Eg 2:char a[ ] = Rama Rao;

printf(%s, a) ; ( or) puts(a) ;/* We can use anything */

Note:puts( ) is used to display each string in new line, whereas, pf is used to display each string in the same line.

getch( ):

getch( ) reads a character from the keyboard. Program execution stops temporarily when getch( ) is called. Statements following getch( ) are executed only after user presses any key, but not immediately. We can see O/P on the screen without pressing (Alt + F5) when getch( ) is called at the end of the program. If getch( ) is not called at the end we have to press (Alt + F5) . getch( ) is predefined in .

Syntax:

getch( ) ;Eg:printf(Hyd) ;

getch( ) ;

printf(Sec) ;

Here after displaying Hyd on the screen, computer waits for user to press any key to continue with further execution of statements. After user presses any key, Sec is displayed on the screen.clrscr( ):

clrscr( ) is used to clear the screen. clrscr( ) is predefined in .

Note:clrscr( ) should be used in any function only after declaration statements.

COMMENTS:

Comments in c are given with in /* and */ . Comments are ignored by the compiler.C files contain comments but not .exe files. Comments do not affect the execution speed and the size of a compiled program.

Note:Nested comments are not allowed.

Eg: /* = =/* = = */ = = */ This is not valid and therefore gives error.

CHARACTER TEST FUNCTIONS:

For character functions, we have to include the header file FunctionTest

isalnum(c)Is c an alphanumeric character ?

isalpha(c)Is c an alphabetic character ?

isdigit(c)Is c a digit ?

islower(c)Is c a lower case character ?

isupper(c)Is c an upper case character ?

isprint(c)Is c a printable character ?

ispunct(c)Is c a punctuation mark ?

isspace(c)Is c a white space character ?

toupper(c)Convert c to upper case alphabet.

tolower(c)Convert c to lower case alphabet.

If the question for that function is true, then that function returns True else False .Note:1. c in the function brackets is a character. It should always be in single quotes.

2. isspace( ) function includes space, \n, \t.

3. toupper( ) and tolower( ) functions return same character for any other characters apart from lower case and upper case alphabets respectively.OPERATORS, EXPRESSIONS ANDTYPE CONVERSIONSOPERATORS:

There are 8 types of operators in C .

1. Arithmatic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

5. Increment and Decrement Operators

6. Conditional Operators

7. Bitwise Operators

8. Special Operators

Note:If the above operators are not of the correct type and range in expressions, overflow and underflow errors may occur.

1. Arithmatic Operators:

OperatorMeaning

+Addition

-subtraction

*Multiplication

/Division

%Modulo division

Note:1. 6/7 Ans is 0

- 6/7

Ans is 0 (or) -1 (Machine dependent)

2. During Mudolo division, the sign of the result is the sign of the first operandEg 1:-14/3 = -2

Eg 2:-14/-3 = -2

Eg 3:14/-3 = 2

3. One major problem is division by zero. When expression is divided by zero, abnormal termination may result or in some cases meaningless results may be produced.2. Relational Operators:

OperatorMeaning

=Is greater than or equal to

= =Is equal to

!=Is not equal to

Note:It is an error if there is any space between the above operators.3. Logical Operators:

OperatorMeaning

&&AND

||OR

!NOT

Note:The output returned is either Non-zero (or) True or Zero (or) False .

4. Assignment Operators:

The usual assignment operator is = . C has a set of Shorthand assignment operators of the form:

variable operator = expression ;

The above statement is equivalent to:

variable = variable operator (expression) ;

Eg:x += y + 1 ;

The above statement is equivalent to :x = x + (y + 1) ;

5. Increment and Decrement Operators:

++ and -- are called increment and decrement operator respectively.

++ and -- means increment and decrement by 1 respectively. These are unary operators and they have only one operand.

The expansion for ++a or a++ is a=a+1 .

Here ++a is pre increment and a++ is post increment .

Eg 1:if a = 5

Then for ++a (or) a++ (or) a+=1 (or) a=a+1 , Ans is 6Eg 2:char ch = b ;

ch++ ;

Ans is c The expansion for --a or a-- is a = a - 1 .

Here --a is pre decrement and a-- is post decrement .

Eg: 1:if a = 5

Then for a (or) a--(or) a - =1 (or) a=a-1 ,

Ans is 4Eg 2:char ch = b ;

ch-- ;

Ans is a

Note: Variable increment or decrement is allowed but not value increment or decrement.

Eg: a++ or -- a is allowed but not 7++ or -- 7 .

a = 7;

b = ++a;a = 7;

b = a++;a = 7;

b = --a;a = 7;

b = a--;a = 7;

b = - a;

a = a + 1;

b = a;b = a;

a = a + 1;a = a - 1;

b = a;b = a;

a = a - 1;

a = 8

b = 8b = 7

a = 8a = 6

b = 6b = 7

a = 6a = 7

b = - 7

COMPARISON BETWEEN PRE AND POST INCREMENT:b = ++ab = a++

1.Increment a by 1.return new value.Increment a by 1.return old value.

2.Left hand side variable b contains new value.Left hand side variable contains old value.

3.Evaluate pre increment before execution of statement.Evaluate post increment after execution of statement.

4. a = +1;

b = a;b = a;

a = a+1;

Note: The above tabular column is same for pre and post decrement.

Eg 1: main( )

{

int a=7;

printf(%d, a++) ;

Ans is 7

printf(%d, a) ;

Ans is 8

}

Note: a++ in printf means

1.Display current value of a .

2.Increment a by 1 .Eg 2:main( )

{

int a=7;

printf(%d, ++a) ;

Ans is 8

printf(%d, a) ;

Ans is 8

}

Note: a++ in printf means

1.Increment a by 1 .

2.Display new value of a .Eg 3:main( )

{

int a=7;

printf(%d \t %d \t %d \t %d, a++, ++a, a++, ++a) ; Ans is 8 8 10 10 .

printf(%d, a) ;

Ans is 11

}

Note: Parameter evaluation in functions is from right to left due to stacks .

Actual value

Display

++a

8

8

a++

9

8

++a

10

10

a++

11

10

Eg 4: main( )

{

int a = 25 ;

printf(%d \t %d \t %d, a = = 25, a = 35, a = = 45) ; Ans is 0 35 0 .

printf(%d, a) ;

Ans is 35

}

Eg 5:main( )

{

int a = 4, b ;

b = pow(a++, ++a) ; (As parameter evaluation is from right to left we have

++a as 5 and a++ also as 5)

printf(a = %d, a) ;

Ans is 6 printf(b = %d, b) ;

Ans is 5 to the power of 5

}

Note:For b = pow(++a, a++) ; (a++ is 4 and ++a is 6 .Therfore answer is

6 to the power of 4)

Eg 6: main( )

{

int a = 7, b ;

b = a++ + ++a + a++ + ++a ;

printf(a = %d, a) ;

Ans is 11

printf(b = %d, b) ;

Ans is 36

}

Note: In assignments we cannot say from right to left. There is a standard

evaluation procedure.

1. Evaluate pre increments.

Above there are 2 pre increments, therefore a = 7 + 2 = 9

2. Execute the statement ie. substitute a=9 irrespective of pre or post increments.

Now b = 9 + 9 + 9 +9 = 36

3. Evaluate post increments.

There are 2 post increments, therefore a = 9 + 2 = 11

Eg 7: main( )

{

int a = 7, b ;

b=a++ * ++a;

printf(a = %d, a) ;

Ans is 9

printf(b = %d, b) ;

Ans is 64

}

Note: If you give b = a+++a;

System will think it as b = a++ + a ;

Then for a = 7 , we have b = 14 and a = 8

6. Conditional Operators( ? : ):

Conditional operator ( ? : ) is also called as ternary operator .Syntax:

variable = exp1 ? exp 2 : exp 3 ;

If exp1 is true or non zero say negative or positive, exp 2 is evaluated.

If exp1 is false or zero, exp3 is evaluated.

Thus only one exp is evaluated. Variable contains result of either exp 2 or 3.Eg: 1:a = 7 > 3 ? 100 : - 25 ;

Ans is a = 100 Eg 2: b = 6 < 4 ? 10 : 3 + 4 * 5 ;

Ans is b = 23 Eg 3: c = 7 - 7 ? - 25 : 6 / 3 * 4;

Ans is c = 8 Eg 4:d = 7 + 8 ? 100 : - 200 ;

Ans is d = 100 7. Bitwise Operators:

These operators are used in low level programming. They are used to deal with hardware of computer. They are useful while dealing with I/O ports. The operands are either 0 or 1. The different bitwise operators are :

1. & (Bitwise And operator)

2. | (Bitwise Or operator)

3. ^ (Bitwise Ex-Or operator)

4. ~ (Bitwise complement operator)

5. > (shift right) & (Bitwise And operator):

This operator performs bitwise multiplication. The different operations are :

0 & 0 = 0

0 & 1 = 0

1 & 0 = 0

1 & 1 = 1Eg:a = 25 and b = 46

32168421

a = 25

011001

b = 46

101110

001000Ans is 8 | (Bitwise Or operator):

This operator performs bitwise addition. The different operations are :

0 | 0 = 0

0 | 1 = 1

1 | 0 = 1

1 | 1 = 1

Eg:a = 25 and b = 46

32168421

a = 25

011001

b = 46

101110

111111 Ans is 63 ^ (Bitwise Ex-Or operator):

This operator performs bitwise odd operation. If there are odd number of 1s result is 1 . If even number of 1s result is 0 . The different operations are :

0 ^ 0 = 0

0 ^ 1 = 1

1 ^ 0 = 1

1 ^ 1 = 0

Eg:a = 25 and b = 46

32168421

a = 25

011001

b = 46

101110

110111Ans is 55 ~ (Bitwise complement operator):

This operator performs bitwise complement. Each bit is complemented. It is a unary operator and has only 1 operand. The different operations are :

~ 0 = 1

~ 1 = 0

Eg:a = 25 and b = 46

32168421

a = 25

011001

100110

(shift right):Eg:a = 25 ;

a = a >> 1 /* This means shift right once */

32168421

a = 25

011001

001100Ans is 12

After shifting, add a 0 to the left most bit.

Shift left is dividing the given value by 2 .

PROGRAMS1. To find whether a given number is even or odd using bitwise operatorsmain( )

{

int n ;

printf(Enter any +ve integer :) ;scanf(%d, &n) ;if(n & 1) (or) if(n & 1 = = 1)

printf(Odd number) ;else

printf(Even number) ;getch( ) ;}Note:I/P must be decimal number but not binary number. System converts decimal to binary, since & is bitwise operator. 32 16 8 4 2 1

32 16 8 4 2 1

a = 25

0 1 1 0 0 1 b = 46 1 0 1 1 1 0

0 0 0 0 0 1

0 0 0 0 0 1

0 0 0 0 0 1

0 0 0 0 0 0

Odd number

Even number

2. To swap 2 values using bitwise operatorLogic:Use ex-or 3 times.main( )

{

int a, b ;

printf(Enter the values of a and b :) ;scanf(%d %d, &a, &b) ;a = a ^ b;b = a ^ b;a = a ^ b;

printf(The swapped values of a and b are %d , %d, a, b) ;getch( ) ;}Eg:If a = 25 and b = 46

a = a ^ b gives a as 55 . ie representing a and b in binary format and ex-oring.

b = a ^ b gives b as 25 .

a = a ^ b gives a as 46 .

8. Special Operators:

Special operators include comma operator, sizeof operator, pointer operators ( & and *) and member selection operators ( . and -> )Comma:

A comma operator is used to link related expressions together. A comma-linked list of expressions are evaluated from left to right and the value of the right-most expression is the value of the combined expression.Eg:value = (x = 10, y = 5, x + y) ;

Now value = 15sizeof operator:

This operator gives the size of a variable, data type, pointer, structure, array etc.

Syntax:

sizeof(variable / data type / value) ;Eg 1: int a;

sizeof(a)Ans is 2

sizeof(int)Ans is 2

sizeof(25)Ans is 2 Eg 2:float b;

sizeof(b)Ans is 4

sizeof(float)Ans is 4

sizeof(10.8f)Ans is 4 Eg 3:char ch;

sizeof(ch)

Ans is 1

sizeof(char)

Ans is 1

sizeof(g)

Ans is 1 Eg 4:sizeof(25)

Ans is 2 Eg 5:sizeof(25u)

Ans is 2 Eg 6:sizeof(25L)

Ans is 4 . note: Here L is long .Eg 7:sizeof(10.6f)

Ans is 4 Eg 8:sizeof(10.6)

Ans is 8 . note: If nothing is specified then it is doubleEg 9:sizeof(10.6L)

Ans is 10 . Here L is long double .

Eg 10:printf(size of int is %d, sizeof(int)) ; Ans is size of int is 2Note:For sizeof( ) operator format to be used is %d .

SIZES IN OPERATING SYSTEMS:Data typeDos/Windows operating systemUnix/Linux operating system

int24

float48

Char12

In C and C++ sizes are platform dependent ie operating system dependent.

In java sizes are platform independent.EXPRESSIONS:EVALUATION OF EXPRESSIONS:

An arithmetic expression without parentheses will be evaluated from left to right using the rules of precedence of operators.OPERATORS THEIR RANKS AND THEIR ASSOCIATIVITY:RankOperatorDescriptionAssociativity

1( )

[ ]Function call

Array element referenceLeft to right

2+-

++

--

!

~

*

&

sizeof

(type)Unary plusUnary minus

Increment

Decrement

Logical negation

Ones compliment

Pointer reference (indirection)

Address

Size of an object

Type cast (conversion)Right to left

3*/

%MultiplicationDivision

Modulo divisionLeft to right

4+-AdditionSubtractionLeft to right

5Left shiftRight shiftLeft to right

6=Less thanLess than or equal to

Greater than

Greater than or equal toLeft to right

7= =!=EqualityInequalityLeft to right

8&Bitwise ANDLeft to right

9^Bitwise XORLeft to right

10!Bitwise ORLeft to right

11&&Logical ANDLeft to right

12||Logical ORLeft to right

13?:Conditional expressionRight to left

14=

*= , /= , %=

+= , - =

&= , ^= , |=

=Assignment operatorsRight to left

15,Comma operatorLeft to right

MATHEMATICAL FUNCTIONS (OR) LIBRARY FUNCTIONS:

When the following functions are called header file must be used.

1.sqrt(x):

This is used to find the square root of x where x > 0.

Eg 1:sqrt(9) is 3Eg 2:sqrt(10) is 3.1Eg 3:sqrt(-25) gives error.Note: we cant find square root of a ve number.

2. pow(x,y):

This is used to find the power of a term.Here it is x to the power of y.

Eg 1:pow(2,3) is 8Eg 2:pow(-2,-3) is -0.125

3.abs(x):

This is used to find the absolute value of x.

Eg 1:abs(-25) is 25Eg 2:abs(75) is 75

4.exp(x):

This is used to find the exponent value of x.

Eg:exp(1) is e to the power of 1 that is 2.71828.

5.log(x) and log10(x):

This is used to find the log of x.In log(x) the base is e and in log10(x) it is 10.

Eg 1:log(exp(1)) is 1 Eg 2:log10(10) is 1

6.floor(x):

This is used to find the previous value.

Eg 1:floor(3.8) is 3Eg 2:floor(25) is 25Eg 3:floor(-3.8) is 4.

7. ceil(x):

This is used to find the next value.

Eg 1: ceil(3.8) is 4Eg 2:ceil(25) is 25Eg 3:ceil(-3.8) is - 38. sin(x),cos(x) and tan(x):

This is used to find sine, cosine and tan of x. Here x is in radians.

9. asin(x), acos(x), atan(x):

This is used to find inverse of sine, cosine and tan of x .x is in radians.

10. sinh(x),cosh(x) and tanh(x):

This is used to find hyperbolic value. Here x is in radians.

11. fmod(x,y):

This will give float remainder of x divided by y. And note x%y gives int remainder.

Note:

All mathematical functions implement double type parameters and return double type values.TYPE CASTING

Conversion of a data type to some other data type is known as type casting.

Eg: conversion of int to float, float to int, int to char and so on.

There are two types of type casting: 1. Implicit typecasting.

2. Explicit typecasting.1. Implicit typecasting:

Typecasting is done by the system.Eg 1:int a = 25.8f ;

Here float value is typecasted to int. Ans is 25Eg 2:float b = 25 ;

Here integer value is typecasted to float. Ans is 25.0 Eg 3:char ch = 65 ;

Here integer value is typecasted to char. Ans is ch = a Eg 4:int sum = z ;

Here character is typecasted to int. Ans is sum = 90 (ascii value for z) .

2. Explicit typecasting:

Typecasting is done by the programmer.

Eg 1:int a = 7, b = 2 ;

Now for a/b we get ans as 3

But if (float) a/b we get ans as 3.5

Also for a/(float)b we get ans as 3.5 Note: for / ,typecast either numerator or denominator to get float result. Typecasting is only for that statement and not for the entire progam. Variables a,b are of type int. They are typecasted to float, but in the rest of the program they continue to be integers.Eg 2:float a = 9.8, b = 5. 9;

a % b gives error because % is an integer operator.

Therfore give (int) a % (int) b to use 5 ie. 9 % 5 and ans is 4 .

Variables a,b are of type float. They are typecasted into int but their values continue to be 9.8 and 5.9 in the rest of the program.

Eg 3:int a = 25 ;

float b = 10.8 ;

Here if we say (int) b, then ans is 10 .CONVERSION HIERARCHY:

The conversion is made from lower size type to higher size type.

Rank In HierarchyData type

1long double

2double

3float

4unsigned long int

5long int

6unsigned int

7int

8short and char

1. All short and char are automatically converted to int .

2. In the above for example if one of the operands is long double , the others too will be converted to long double and so on according to hierarchy.

Note:1. float to int causes truncation of the fractional part.

2. double to float causes rounding of digits.

3. long int to int causes dropping of the excess higher order bits.

PROGRAMS1. To find the volume of a sphereLogic:volume = 4.0 / 3 * 3.14 * pow(r, 3) ;Note: 4.0 because 4 / 3 gives 1 and 4.0 / 3 gives 1.33 .

2. To find ascii value of a given character

char ch = a ;

printf(ascii value of %c is %d , ch, ch) ;Ans is ascii value of a is 65 .

3. To find the largest of 2 numbersint a, b, max ;

max = a > b ? a : b ;

4. To find the largest of 3 numbersint a, b, c, max;

max = a > b ? (a > c ? a : c) : (b > c ? b : c) ;Note: conditional operator within a conditional operator is called nested conditional operator.5. To find whether a given number is even or oddint n;

n % 2 = = 0 ? printf(even number) : printf(odd number) ;

(or)

n % 2 ? printf(odd number) : printf(even number) ;Note: Dont give semicolon at the end of 1st printf statement as it will terminate thereafter. Therefore give at the end .

6. Write a program for the following:

b= 1 if a is +ve ,

b= -1 if a is ve ,

b= 0 if a is 0 .int a,b;

b= a > 0 ? 1 : (a < 0 ? -1 : 0) ;

PAGE 1