Vous êtes sur la page 1sur 46

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. 1 Vishwanath Yadav

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( ) { Declaration part Executable part } /* End of program */ /* Function name /* Start of the program */ /* Function body */

Subprogram Section Function 1 Function 2 Function n /* User-defined functions */

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.

2 Vishwanath Yadav

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( ) main(void) void main( ) void main(void) int main( ) int main(void) /* These 2 statements are one and the same */ /* These 2 statements are one and the same */ /* These 2 statements are one and the same */

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 3 Vishwanath Yadav

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 CONSTANTS DATA 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. 4 Vishwanath Yadav

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:

TYPE

SIZE (BYTES)

RANGE

char (or) signed char unsigned char short int (or) signed short int unsigned short int int (or) signed int unsigned int long int (or) signed long int unsigned long int float double long double

1 1 1 1 2 2 4 4 4 8 10

-128 to 127 0 to 255 -128 to 127 0 to 255 -32768 to 32767 0 to 65535 -2147483648 to 2147483647 0 to 4294967295 3.4E-38 to 3.4E+38 1.7E-308 to 1.7E+308 3.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.

5 Vishwanath Yadav

MAXIMUM AND MINIMUM VALUES OF DATA TYPES:

Data type

Maximum

Minimum

Defined in header file

integer long unsigned unsigned long float double long double char unsigned char

INT_MAX (32767) LONG_MAX UINT_MAX (65535) ULONG_MAX FLT_MAX DBL_MAX LONGDBL_MAX CHAR_MAX (127) UCHAR_MAX (255)

INT_MIN (-32768) LONG_MIN 0 0 FLT_MIN DBL_MIN LONGDBL_MIN CHAR_MIN (-128) 0

limits.h limits.h limits.h limits.h floats.h floats.h floats.h

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. If we try to store 32768 in an integer variable, then it gets stored as - 32768

Eg:

FORMATS FOR DATA TYPES:


S.No Data type
1 2 3 4 5 6 7 short unsigned short int unsigned long unsigned long char 6 Vishwanath Yadav

Format
%hd %uh %d %u %ld %ul %c

8 9 10 11 12 13

float float (To represent exponent value) float (Either normal float or exponent value) double long double char array

%f %e %g %lf %Lf %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} ;

7 Vishwanath Yadav

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 . 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.

Eg:

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:
auto break case char const continue default do

8 Vishwanath Yadav

double int struct

else long switch

enum register typedef

extern return union

float short unsigned

for signed void

goto sizeof volatile

if static while

Identifiers (or) Variables:


Identifiers refer to the name of variables, functions and arrays. They are userdefined 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 */

9 Vishwanath Yadav

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
10 Vishwanath Yadav

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 constants

11 Vishwanath Yadav

i. 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 7 character 7 string Say string Hyd 25 integer 25 character 25 string is internally H y d \0

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:


Constant
\a \b \f 12 Vishwanath Yadav Back space Form feed

Meaning
Audible alert (Bell sound)

\n \r \t \v \ \ \? \\ \0

New line Carriage return Horizontal tab Vertical tab Single quote Double quote Question mark Backslash Null

DECLARING CONSTANTS:
Constants are declared with the help of keyword const .

Eg 1: const int a = 10; int b = 20; a = a + 5; b = b + 5; /* Error */ /* 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 int

Eg 2: -56789L

represents long int

Eg 3: 987654UL 13 Vishwanath Yadav

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 float

Eg 2: 1.23456789L

represents long double

INPUT AND OUTPUT OPERATIONS INPUT 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 <stdio.h> . 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.

14 Vishwanath Yadav

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 12.25 in y and g in z .

Here 10 gets stored in x ,

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;

15 Vishwanath Yadav

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. 16 Vishwanath Yadav

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 <stdio.h> . 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 <stdio.h> . Syntax: gets( ):

Eg:

gets( array name) ;

17 Vishwanath Yadav

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<stdio.h>. stdin in fflush( ) is standard I/P ie keyboard.

DIFFERENCES BETWEEN scanf( ) and gets( ):


scanf( )
1.scanf will read only one word.

gets( )
gets will read a full line.

2.scanf is formatted function because %s is Gets is an unformatted function`. used. 3.For scanf space or enter is the end. For gets only enter is the end.

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

OUTPUT FUNCTIONS printf( ):


Its an o/p function. It is predefined in <stdio.h> . Its call by value function. Syntax: printf( format strings , variable1, variable2, ..) ; Note: Some recommend the inclusion of the statement #include <stdio.h>

18 Vishwanath Yadav

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) ; printf(%7d, a) ; printf(%07d, a) ; printf(%2d, a) ; printf(%-7d, a) ; Ans is 6782 Ans is _ _ _ 6782

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

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

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

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

Eg 6: float = 123.6782 ; printf(%.2f, a) ; printf(%.3f, a) ; printf(%5.2f, a) ; printf(%f, a) ; 19 Vishwanath Yadav Ans is 123.67 Ans is 123.678 Ans is 123.67 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 ) ; Eg 8: printf( \ \ ) ; Eg 9: printf( \ ) ; Eg 10: printf( % %) ; Eg 11: printf( \ hi \ hru) ; 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) ) ;

\ n is displayed .

\ is displayed . is displayed .

% is displayed hi hru is displayed .

20 Vishwanath Yadav

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) ; 2. printf(%c, A) ; 3. printf(%d, 7) ; 4. printf(%d, 7) ; 5. printf(%c, 7) ; 6. printf(%d, . ) ; 7. printf(%d, \n ) ; 8. printf(%d, \0 ) ; 21 Vishwanath Yadav Ans is 65

Ans is A

Ans is 55

Ans is 7

Ans is 7 Ans is ascii value of . Ans is ascii value of \n

Ans is 0

9. printf(%c, \0 ) ;

no O/P

DIFFERENCES BETWEEN scanf( ) AND printf( ):


scanf( )
1. This is an I/P function 2.Read a value from keyboard into variable 3. It deals with keyboard. 4. Call by address function. 5. Dont use \n \t in scanf( ) 6. Use only variables in scanf( )

printf( )
This is an O/P function Display the value of the variable. It deals with monitor. Call by value function. These characters can be used in printf( ) We can use messages, variables and expressions.

putchar( ):
putchar( ) displays a character which is stored in a variable. putchar( ) is predefined in <stdio.h> . Syntax: char ch = h ; putchar(ch) ; The above statement displays character h. It is similar to printf(%c, ch) ; Eg 1: putchar(7) ; Eg 2: putchar($) ; Eg 3: putchar(A) Eg 4: putchar(A) ;

Ans is 7

Ans is $

Ans is A This gives error as A is string but not character.

22 Vishwanath Yadav

puts( ):
puts( ) is used to display each string in new line. It is predefined in <stdio.h> . Syntax: puts(array name / string) ; Eg 1: puts(Hyd) ; puts(Sec) ; O/P apperars as 1st 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 <conio.h> . 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.

23 Vishwanath Yadav

clrscr( ):
clrscr( ) is used to clear the screen. clrscr( ) is predefined in <conio.h> . 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 <ctype.h> Function isalnum(c) isalpha(c) isdigit(c) islower(c) isupper(c) isprint(c) ispunct(c) isspace(c) toupper(c) tolower(c) Test Is c an alphanumeric character ? Is c an alphabetic character ? Is c a digit ? Is c a lower case character ? Is c an upper case character ? Is c a printable character ? Is c a punctuation mark ? Is c a white space character ? Convert c to upper case alphabet. Convert c to lower case alphabet.

If the question for that function is true, then that function returns True else False .

24 Vishwanath Yadav

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 CONVERSIONS OPERATORS:


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:
Operator + * / % Meaning Addition subtraction Multiplication Division Modulo division

25 Vishwanath Yadav

Note: 1. 6/7 - 6/7

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

2. During Mudolo division, the sign of the result is the sign of the first operand Eg 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:
Operator < <= > >= == != Is less than Is less than or equal to Is greater than Is greater than or equal to Is equal to Is not equal to Meaning

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

3. Logical Operators:
Operator && || ! Meaning AND OR NOT

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

4. Assignment Operators:

26 Vishwanath Yadav

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 6

Eg 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 4

Eg 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 . 27 Vishwanath Yadav

a = 7; b = ++a; a = a + 1; b = a; a=8 b=8

a = 7; b = a++; b = a; a = a + 1; b=7 a=8

a = 7; b = --a; a = a - 1; b = a; a=6 b=6

a = 7; b = a--; b = a; a = a - 1; b=7 a=6

a = 7; b = - a;

a=7 b=-7

COMPARISON BETWEEN PRE AND POST INCREMENT:


b = ++a
1.Increment a by 1.return new value.

b = a++
Increment a by 1.return old value.

2.Left hand side variable b contains new Left hand side variable contains old value. value. 3.Evaluate pre increment before execution Evaluate post increment after execution of of statement. 4. a = +1; b = a; statement. 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++) ; printf(%d, a) ; } Note: a++ in printf means 1.Display current value of a . 2.Increment a by 1 . Ans is 7 Ans is 8

Eg 2: main( ) 28 Vishwanath Yadav

{ int a=7; printf(%d, ++a) ; printf(%d, a) ; } 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 printf(%d, a) ; } Note: Parameter evaluation in functions is from right to left due to stacks . Actual value ++a a++ ++a a++ 8 9 10 11 Display 8 8 10 10 Ans is 11 8 10 10 . Ans is 8 Ans is 8

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 ; 29 Vishwanath Yadav

b = pow(a++, ++a) ; printf(a = %d, a) ; printf(b = %d, b) ; }

(As parameter evaluation is from right to left we have ++a as 5 and a++ also as 5) Ans is 6 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) ; printf(b = %d, b) ; } 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 Ans is 11 Ans is 36

Eg 7: main( ) { int a = 7, b ; b=a++ * ++a; printf(a = %d, a) ; printf(b = %d, b) ; } 30 Vishwanath Yadav Ans is 9 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 : 31 Vishwanath Yadav

1. & (Bitwise And operator) 2. | (Bitwise Or operator) 3. ^ (Bitwise Ex-Or operator) 4. ~ (Bitwise complement operator) 5. << (Shift left) 6. >> (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=1

Eg:

a = 25 and b = 46 32 a = 25 b = 46 0 1 0 16 1 0 0 8 1 1 1 4 0 1 0 2 0 1 0 1 1 0 0 Ans is 8

| (Bitwise Or operator):
This operator performs bitwise addition.

The different operations are : 0|0=0 0|1=1 1|0=1 32 Vishwanath Yadav

1|1=1

Eg:

a = 25 and b = 46 32 a = 25 b = 46 0 1 1 16 1 0 1 8 1 1 1 4 0 1 1 2 0 1 1 1 1 0 1 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 32 a = 25 b = 46 0 1 1 16 1 0 1 8 1 1 0 4 0 1 1 2 0 1 1 1 1 0 1 Ans 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 33 Vishwanath Yadav

~1=0

Eg:

a = 25 and b = 46 32 a = 25 0 1 16 1 0 8 1 0 4 0 1 2 0 1 1 1 0

<< (Shift left):


Eg: a = 25 ; a = a << 1; /* This means shift left once */

32 a = 25 0 1

16 1 1

8 1 0

4 0 0

2 0 1

1 1 0 Ans is 50

After shifting, add a 0 to the right most bit. Shift left is multiplying the given value by 2 .

>> (shift right):


Eg: a = 25 ; /* This means shift right once */

a = a >> 1

32 a = 25 0

16 1

8 1

4 0

2 0

1 1

34 Vishwanath Yadav

Ans is 12

After shifting, add a 0 to the left most bit. Shift left is dividing the given value by 2 .

PROGRAMS
1. To find whether a given number is even or odd using bitwise operators

main( ) { 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 a = 25 0 0 0

16 8 4

2 1 b = 46

32 1 0 0

16 8 4 2 1 0 1 1 1 0 0 0 0 0 1 0 0 0 0 0

1 1 0 0 1 0 0 0 0 1 0 0 0 0 1 Odd number

Even number

35 Vishwanath Yadav

2. To swap 2 values using bitwise operator Logic: 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 = 15

36 Vishwanath Yadav

sizeof 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) sizeof(int) sizeof(25) Ans is 2 Ans is 2 Ans is 2

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

sizeof(10.8f) Ans is 4

Eg 3: char ch; sizeof(ch) sizeof(char) sizeof(g) Ans is 1 Ans is 1 Ans is 1

Eg 4: sizeof(25)

Ans is 2

Eg 5: sizeof(25u)

Ans is 2 Ans is 4 . note: Here L is long .

Eg 6: sizeof(25L)

Eg 7: sizeof(10.6f)

Ans is 4

Eg 8: sizeof(10.6)

Ans is 8 . note: If nothing is specified then it is double

37 Vishwanath Yadav

Eg 9: sizeof(10.6L)

Ans is 10 . Here L is long double . Ans is size of int is 2

Eg 10: printf(size of int is %d, sizeof(int)) ;

Note: For sizeof( ) operator format to be used is %d .

SIZES IN OPERATING SYSTEMS:

Data type int float Char

Dos/Windows operating system 2 4 1

Unix/Linux operating system 4 8 2

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: Rank


1

Operator
() []

Description
Function call Array element reference Unary plus Unary minus Increment Decrement Logical negation

Associativity
Left to right

+ ++ -!

Right to left

38 Vishwanath Yadav

~ * & sizeof (type) 3 * / % 4 + 5 << >> 6 < <= > >= 7 == != 8 9 10 11 12 13 14 & ^ ! && || ?: = *= , /= , %= += , - = &= , ^= , |= <<= , >>= 15 ,

Ones compliment Pointer reference (indirection) Address Size of an object Type cast (conversion) Multiplication Division Modulo division Addition Subtraction Left shift Right shift Less than Less than or equal to Greater than Greater than or equal to Equality Inequality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional expression Assignment operators Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right Left to right Left to right Left to right Left to right

Comma operator

Left to right

39 Vishwanath Yadav

MATHEMATICAL FUNCTIONS (OR) LIBRARY FUNCTIONS:


When the following functions are called <math.h> 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 3

Eg 2: sqrt(10) is 3.1

Eg 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 8

Eg 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 25

Eg 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. 40 Vishwanath Yadav

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 3

Eg 2: floor(25) is 25

Eg 3: floor(-3.8) is 4.

7. ceil(x):
This is used to find the next value. Eg 1: ceil(3.8) is 4

Eg 2: ceil(25) is 25

Eg 3: ceil(-3.8) is - 3

8. 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):


41 Vishwanath Yadav

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 25

Eg 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) .

42 Vishwanath Yadav

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 Hierarchy 1 2 3 4 5 43 Vishwanath Yadav Data type long double double float unsigned long int long int

6 7 8

unsigned int int short 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.

PROGRAMS
1. To find the volume of a sphere Logic: 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 numbers int a, b, max ; max = a > b ? a : b ;

4. To find the largest of 3 numbers int 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 odd 44 Vishwanath Yadav

int 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 1 st 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) ;

45 Vishwanath Yadav

46 Vishwanath Yadav

Vous aimerez peut-être aussi