Introduction
Introduction
C is a High Level Programming Language. It is the most popular General Purpose Language. This C is a High Level Programming Language. It is the most popular General Purpose Language. This Language was first developed by Dennis Ritchie at AT&T Bell Labs in 1972. Before this C language low Language was first developed by Dennis Ritchie at AT&T Bell Labs in 1972. Before this C language low level language was used for the computer which is very difficult for human to understand and there are so level language was used for the computer which is very difficult for human to understand and there are so many problems in that type of language. So C language is developed which is a High Level Language which many problems in that type of language. So C language is developed which is a High Level Language which is very closer to human languages. C language has also many features like other high level languages like is very closer to human languages. C language has also many features like other high level languages like Readability, Maintainability, Portability, Usability etc.
Readability, Maintainability, Portability, Usability etc.
Character Set
Character Set
Character sets means the characters and symbols that can be understand and accepted by the C language. Character sets means the characters and symbols that can be understand and accepted by the C language. These are grouped to form the commands, expressions, c-statements and other tokens for C Language. There These are grouped to form the commands, expressions, c-statements and other tokens for C Language. There are mainly four categories of the character set as given below.
are mainly four categories of the character set as given below.
1.
1.
Letter or Alphabet:Letter or Alphabet: These are represented by A-Z or a-z. C language is case sensitive so it takesThese are represented by A-Z or a-z. C language is case sensitive so it takes different meaning for small case and upper case letters. There are total 26 letters used in the different meaning for small case and upper case letters. There are total 26 letters used in the C-Programming.Programming.
2.
2.
Digit:Digit: These are represented by 0-9 or by combination of these digits, there are total 10 digits used inThese are represented by 0-9 or by combination of these digits, there are total 10 digits used in the C-Programming.the C-Programming.
3.
3.
Special Special CharacterCharacters:s: There are some special symbols and punctuation marks used for some specialThere are some special symbols and punctuation marks used for some special purpose. Here are total 30 special characters used in the C-Programming. Special symbols used purpose. Here are total 30 special characters used in the C-Programming. Special symbols usedunder this category are like, +, -, *,
under this category are like, +, -, *, /, @, #, $, %, /, @, #, $, %, ^ etc.^ etc.
4.
4.
Empty space characters or whiteEmpty space characters or white spaces:spaces: White spaces has blank space, new line return,White spaces has blank space, new line return, Horizontal tab space, vertical tab space, etc.Horizontal tab space, vertical tab space, etc.
Identifiers
Identifiers
Identifiers are used for naming variables, methods, classes, labels and other programming elements. Identifiers are used for naming variables, methods, classes, labels and other programming elements. Identifiers must enforce following rules
Identifiers must enforce following rules a)
a) They They can hacan have alphave alphabets (a bets (a to z), to z), digits digits (0 to (0 to 9), a9), and undend underscore.rscore. sal1 Valid
sal1 Valid sa
sal#l# InInvavalilid (d (# i# is ns not ot a va valalid id chchararacacteter)r) b)
b) TheThey my must ust not bnot begin egin witwith a dh a digitigit.. ssaall11 VVaalliidd
_
_ssaall11 VVaalliidd 1s
c)
c) UppeUppercasrcase and le and lowerowercase lcase lettetters arers are dise distinctinctt #include<iostram.h> #include<iostram.h> void main() void main() { { iinnt t aa==22;; printf(“%d”,A) ; printf(“%d”,A) ; } }
O/P- This program generates compile error: Undefined Variable A because in our program we have O/P- This program generates compile error: Undefined Variable A because in our program we have declared a not A
declared a not A d)
d) KeyKeyworwords cads cannot nnot be usbe used as ed as idenidentifitifiers.ers. iinnt t ffllooaatt iinnvvaalliid (d (ffllooaat t iis s a a kkeeyywwoorrdd))
Keywords
Keywords
The keywords are also called reserved words. Keywords can not be used as variables names. These are The keywords are also called reserved words. Keywords can not be used as variables names. These are mainly 40 keywords among which 32 are used by many compilers for high level programming, whereas mainly 40 keywords among which 32 are used by many compilers for high level programming, whereas remaining 8 reserve words are used by the programmer for low level programming. Following are the 32 remaining 8 reserve words are used by the programmer for low level programming. Following are the 32 Keywords of C.
Keywords of C.
aauuttoo ddoo ffoorr rreettuurrnn
ttyyppeeddeeff bbrreeaakk dodouubblle e ggoottoo
ssttaarrtt uunniioonn ccaassee eellssee
iiff ssiizzeeooff uunnssiiggnneedd cchhaarr iinntt ssttaattiicc vvooiid d ccoonnttiinnuuee eexxtteerrnn lloonngg ssttrruucctt wwhhiillee v
voollaattiillee ccoonnssttaannt t ddeeffaauulltt rreeggiisstteer r ssiiggnneedd sswwiittcchh ddoouubbllee eennuumm
Constants/Literals
Constants/Literals
Constant is one that has a fixed value throughout the program. Constants are assigned to variables in a Constant is one that has a fixed value throughout the program. Constants are assigned to variables in a program. Constants can be divided into two categories
program. Constants can be divided into two categories 1) Numeric Constant 1) Numeric Constant 2) Non-Numeric Constant 2) Non-Numeric Constant Constants Constants N
Nuummeerriic c CCoonnssttaanntt NNoonn--NNuummeerriic c CCoonnssttaanntt
IInntteeggeerr RReeaal l oor r ffllooaatt SSiinngglle e CChhaarraacctteer r SSttrriinng g CChhaarraacctteer Br Baacckkssllaassh h cchhaarraacctteer r
D
Deecciimmaal l OOccttaal l HHeexxaaddeecciimmaall wwiitthh wwiitthhoouutt E
Exxppoonneenntt EExxppoonneenntt
1. Numeric Constant: 1. Numeric Constant:
These have numeric value having combination of sequence of digits i.e. from 0-9 as alone or These have numeric value having combination of sequence of digits i.e. from 0-9 as alone or combination of 0-9 with decimal points having positive or negative sign.
combination of 0-9 with decimal points having positive or negative sign.
a. Integer Constant: a. Integer Constant:
Integer numeric constant have integer data combination of 0-9 without any decimal point. Integer numeric constant have integer data combination of 0-9 without any decimal point. These are further subdivided into three parts:
These are further subdivided into three parts:
i.
i.
Decimal Constant:Decimal Constant: These have no decimal point in it and is either be alone or theThese have no decimal point in it and is either be alone or the combination of 0-9 digits. These have either +ve or –ve sign.combination of 0-9 digits. These have either +ve or –ve sign. For example 124, -345, +45 etc.
For example 124, -345, +45 etc.
ii.
ii.
Octal Constant:Octal Constant: These consist of combination of These consist of combination of digits from 0-7 with digits from 0-7 with positive or positive or negative sign. It has leading with O or o. For example O37, -O87, O0 etc.negative sign. It has leading with O or o. For example O37, -O87, O0 etc.
iii.
iii.
Hexadecimal Constant:Hexadecimal Constant: These consist of combination of digits from 0-9 and A-F.These consist of combination of digits from 0-9 and A-F. It has leading with Ox or ox. For example Ox37, ox87, OX0 etc.b. Real or
b. Real or Float Constant:Float Constant:
Real numeric constant have data combination of 0-9 with decimal point. It may have positive Real numeric constant have data combination of 0-9 with decimal point. It may have positive or negative values. It is also called floating point constant. These are further subdivided into two or negative values. It is also called floating point constant. These are further subdivided into two parts:
parts:
i.
i.
Without exponent:Without exponent: Real numeric constant without exponent is a simple numericReal numeric constant without exponent is a simple numeric value having combination of 0-9 with decimal point.value having combination of 0-9 with decimal point. For example: 3.54, 34.56, -987.56 etc.
For example: 3.54, 34.56, -987.56 etc.
ii.
ii.
With exponent:With exponent: Real numeric constant with exponent have two parts in the constantReal numeric constant with exponent have two parts in the constant value. One part is mantissa and other part is exponent part.value. One part is mantissa and other part is exponent part. For example: 3.2e-04 (0.00032), 65.74e01(657.4) etc. For example: 3.2e-04 (0.00032), 65.74e01(657.4) etc.
2. Non-Numeric Constant: 2. Non-Numeric Constant:
These Non-numeric constant have values only from alphanumeric characters. There are not any These Non-numeric constant have values only from alphanumeric characters. There are not any negative values in these constants.
negative values in these constants.
a.
a.
Single Character Constant:Single Character Constant: This type of constant contains only single character fromThis type of constant contains only single character from alphanumeric character sets. This single character is written in single quotation marks. alphanumeric character sets. This single character is written in single quotation marks. ForFor example: example: ‘a’, ‘a’, ‘A’, ‘A’, ‘2’ ‘2’ valid valid constants, constants, ‘sd’ ‘sd’ invalid invalid constants.constants.
b.
b.
String Character Constant:String Character Constant: This type of constant contains more than one character in it. ItThis type of constant contains more than one character in it. It contains multiple characters according to our requirements. These characters are written in contains multiple characters according to our requirements. These characters are written in double quotation marks. For example: “Welcome to IIMT”etc.double quotation marks. For example: “Welcome to IIMT”etc.
c.
c.
Backslash Character Constant:Backslash Character Constant: These type of constant contains some characters for someThese type of constant contains some characters for some special purposes. Following are some of the backslash character constants. These are also known special purposes. Following are some of the backslash character constants. These are also known as Escape sequences.as Escape sequences.
Es
Escacape Sepe Seququenencece PuPurprpososee
\a
\a Alert/ Alert/ bell/ bell/ beepbeep \\bb BBaacckkssppaaccee \\ff FFoorrm m ffeeeedd \\nn NNeew w lliinnee
\\tt TTaabb
\\’’ SSiinngglle e qquuoottaattiioon n mmaarrk k \\”” DDoouubblle e qquuoottee
Punctuators
Punctuators
These are symbols used for grouping and separating code. They are also known as separators or Delimiters. These are symbols used for grouping and separating code. They are also known as separators or Delimiters. Separators are given below
Separators are given below
• • Parentheses ()Parentheses () • • Braces Braces { { }} • • Brackets [ ]Brackets [ ] • • Semicolon (;)Semicolon (;) • • Colon (:)Colon (:) • • Comma (,)Comma (,) •
• Period (.) etc.Period (.) etc.
Data Types
Data Types
Data types are used to declare variables. Variable declaration tells us Data types are used to declare variables. Variable declaration tells us
1)
1) TyType of vpe of valualue a vare a variaiablble can he can hololdd 2)
2) NaName me of of vavaririabablele 3
3)) RRaannggee
There are mainly five types of data type used in C There are mainly five types of data type used in C
1.
1. PriPrimarmary or scaly or scalar or staar or standarndard or fundd or fundameamental or sintal or simplmple data tye data typepe 2.
2. SeSeconcondadary ory or der deririved dved datata tya typepe 3.
3. EnumEnumeraterated Daed Data tyta types or pes or UseUser defr defineined data td data typeypess 4.
4. EmEmpty pty dadata tta typype or ve or voioid dad data tta typypee 5.
5. PoPoininteter dar data tta tyypepe
1. Primary or Scalar Data type:
1. Primary or Scalar Data type: it is used for it is used for representrepresenting a ing a single value only. Scalasingle value only. Scalar data type r data type is further is further divided into three types
divided into three types 1. Integer types 1. Integer types 2. Floating types 2. Floating types 3. Character 3. Character
Integer type:
Integer type: Integer type can store integer constant i.e. numerical value without decimal points.Integer type can store integer constant i.e. numerical value without decimal points. Numerical value can be positive as well as negative. It supports 4 types of integers as shown in table Numerical value can be positive as well as negative. It supports 4 types of integers as shown in table
T
Tyyppee SSiizzee RRaannggee
IInntt 2 2 bbyytteess --3322776688 tto o 3322776677 U
Unnssiiggnneed d iinntt 2 2 bbyytteess 0 0 tto o 6655553355 L
Loonngg 4 4 bbyytteess --223131to 2to 23131-1-1
U
Unnssiiggnneed d lloonngg 4 4 bbyytteess 0 0 tto o 223232 -1-1
Floating Data Type:
Floating Data Type: Floating data type can store real constants i.e. numerical value with decimalFloating data type can store real constants i.e. numerical value with decimal points. Values can be positive as well as negative.
points. Values can be positive as well as negative. T
Tyyppee SSiizzee RRaannggee F
Fllooaatt 4 4 bbyytteess 33..4 4 * * 1100 –38 –38 to 3.4 * 10to 3.4 * 103838
D
Doouubbllee 8 8 bbyyttees s 1..7 1 7 * * 1100 –308 –308 to 1.1 * 10to 1.1 * 10308308 L
Loonng g ddoouubbllee 110 0 bbyytteess 33..4 4 * * 1100 –4932 –4932to 1.1 * 10to 1.1 * 10 49324932
Character Type:
Character Type: CharactCharacter data type can er data type can hold only a single alphabet (A-Z) or digit (0-9) or hold only a single alphabet (A-Z) or digit (0-9) or specialspecial symbol. The character data type assumes a size of one byte. It has been designed to hold 8 bit ASCII symbol. The character data type assumes a size of one byte. It has been designed to hold 8 bit ASCII code. Its range is from 0 to 255.
code. Its range is from 0 to 255.
2. Secondary or Derived data type: 2. Secondary or Derived data type:
Secondary data types are derived from the scalar data types. Secondary data type may be used for Secondary data types are derived from the scalar data types. Secondary data type may be used for representing single value or multiple values. Secondary data types are divided into three categories representing single value or multiple values. Secondary data types are divided into three categories
1.
1. ArArraray oy or Sr Strtriningsgs 2
2.. SSttrrucuctturureess 3
3.. UUnniioonnss
3. Enumerated Data types or User defined data types: 3. Enumerated Data types or User defined data types:
It provides us a
It provides us a way to define our own data types. This is used way to define our own data types. This is used when you know in advance the finitewhen you know in advance the finite number of values a variable can take in a program. ‘Enumerated’ means that all values are listed. number of values a variable can take in a program. ‘Enumerated’ means that all values are listed. These data types are internally treated as integers. By default first member gets value 0, second 1 and These data types are internally treated as integers. By default first member gets value 0, second 1 and so on.
#include<iostream.h> #include<iostream.h> enum dow{sun=1,mon,tue,wed,thu,fri,sat,sun}; enum dow{sun=1,mon,tue,wed,thu,fri,sat,sun}; void main() void main() { { ddoow w dd11,,dd22;; d1=mon; d1=mon; d2=thu; d2=thu; printf(“%d”,d2-d1); printf(“%d”,d2-d1); } } Output: 3 Output: 3 4.
4. Void or Void or Empty Data Empty Data Type:Type:
Void or empty data type is used in the user defined functions. This is used when function returns Void or empty data type is used in the user defined functions. This is used when function returns nothing. This is also used when function has no arguments.
nothing. This is also used when function has no arguments.
5. Pointer Data Type: 5. Pointer Data Type:
Pointer data types are used to store memory addresses instead of values. Pointer data types are used to store memory addresses instead of values.
White spaces
White spaces
White space is defined as spaces, carriage return, line feeds, tabs, vertical tabs and form feeds. These are White space is defined as spaces, carriage return, line feeds, tabs, vertical tabs and form feeds. These are ignored by the compiler. But there are some exceptions:
ignored by the compiler. But there are some exceptions: 1.
1. The The stristring cng constonstant ant can can not not be be splisplit.t. 2.
2. #inc#includelude<hea<headerfderfile> mile> must be wust be writritten on a siten on a single lngle lineine.. 3.
3. // symbol// symbols can be us can be used to show sed to show commencomments. These ats. These are valid ore valid only for a nly for a single linsingle line; no whie; no white spacete space should be used between these slashes.
C operators
C operators
An operator is a symbol that tells the compiler to perform a certain mathematical or logical manipulators. C supports An operator is a symbol that tells the compiler to perform a certain mathematical or logical manipulators. C supports a rich set of operators. C operators can be classified into following categories:
a rich set of operators. C operators can be classified into following categories:
1. Arithmetic operators 1. Arithmetic operators
Arithmetic operators are used for arithmetic operations like Addition, Subtraction, Multiplication, Division Arithmetic operators are used for arithmetic operations like Addition, Subtraction, Multiplication, Division & Modulus. These can operate on any built in numeric type. Following are the list of Arithmetic Operators. & Modulus. These can operate on any built in numeric type. Following are the list of Arithmetic Operators.
O
Oppeerraattoorr MMeeaanniinngg
+ + AAddddiittiioonn -- SSuubbttrraaccttiioon n oor r uunnaarryy minus minus * * MMuullttiipplliiccaattiioonn // DivisionDivision %
% Modulus divisionModulus division E.g. If
E.g. If a=14 and b=4 a=14 and b=4 we have following resultswe have following results
aa--bb==1100 aa++bb==1188
aa**bb==5566 aa//bb==33( ( ddeecciimmaal l ppaarrt t ttrrnnccaatteed d )) a%b=2
a%b=2 (Remai(Remainder of the division)nder of the division)
Here a, b are known as operands. Operator is called binary operator if it requires two operands and unary Here a, b are known as operands. Operator is called binary operator if it requires two operands and unary operator if it requires one operand.
operator if it requires one operand.
Type Conversions:
Type Conversions: When two operands of different types are encountered in the same expression low typeWhen two operands of different types are encountered in the same expression low type variable is converted to the type of the higher type variable. The conversion takes place (implicitly) invisible variable is converted to the type of the higher type variable. The conversion takes place (implicitly) invisible to the user.
to the user.
Lo
Long ng DoDoubublele HiHighghesest t orordeder r Double Double Float Float Long Long Int Int
C
Chhaarr ((LLoowweesst t oorrddeerr))
E
E..gg.. 11. . a a = = 1111//55= = 22 22. . a a = = 1111//55..00==22..22
Casting:
Casting:The term applies to the data conversions by the programmer as opposed to the automatic dataThe term applies to the data conversions by the programmer as opposed to the automatic data conversion. It is also known as explicit conversion.
conversion. It is also known as explicit conversion. E.g.
E.g. a a = = 11/( 11/( int int ) ) (5.0 (5.0 ) ) =2=2
Expressions:
Expressions:
An expression is a combination of operands and operators. In an expression there may be multiple operands An expression is a combination of operands and operators. In an expression there may be multiple operands and multiple operators depends upon the situation. An operand may be a variable or a constant value. Expression are and multiple operators depends upon the situation. An operand may be a variable or a constant value. Expression are of five types. of five types. 1. Arithmetic Expression 1. Arithmetic Expression 2. Relational Expression 2. Relational Expression 3. Logical Expression 3. Logical Expression 4. Assignment Expression 4. Assignment Expression 5. Conditional Expression 5. Conditional Expression 1. Arithmetic Expression:
1. Arithmetic Expression: Arithmetic Expressions are the expressions which contains only the ArithmeticArithmetic Expressions are the expressions which contains only the Arithmetic Operators. These are of three types.
Operators. These are of three types.
a) Integer Arithmetic Expression:
a) Integer Arithmetic Expression: When all the operands are of When all the operands are of Integer type then the Expression isInteger type then the Expression is known as Integer Arithmetic Expression. For Example: 5 +2, 35/3 etc.
known as Integer Arithmetic Expression. For Example: 5 +2, 35/3 etc.
b) Real
b) Real Arithmetic Expression:Arithmetic Expression:When all the operands are of real type then the expression is knownWhen all the operands are of real type then the expression is known as Real Arithmetic Expression. For Example: 5.4*3.2, 567.7/45.7 etc.
as Real Arithmetic Expression. For Example: 5.4*3.2, 567.7/45.7 etc.
c)
c) MixeMixed d Mode ArithmetMode Arithmetic ic ExprExpressiession:on: When all the operands are of mixed type i.e. someWhen all the operands are of mixed type i.e. some operands are of real type and some operands are of Integer type then the Expression is known as operands are of real type and some operands are of Integer type then the Expression is known as Mixed Mode Arithmetic Expression. For example: 3+5.6, 567* 4.5 etc.
Mixed Mode Arithmetic Expression. For example: 3+5.6, 567* 4.5 etc.
2. Relational Operators:
2. Relational Operators: The relational operators are symbols that are used to test the relation between twoThe relational operators are symbols that are used to test the relation between two expression
expressions. These operators return s. These operators return true or false true or false i.e. 1 i.e. 1 or 0.Relational operatoror 0.Relational operators are s are binary operators becausebinary operators because they required two operands. There are mainly six type of relational operators used in C-Language.
they required two operands. There are mainly six type of relational operators used in C-Language.
Op
Opereraatotorr MMeeaaniningng
= = == EEqquuaal l ttoo > > GGrreeaatteer r tthhaann < < LLeesss s tthhaann !!== NNoot t eeqquuaal l ttoo
>
>== GGrreeaatteer r tthhaan n oor r eeqquuaal l ttoo <
<== LLeesss s tthhaan n oor r eeqquuaal l ttoo
2. Relational
2. Relational Expression:Expression:Relational Expressions are the expressions which contains only the RelationalRelational Expressions are the expressions which contains only the Relational Operators. These are of three types.
Operators. These are of three types.
a) Integer Relational Expression:
a) Integer Relational Expression: When all the operands are of Integer type then the Expression isWhen all the operands are of Integer type then the Expression is known as Integer Relational Expression. For Example: 5 < 2, 35 > 3 etc.
known as Integer Relational Expression. For Example: 5 < 2, 35 > 3 etc.
b) Real Relational
b) Real Relational Expression:Expression:When all the operands are When all the operands are of real type then of real type then the expression is knownthe expression is known as Real Relational Expression. For Example: 5.4= =3.2, 567.7!=45.7 etc.
as Real Relational Expression. For Example: 5.4= =3.2, 567.7!=45.7 etc.
c) Mixed Mode Relational Expression:
c) Mixed Mode Relational Expression: When all the operands are of mixed type i.e. some operandsWhen all the operands are of mixed type i.e. some operands are of real type and some operands are of Integer type then the Expression is known as Mixed Mode are of real type and some operands are of Integer type then the Expression is known as Mixed Mode Relational Expression. For example: 345< 34.5, 23.45 >= 34 etc.
Relational Expression. For example: 345< 34.5, 23.45 >= 34 etc.
3. Logical operators:
3. Logical operators: Logical operators are used to combine two or more relations. These are used inLogical operators are used to combine two or more relations. These are used in decision making statement because they return true or false values only i.e. 1 or 0. There are mainly three decision making statement because they return true or false values only i.e. 1 or 0. There are mainly three type of Logical Operators used in the C-Language.
type of Logical Operators used in the C-Language.
O
Opeperarattoror MMeaeaniningng
& &&& AANNDD |||| OORR !! NNOOTT For example: For example: void main() void main() { { iinnt t aa==22,,bb==00,,cc;; if( a>=2 && a<=7) if( a>=2 && a<=7)
printf(”\nYes”); printf(”\nYes”); else else printf(”\nNo”); printf(”\nNo”); c=a || b; c=a || b; printf(”\t c=%d”,c); printf(”\t c=%d”,c); } } O
Truth Table of Logical AND and
Truth Table of Logical AND and Logical OR OperatorsLogical OR Operators A
A BB AA&&&&BB AA||||BB
0 0 00 00 00 0 0 11 00 11 1 1 00 00 11 1 1 11 11 11
Truth Table of Logical NOT Operator Truth Table of Logical NOT Operator
A A !A!A 0 0 11 1 1 00 3. Logical Expression:
3. Logical Expression:Logical Expressions are the expressions which contains only the Logical Operators.Logical Expressions are the expressions which contains only the Logical Operators. These are of three types.
These are of three types.
a) Integer Logical Expression:
a) Integer Logical Expression: When all the operands are of Integer type then the Expression isWhen all the operands are of Integer type then the Expression is known as Integer Logical Expression. For Example: (5 < 2)&& (35 > 3) etc.
known as Integer Logical Expression. For Example: (5 < 2)&& (35 > 3) etc.
b) Real Logical Expression:
b) Real Logical Expression: When all the operands are of When all the operands are of real type then the expression is known asreal type then the expression is known as Real Logical Expression. For Example: (5.4= =3.2) || (567.7!=45.7) etc.
Real Logical Expression. For Example: (5.4= =3.2) || (567.7!=45.7) etc.
c) Mixed Mode Logical
c) Mixed Mode Logical Expression:Expression:When all the operands are of mixed type i.e. someWhen all the operands are of mixed type i.e. some operands are of real type and some operands are of Integer type then the Expression is known operands are of real type and some operands are of Integer type then the Expression is known as Mixed Mode Logical Expression. For example: (345< 34.5)&& (23.45 >= 34) etc.
as Mixed Mode Logical Expression. For example: (345< 34.5)&& (23.45 >= 34) etc.
4. Assignment operator:
4. Assignment operator: Assignment operators are used for assigning an expression or value to a variable.Assignment operators are used for assigning an expression or value to a variable. It is the short hand symbol for arithmetic & bitwise operators. Assignment operators are binary operators It is the short hand symbol for arithmetic & bitwise operators. Assignment operators are binary operators because they required two operands.
because they required two operands. Some of the commonly used assignment operators are given belowSome of the commonly used assignment operators are given below St
Statatemement uent usising Asng Assisignmgnmenent Opet Operaratortor EqEquivuivalalent stent statatemement uent usising arng arithithmemetitic operc operatoator r
aa++==11 aa==aa++11
aa-- ==11 aa==aa--11
aa\\==55 aa==aa//55
aa%%==bb aa==aa%%bb
4. Assignment Expression:
4. Assignment Expression: Assignment Expressions are the expressions which contains the AssignmentAssignment Expressions are the expressions which contains the Assignment Operators. These are of three types.
Operators. These are of three types.
a) Integer Assignment Expression:
a) Integer Assignment Expression: When all the operands are of Integer type then the Expression isWhen all the operands are of Integer type then the Expression is known as Integer Assignment Expression. For Example: a = 5+2, b= 35*3 etc.
known as Integer Assignment Expression. For Example: a = 5+2, b= 35*3 etc.
b) Real Assignment Expression:
b) Real Assignment Expression: When all the operands are of real type then the expression isWhen all the operands are of real type then the expression is known as Real Assignment Expression. For Example: c=5.4/3.2, d=567.7*5.7 etc.
known as Real Assignment Expression. For Example: c=5.4/3.2, d=567.7*5.7 etc.
5. Conditional operator or
5. Conditional operator or Ternary operator:Ternary operator:This operator is compressed version of if-else statement.This operator is compressed version of if-else statement. This is called ternary operator because it requires three operands. The syntax of the statement is
This is called ternary operator because it requires three operands. The syntax of the statement is C=( a > b) ? a
C=( a > b) ? a::b;b;
This above statement returns the greatest number as a value of C variable i.e if a is greater than b then the value of a is This above statement returns the greatest number as a value of C variable i.e if a is greater than b then the value of a is assigned to c otherwise the value of b is assigned to c.
assigned to c otherwise the value of b is assigned to c.
6.
6. IncrementIncrement/Decrement operator:/Decrement operator: The ++ (increment) operator adds 1 to the operand and – (decrement)The ++ (increment) operator adds 1 to the operand and – (decrement) subt
subtracracts ts 1 1 from the from the operoperand. Both and. Both are are unarunary y operoperatorators s becabecause use they requirthey required ed singsingle le operoperand. Theseand. These operators can be used in two ways:
operators can be used in two ways: 1.
1. Prefix Prefix operator operator 2.
2. PoPoststfifix opx opereratator or
1.
1. PrePrefix fix IncrIncremenement/Dect/Decremerement nt OperOperatorator:: In this first of all value will be incrementedIn this first of all value will be incremented or decremented (according to operators ++ & --) and then that new value will be
or decremented (according to operators ++ & --) and then that new value will be assigned to a variable.
assigned to a variable.
2.
2. PostPostfix fix IncrIncremenement/Det/Decremcrement ent OperOperatorator:: In this first of all value will be assigned toIn this first of all value will be assigned to a variable then its is incremented or decremented according to the operator used. a variable then its is incremented or decremented according to the operator used.
//Program to explain Postfix
//Program to explain Postfix and Prefix Increment Operatorand Prefix Increment Operator
#include<iostream.h> #include<iostream.h> void main ( )
void main ( ) {
{ int int a=2, a=2, b=2, b=2, c, c, d;d; c= ++a; c= ++a; d= b++; d= b++; printf(“\na=%d\tc=%d”,a,c); printf(“\na=%d\tc=%d”,a,c); printf(“\nb=%d\td=%d”,b,d); printf(“\nb=%d\td=%d”,b,d); } } O
Ouuttppuutt:: aa==33 cc==33 b
7. Bitwise Operators: 7. Bitwise Operators:
These operators are mainly used for the operation of Binary bits i.e. 0 and 1. So these are mainly used for These operators are mainly used for the operation of Binary bits i.e. 0 and 1. So these are mainly used for low level programming. Bitwise operations are the testing, setting or shifting of the actual bit in a byte. low level programming. Bitwise operations are the testing, setting or shifting of the actual bit in a byte. These operators should not be of float or double type due to binary version. There are mainly six Bitwise These operators should not be of float or double type due to binary version. There are mainly six Bitwise Operators used in C programming.
Operators used in C programming.
B
Biittwwiisse e OOppeerraattoorr MMeeaanniinngg
&
& BBiittwwiisse e AANNDD || BBiittwwiissee OORR ^^ BBiittwwiisseeXXOORR <
<<< BiittwB wiisse e LLeefftt >
>>> BBiittwwiisse e RRiigghhtt ~
~ OOnnee’’s s CCoommpplleemmeenntt
8. Special Operators:
8. Special Operators: These are used for special purposes in C-Language. These operators are used inThese are used for special purposes in C-Language. These operators are used in Pointers, Structures and Unions etc. Six type of Special Operators are given below.
Pointers, Structures and Unions etc. Six type of Special Operators are given below. aa. . UUnnaarry y OOppeerraattoorr bb. . CCoommmma a OOppeerraattoor r
cc. . SSiizzeeoof f OOppeerraattoorr d. d. TTyyppe e OOppeerraattoor r
ee. . PPooiinntteer r OOppeerraattoorr ff. . MMeemmbbeer r SSeelleeccttiioon n OOppeerraattoor r
Sizeof Operator
Sizeof Operator
This operator returns the number of bytes occupied by operand. The operand may be a variable, a constant This operator returns the number of bytes occupied by operand. The operand may be a variable, a constant or a data type. For Example
or a data type. For Example
aa= = ssiizzeeooff((iinntt)) ////aa==22 aa==ssiizzeeooff((ffllooaatt)) ////aa==44 aa==ssiizzeeoof f ((cchhaarr)) ////aa==11
Precedence of operators:
Precedence of operators: In an expression operators with higher precedence are evaluated before lower In an expression operators with higher precedence are evaluated before lower precedence operator. Operators having equal precedence are evaluated on the basis of associatively.
precedence operator. Operators having equal precedence are evaluated on the basis of associatively. D
Deesscc.. OOppeerraattoorr AAssssoocciiaattiivveellyy H
Hiigghheerr ( ( )), , [ [ ]], , -->>, , .. LLeefft t tto o rriigghhtt -, ++, --, ~, !
-, ++, --, ~, ! & (address of) & (address of)
* ( value of address) * ( value of address) ( Type ) casting ( Type ) casting Size of Size of Right to left Right to left *
* , , / / , , %% LLeefft t tto o rriigghhtt +
+ -- LLeefft t tto o rriigghhtt << ( left shift) << ( left shift) >> ( Right shift ) >> ( Right shift ) Left to right Left to right <
< ,,<<==, , > > , , >>== LLeefft t tto o rriigghhtt =
===, , !!== LLeefft t tto o rriigghhtt &
& (Bitwise (Bitwise AND) AND) Left Left to to rightright ^
^ BBiittwwiisse e XXOORR LLeefft t tto o rriigghhtt |
| BBiittwwiisse e OORR LLeefft t tto o rriigghhtt &
&&& LLeefft t tto o rriigghhtt |||| LLeefft t tto o rriigghhtt ? : ( c
? : ( condondititionional opal opereratator)or) RiRight ght to lto lefteft L Loowweerr == *= *= |= |= %=%= += -= &= += -= &= Right to left Right to left Right to left Right to left Right to left Right to left
^= |= ^= |= <<= >>== <<= >>== Right to left Right to left Right to left Right to left
Control Statements or Flow Controls
Control Statements or Flow Controls
A program consists of some statements which will execute in some sequiential manner but if we want to A program consists of some statements which will execute in some sequiential manner but if we want to override that flow of execution of statements then we need some type of Flow Control Statements. So there override that flow of execution of statements then we need some type of Flow Control Statements. So there are mainly three different categories to control the flow of execution.
are mainly three different categories to control the flow of execution.
1
1. . BBrraanncchhiinngg 22. . LLooooppiinngg 33. . JJuummppiinngg
1. Branching
1. Branching
To override the sequential flow of execution branching is must. At the same time arbitrary unconditional To override the sequential flow of execution branching is must. At the same time arbitrary unconditional branches are not healthy for programming. Branching must be done on a test. C supports following control branches are not healthy for programming. Branching must be done on a test. C supports following control
or decision making statements or decision making statements
1
1.. IIf sf sttaatteemmeentnt 2.
2. swswititch ch ststatatememenentt 3.
3. conconditditioional opnal opereratoator statr statememenentt
If statement If statement
If statement is used to control the flow of execution of statements. It is a two way decision statement If statement is used to control the flow of execution of statements. It is a two way decision statement and used in conjunction with an expression. If statement is of further four types.
and used in conjunction with an expression. If statement is of further four types.
a) Simple If
a) Simple If Statement:Statement:When there is only one statement in our program, then we need only oneWhen there is only one statement in our program, then we need only one block of statement. At that time we need only Simple if statement. The syntax of if statement is like block of statement. At that time we need only Simple if statement. The syntax of if statement is like
If (condition) If (condition)
{true statement block;} {true statement block;} other statements;
other statements;
In this type of statement condition will be checked. If condition is true then true statement In this type of statement condition will be checked. If condition is true then true statement block will be executed and after that other statements block will be executed. If the condition is false block will be executed and after that other statements block will be executed. If the condition is false
only other statements bock will be executed. only other statements bock will be executed.
b) If-else Statement:
b) If-else Statement: This statement also contains single condition but with two different blocks oneThis statement also contains single condition but with two different blocks one for the true condition and one for the false condition. The syntax of if statement is like:
for the true condition and one for the false condition. The syntax of if statement is like:
Expressi Expressi on on ?? FalseFalse True True If (condition) If (condition)
{True Statement- block;} {True Statement- block;} else
else
{False Statement- block;} {False Statement- block;} Statement – n;
block will be executed and after that statement - n block will be executed. If the condition is false block will be executed and after that statement - n block will be executed. If the condition is false then the block of false statement will be executed and after that statement – n block will be executed. then the block of false statement will be executed and after that statement – n block will be executed.
c) Nested If Statement:
c) Nested If Statement: When one if statement occurs within another if statement then that type of if When one if statement occurs within another if statement then that type of if stateme
statements are known nts are known as nested if as nested if statemestatements. These statementnts. These statements are s are used to solve used to solve some complex typesome complex type of problems. The syntax of this statement is given below:
of problems. The syntax of this statement is given below:
If(condition1) If(condition1) {{ If (condition2) If (condition2) {Statement1;} {Statement1;} else else {Statement2;} {Statement2;} }} else else {Statement3;} {Statement3;} Statement – n; Statement – n; }}
In this type of statement condition1 will be checked. If condition1 is true then next condition2 In this type of statement condition1 will be checked. If condition1 is true then next condition2 will be checked. If condition2 is true then Statement1 will be executed and Statement – n will be will be checked. If condition2 is true then Statement1 will be executed and Statement – n will be executed and if condition2 will be false then Statement2 will be executed and then Statement – n will executed and if condition2 will be false then Statement2 will be executed and then Statement – n will be executed. If condition1 becomes false then Statement3 will be executed and after that Statement – be executed. If condition1 becomes false then Statement3 will be executed and after that Statement –
n will executed. n will executed.
d) Ladder if-else statement:
d) Ladder if-else statement: This type of statement is used only when there are many number of This type of statement is used only when there are many number of conditions to be there to check. The program showing the structure of this statement are given below: conditions to be there to check. The program showing the structure of this statement are given below: //P
//Program to print the division of a rogram to print the division of a student on the basis of following criteria:student on the basis of following criteria:
M
Maarrkkss>>==6600 FFiirrsstt MMaarrkkss>>==550 0 AANND D MMaarrkkss<<6600 SSeeccoonndd M
Maarrkkss>>==440 0 AANND D MMaarrkkss<<5500 TThhiirrdd MMaarrkkss<<440 0 FFaaiill void main( )
void main( ) {
{ int int marks;marks;
printf(”Enter marks”); printf(”Enter marks”); scanf(“%d”,&marks); scanf(“%d”,&marks); if(marks >=60) if(marks >=60) printf(”First”); printf(”First”); else if(marks >=50) else if(marks >=50) printf(”Second”); printf(”Second”); else if(marks >=40) else if(marks >=40) printf(”Third”); printf(”Third”);
printf(”Fail”); printf(”Fail”); } } 2. Switch statement: 2. Switch statement:
Switch statement is a multi way decision statement which tests the value of a given variable (expression) Switch statement is a multi way decision statement which tests the value of a given variable (expression) against a list of case values and when a match is found a block of statements associated with that case is against a list of case values and when a match is found a block of statements associated with that case is executed. The general form of switch statement is as shown below
executed. The general form of switch statement is as shown below Switch (expression)
Switch (expression) {
{ case case value1: value1: block-1; block-1; break;break; case value 2: block-2;break ; case value 2: block-2;break ; default: default block;
default: default block; }
}
//Program to check if the given character is vowel //Program to check if the given character is vowel
void main( ) void main( ) {
{ char char ch;ch;
printf (”\n Enter any character”); printf (”\n Enter any character”);
scanf (“%c”, &ch) ; scanf (“%c”, &ch) ; switch(ch)
switch(ch) {
{ case case ‘A’ ‘A’ ::
case ‘a’ : printf(”Vowel”); break; case ‘a’ : printf(”Vowel”); break; case ‘E’ :
case ‘E’ : case
case ‘e’ ‘e’ : : printf(”Vowel”); break;printf(”Vowel”); break; case ‘I’ :
case ‘I’ : case
case ‘i’ ‘i’ : : printf(”Vowel”); break;printf(”Vowel”); break; case ‘O’ :
case ‘O’ :
case ‘o’ : printf(”Vowel”); break; case ‘o’ : printf(”Vowel”); break; case ‘U’ :
case ‘U’ :
case ‘u’ : printf(”Vowel”); break; case ‘u’ : printf(”Vowel”); break; default : printf(”\n Not Vowel”) ; default : printf(”\n Not Vowel”) ; }
} }
Conditional operator is compressed version of if statement. It is also called ternary operator because it Conditional operator is compressed version of if statement. It is also called ternary operator because it
requires three operands. The general form of use of the conditional operator is as follows requires three operands. The general form of use of the conditional operator is as follows
Conditional
Conditional Expression? Expression? exp1: exp1: exp2exp2
The conditional expression is evaluated first if the result is true exp1 is evaluated and is returned otherwise The conditional expression is evaluated first if the result is true exp1 is evaluated and is returned otherwise exp2 is evaluated and its value is returned.
exp2 is evaluated and its value is returned.
For Example For Example void main( ) void main( ) { { int int x=2, x=2, y y ;; y= ( x>2) ? ( 2 * x * 5) : (3 * x +1); y= ( x>2) ? ( 2 * x * 5) : (3 * x +1); printf(“%d”,y) ; printf(“%d”,y) ; } } Output Output : : 77
2. Looping:
2. Looping:
Loo
Loops are ps are used to used to reperepeat the at the somsome e portportion of ion of a a progprogram eitheram either r a specifia specified ed numbnumber of er of timtimes or es or untiuntil l aa particular condition is being satisfied. Mainly loops are of two types. One is
particular condition is being satisfied. Mainly loops are of two types. One is Entry Controlled LoopEntry Controlled Loop andand another is
another isExit Controlled LoopExit Controlled Loop..
a) Entry Control Loop:
a) Entry Control Loop: In this type of In this type of loop firsloop firstly condtly conditiition is on is checchecked if ked if it is it is true then body of thetrue then body of the loop is executed otherwise body of the loop is not executed.
loop is executed otherwise body of the loop is not executed.
b) Exit Control Loop:
b) Exit Control Loop: In this type of loop firstly body of the loop is executed then condition is checked,In this type of loop firstly body of the loop is executed then condition is checked, now if condition is true then body executed again until the condition becomes true otherwise the now if condition is true then body executed again until the condition becomes true otherwise the program goes out of the loop.
program goes out of the loop.
After the above types, there are three ways by which we can repeat a part of the program. After the above types, there are three ways by which we can repeat a part of the program. 1. For statement 1. For statement 2. While statement 2. While statement 3. Do-while statement 3. Do-while statement 1. For loop: 1. For loop:
For loop is an entry control
For loop is an entry control loop. It is one step loop, which initialize, check the condition andloop. It is one step loop, which initialize, check the condition and
increment/decrement the step in the loop in a single step. For loop is used where the loop will be traversed a increment/decrement the step in the loop in a single step. For loop is used where the loop will be traversed a fixed number of times. The general form of for statement is as under
fixed number of times. The general form of for statement is as under for( initialization; test condition; modifier expression)
for( initialization; test condition; modifier expression) {
{
body of the loop; body of the loop; } } For Example For Example void main( ) void main( ) { { int int i;i;
for( i=1;i<=5; I++) for( i=1;i<=5; I++)
printf(”ICIT”); printf(”ICIT”); }
}
output: ICIT prints 5 times. output: ICIT prints 5 times. void main( )
cout<<”Hello”; cout<<”Hello”; }
}
Output: Hello infinite times. Output: Hello infinite times.
2. While loop: 2. While loop:
While is an
While is an entry controlentry controlled loop statement. The test condition is evaluated and led loop statement. The test condition is evaluated and if the condition is true if the condition is true thenthen the body of
the body of the loop is the loop is executed. While loop keeps repeating an action until the test executed. While loop keeps repeating an action until the test conditiocondition returns false.n returns false. The general form of while loop is as under:
The general form of while loop is as under: initialization;
initialization;
while( test condition) while( test condition) { { BBooddy y oof f tthhe e lloooopp;; }} For example For example void main( ) void main( ) {
{ int int sum sum =0; =0; int int n=1;n=1; while (n<=5) while (n<=5) { { ssuumm= = ssuumm++n n ;; n++; n++; } } printf(“%d”,sum); printf(“%d”,sum); } } Output: 15 Output: 15 3. Do-while statement: 3. Do-while statement: Do
Do While is an exit controlled loop statement. In this loop, first body of the loop is executed and then theWhile is an exit controlled loop statement. In this loop, first body of the loop is executed and then the condition is checked. If condition is true, then the body of the loop is executed. When conditions become condition is checked. If condition is true, then the body of the loop is executed. When conditions become false, then it will exit from the loop. The syntax of this loop is:
false, then it will exit from the loop. The syntax of this loop is: initializations;
initializations; do
do {
{ body body of of the the loop; loop; }} while ( test condition);} while ( test condition);} void main( ) void main( ) { { iinnt t ii==1100;; do do
i++; i++; } while( i<10); } while( i<10); } } Output: Hello Output: Hello
3. Jumping:
3. Jumping:
1. Break statement: 1. Break statement:Break statement is used for an early exit from a loop .It is usually used with for loop, do-while, while loops Break statement is used for an early exit from a loop .It is usually used with for loop, do-while, while loops and in the switch statement.
and in the switch statement. void main( ) void main( ) { { int i=1; int i=1; for( for( ; ; ; ; )) { { iiff((ii>>55)) break; break; printf(“%d”, i); printf(“%d”, i); i++; i++; } } } } Output: 12345 Output: 12345 2. Continue
2. Continue statementstatement
Continue statement causes the loop to continue with the next iteration without executing remaining Continue statement causes the loop to continue with the next iteration without executing remaining statements. It is usually used with for loop, do-while, while loops
statements. It is usually used with for loop, do-while, while loops void main( ) void main( ) { { for(int i=1;i<=10;i++) for(int i=1;i<=10;i++) if( i%2==0) if( i%2==0) continue; continue; printf(“%d”, i); printf(“%d”, i); } }
3. Goto Statement: 3. Goto Statement:
Goto is a powerful jumping statement. This statement moves the control on a specified address. Jump can be Goto is a powerful jumping statement. This statement moves the control on a specified address. Jump can be either in forward direction or in backward direction.
either in forward direction or in backward direction.
a) Forward GOTO:
a) Forward GOTO: In this control moves forward at some specified level in the program. TheIn this control moves forward at some specified level in the program. The syntax of this is like:
syntax of this is like: Statement1; Statement1; Statement2; Statement2; Goto label; Goto label; Statement3; Statement3; Label: Label: Statement4; Statement4; In the
In the above example after the statement2, statemeabove example after the statement2, statement4 will be nt4 will be executeexecuted because after d because after statemstatement2 theent2 the flow will turned towards statement4 and statement3 will be skipped.
flow will turned towards statement4 and statement3 will be skipped.
a) Backward GOTO:
a) Backward GOTO: In this control moves backward at some specified level in the program. TheIn this control moves backward at some specified level in the program. The syntax of this is like:
syntax of this is like: Statement1; Statement1; Statement2; Statement2; Label: Label: Statement3; Statement3; Statement4; Statement4; Goto Label: Goto Label:
In the above example after the statement4, statement3 and statement4 will be executed again and In the above example after the statement4, statement3 and statement4 will be executed again and again until some specified condition not met to exit from this loop.
again until some specified condition not met to exit from this loop.
Example of Backward Goto Example of Backward Goto
void main ( ) void main ( ) {
{ int int i=1;i=1; take: take: if( i>=10) if( i>=10) printf(“%d”, i); printf(“%d”, i); else else { i++; { i++;
} } Output: 10
Output: 10
Example of Forward Goto Example of Forward Goto
void main ( ) void main ( ) {
{ int int a=10, a=10, b=20, b=20, c, c, d;d; c = a+ b; c = a+ b; d = b-a; d = b-a; printf(“%d”, c); printf(“%d”, c); goto label; goto label; printf(“%d”, d); printf(“%d”, d); label: label: getch(); getch(); } } Output: 30 Output: 30
Difference Between While & Do While
Difference Between While & Do While
S
SNNoo WWhhiillee DDoo WWhhiillee
1
1 WhWhiille e lloooop p iis s eennttrry y ccoonnttrroolllleed d lloooopp i.e
i.e the test the test condition is condition is evaluatedevaluated first and if the condition is true then first and if the condition is true then the body of the loop is executed. the body of the loop is executed.
Do while loop is exit controlled Do while loop is exit controlled loop i.e. first body of the loop is loop i.e. first body of the loop is executed and then condition is executed and then condition is checked
checked 2
2 WhWhiille e lloooop p wwiilll l nnoot t eexxeeccuutte e aannyy statement if the condition is false statement if the condition is false e.g. e.g. void main() void main() { int i=11; { int i=11; while (i<=10) while (i<=10) { { printf(“%d”, i); printf(“%d”, i); } } } }
Output: Blank Screen Output: Blank Screen
Do While loop executes at least Do While loop executes at least once once e.g. e.g. void main() void main() { int i=11; { int i=11; do do { { printf(“%d”,i); printf(“%d”,i); }while (i<=10); }while (i<=10); } } Output: 11 Output: 11 3
Difference Between Break & Continue
Difference Between Break & Continue
1
1 Break statement is used for an earlyBreak statement is used for an early exit from a loop.
exit from a loop. ..
Continue statement causes the loop Continue statement causes the loop to continue with the next iteration to continue with the next iteration without executing remaining without executing remaining statements.
statements.
2
2 IIt t iis s uussuuaalllly y uusseed d wwiitth h ffoor r lloooopp, , ddo o--while, while loops and in the switch while, while loops and in the switch statement. statement. e.g. e.g. void main( ) void main( ) { { iinnt t ii==11;; for( for( ; ; ; ; )) { { iiff((ii>>55)) break; break; printf(“%d”, i); printf(“%d”, i); i++; i++; } } } } Output: 12345 Output: 12345
It is usually used with for loop, It is usually used with for loop, do-while, while loops
while, while loops
e.g. e.g.
void main( ) void main( ) {
{ for(int for(int i=1;i<=10;i++)i=1;i<=10;i++) if( i%2==0) if( i%2==0) continue; continue; printf(“%d”, i); printf(“%d”, i); } } Output: 13579 Output: 13579
Functions
Functions
A function itself is a self contained block of statement that performs some specific task. It is also A function itself is a self contained block of statement that performs some specific task. It is also called sub programs or subroutines. Function has a property that it is reusable i.e. it can be executed from called sub programs or subroutines. Function has a property that it is reusable i.e. it can be executed from many points as required. We can pass information to the function in the form of arguments and some time many points as required. We can pass information to the function in the form of arguments and some time function return some value and sometimes return nothing. By default return type of function is int. Every function return some value and sometimes return nothing. By default return type of function is int. Every program in ‘C’ must have main () function because execution of program starts from main () function.
program in ‘C’ must have main () function because execution of program starts from main () function.
Function has following
Function has following advantages:advantages:
1.
1. Remove Remove coding recoding redundancy dundancy because sabecause same funcme function can tion can be used be used by maby many progrny programs.ams. 2.
2. Easy tEasy to understo understand and and and debug the debug the entire prentire program aogram as a cols a collection lection of functof functions.ions. 3.
3. The leThe length of sngth of sourcource progre program can be ream can be reduceduced by usind by using functg functionsions 4.
4. LesLess mems memory iory is requs required tired to run pro run prograogram if funm if functioction is usedn is used 5.
5. RelReliabiiabilitlity is high in fuy is high in functnction oriion orientented progred programmamminging 6.
6. TeTeststining ig is s eaeasisierer..
To define a function in C, we use three steps as: To define a function in C, we use three steps as:
1.
3.
3. DeDefifininitition of fon of fununctctioionn
Declaring a Function
Declaring a Function means to provide the basic information about a function to the compiler.means to provide the basic information about a function to the compiler. Function declaration is also known as Function Prototyping. The syntax for the declaration of the Function declaration is also known as Function Prototyping. The syntax for the declaration of the function is like
function is like
int mul(int a, int b); int mul(int a, int b); Calling a Function:
Calling a Function: When a function call is When a function call is made then the program jumps to the made then the program jumps to the function definifunction definitiontion part and execute that part of the program. After the execution of the function definition part control part and execute that part of the program. After the execution of the function definition part control
returns to the main program. The syntax for the calling of above function is like: returns to the main program. The syntax for the calling of above function is like:
mul (8, 9) mul (8, 9) Definition of Function
Definition of Function means actual code of the function that tells the compiler what to do. Themeans actual code of the function that tells the compiler what to do. The syntax for definition is like:
syntax for definition is like:
iinnt t mmuull((iinnt t aa, , iinnt t bb)) ////FFuunnccttiioon n HHeeaaddeerr {{
rreettuurrn n ((aa**bb));; ////FFuunnccttiioon n BBooddyy }}
E.g. 1 E.g. 1
#include<iostream.h> #include<iostream.h>
iinnt t mmuull((iinnt t aa, , iinnt t bb));; /// / FFuunnccttiioon n DDeeccllaarraattiioonn void main( )
void main( ) {
{ int int a=10, a=10, b=20, b=20, c;c;
cc= = mmuull((aa,,bb)) ////FFuunnccttiioon n CCaalllliinngg printf(”\n%d ”, c);
printf(”\n%d ”, c); }
}
iinnt t mmuull((iinnt t aa, , iinnt t bb)) ////FFuunnccttiioon n DDeeffiinniittiioonn { { iinnt t dd;; d= a*b; d= a*b; return(d); return(d); } }
#include<iostream.h> #include<iostream.h> void main( ) void main( ) { { void star( ); void star( ); star(); star(); printf(”\nWelcome to IIMT”); printf(”\nWelcome to IIMT”); star( ); star( ); printf(“\nGangtok”); printf(“\nGangtok”); } } void star( ) void star( ) { {
for( int i=0; i<5; i++ ) for( int i=0; i<5; i++ )
printf(”*”); printf(”*”); } } Function calls: Function calls:
There are two types of function calls There are two types of function calls
1)
1) CaCall ll by by vavaluluee 2)
2) CaCall ll by by rerefefererencncee
Call by value Call by value
In call by value we pass value of each actual argument (declared in the calling function) to corresponding In call by value we pass value of each actual argument (declared in the calling function) to corresponding formal arguments (declared in called function). With this method value of the actual arguments in the calling formal arguments (declared in called function). With this method value of the actual arguments in the calling function remains unchanged.
function remains unchanged.
void swap( int, int); void swap( int, int); void main( ) void main( ) { { iinnt t aa==1100, , bb==2200;; swap (a,b); swap (a,b); printf(”\na=%d \tb=%d”, a, b); printf(”\na=%d \tb=%d”, a, b); } }
void swap( int x, int y) void swap( int x, int y) {
} } Output:
Output: a=10 a=10 b=20b=20
Call by
Call by referencereference
In call by reference we pass addresses of actual arguments (Declared in the calling function) to formal In call by reference we pass addresses of actual arguments (Declared in the calling function) to formal arguments (Declared in the called function). So using this method we can change actual arguments. Using arguments (Declared in the called function). So using this method we can change actual arguments. Using this approach a function can return more than one value.
this approach a function can return more than one value. void swap( int *, int *)
void swap( int *, int *) void main( )
void main( ) {
{ int int a=10, a=10, b=20;b=20; swap(&a, &b); swap(&a, &b); printf(”\na=%d \tb=%d”, a, b); printf(”\na=%d \tb=%d”, a, b); } }
swap( int *x, int *y) swap( int *x, int *y) { { iinnt t tt;; t=*x; *x=*y; *y=t; t=*x; *x=*y; *y=t; } } Output:
Output: a=20 a=20 b=10b=10
Recursion
Recursion
When a function calls itself, then it is
When a function calls itself, then it is called recursiocalled recursion. If proper care not n. If proper care not taken then recursion will create antaken then recursion will create an indefini
indefinite loop. Recursion is te loop. Recursion is also called self-referealso called self-reference loop. A nce loop. A function is called recursive if a function is called recursive if a statemstatementent within the body of a function calls the same function. For example
within the body of a function calls the same function. For example E
Exxaammpplle e 11:: vvooiid d mmaaiinn( ( )) {
{ pprriinnttff((““HHeelllloo””));; main( );
main( ); }
}
Output: Hello Infinite times Output: Hello Infinite times
E
Exxaammppllee22:: iinnt t rreec c ((iinntt));; void main( ) void main( ) {
{ int int a, a, fact;fact;
printf(”\n Enter the number”); printf(”\n Enter the number”);
scanf(“%d”,&a); scanf(“%d”,&a); fact= rec(a); fact= rec(a);
} }
int rec (int x) int rec (int x) { { int int f;f; if ( x= =1) if ( x= =1) return 1; return 1; else else f= x*rec(x-1); f= x*rec(x-1); return f; return f; } } Advantages of Recursion Advantages of Recursion 1.
1. RecursioRecursion is more en is more efficient fficient if the progif the program using rram using recursion aecursion are run on core run on computer wimputer with multth multiprocessiiprocessingng facilities
facilities 2.
2. It is simpIt is simple, easle, easily undily understerstandaandableble, compa, compact and tract and transpansparentrent 3.
3. Lesser Lesser number number of progof programminramming stateg statements rements required quired with with the use the use of recof recursionursion 4.
4. It is very It is very useful in useful in solving the solving the data strucdata structure problture problems like lems like linked lisinked list, queues, t, queues, stack, trestack, tree etc.e etc.
Disadvantage
Disadvantages s of Recursionof Recursion
1.
1. It requireIt requires more mes more memory becmory because recuause recursive callrsive calls along wis along with automath automatic variabtic variables are stoles are stored on thered on the stack
stack 2.
2. The comThe computer mputer may run ay run out of mout of memory emory if recurif recursive calsive calls are nls are not properot properly chely checkedcked 3.
Array
Array
Array is a collection of related data items that share a common name and data type. These data items are Array is a collection of related data items that share a common name and data type. These data items are differen
differentiated by index tiated by index number or subscript in brackets after number or subscript in brackets after the array name. All arrays in the array name. All arrays in C start from C start from zero.zero. Array can be initialized at the time of declaration an arrangement of array elements in memory is contiguous Array can be initialized at the time of declaration an arrangement of array elements in memory is contiguous as shown below
as shown below
int a[ ]= { 1,2,3,4,10}; int a[ ]= { 1,2,3,4,10};
aa[[00]] aa[[11]] aa[[22]] aa[[33]] aa[[44]] 1 1 22 33 44 1100 4 4000022 44000044 40400066 44000088 44001100 Advantages of Array: Advantages of Array: 1.
1. LarLarge age amounmount of t of data data itemitems can s can be stbe storedored 2.
2. ArraArray hey helps tlps to arro arrange ange data data in soin sortirting ordng order er 3.
3. SeaSearchirching usinng using arrag array is fasy is fast if art if array is iray is in sortn sorting oring order der 4.
4. ArraArray can be usey can be used to cread to create data stte data structructures liures like stacke stack, queuk, queue etc.e etc.
Disadvantage of Array: Disadvantage of Array:
1.
1. One One arraarray cany can’t be ’t be assiassigned gned to anto anotheother arrr arrayay e.g.
3.
3. BounBound checd checking iking is the res the responsponsibisibilitlity of proy of programgrammer mer //
// WAP to count odd & even no’s from an array.WAP to count odd & even no’s from an array.
void main() void main() {
{ iinnt t aa[[1100]], , ii, , ccee;;
for (i=1; i<=10; i++) for (i=1; i<=10; i++) {
{
printf(”\n Enter Element:”); printf(”\n Enter Element:”);
cin>>a[i]; cin>>a[i]; if(a[i]%2==0) if(a[i]%2==0) ce++ ce++ } } printf(“\nEven No’s=%d”,ce); printf(“\nEven No’s=%d”,ce); printf(“\nOdd No’s=%d”,10-ce); printf(“\nOdd No’s=%d”,10-ce); } }
Addresses and Pointers
Addresses and Pointers
Every byte in the computer memory has an address. Addresses are basically numbers that start from 0 and Every byte in the computer memory has an address. Addresses are basically numbers that start from 0 and end at highest address which will vary
end at highest address which will vary accordinaccording to g to the amount of memory available in computer. E.g. Thethe amount of memory available in computer. E.g. The highest address for 64 KB of memory is
highest address for 64 KB of memory is 65535 (i.e. 64* 1024=65536 bytes). 65535 (i.e. 64* 1024=65536 bytes). & operator returns the memory& operator returns the memory address of a variable
address of a variable
Pointers are memory variables that store the address of another variable instead of value. Pointers are Pointers are memory variables that store the address of another variable instead of value. Pointers are declared as
declared as
int *p; int *p; The asterisk (
The asterisk (**) also called indirection operator.) also called indirection operator.
Advantages of Pointer: Advantages of Pointer:
1.
1. UsinUsing poig pointernters we cs we can cran create eate dynadynamic mic arraarrayy 2.
2. UsinUsing pointg pointers it is poers it is possibssible to pasle to pass comps complete arlete array to furay to functinctionon 3.
3. Helpful Helpful in cin creating reating data data structurstructures likes like line linked liked list, st, stack, stack, queuequeue 4.
4. PoiPointernters reducs reduce the lee the length & cngth & compomplexilexity of prty of prograogram.m. 5.
5. Passing Passing argumentarguments to funs to function whction when functen function needs ion needs to modito modify origify original argunal arguments.ments. 6.
Disadvantage
Disadvantages s of Pointer:of Pointer:
1.
1. UniUninitinitializalized poined pointerters causs cause the sye the system tstem to craso crash.h. 2.
2. DiDiffifficucult lt to to undunderserstantandd For Example
For Example void main( ) void main( ) {
{ int int i=3, i=3, *x; *x; float float j=1.5, j=1.5, *y;*y; Output:Output:
p
prriinnttff((““\\nn%%dd\\tt%%ff””, , ii, , jj)); ; 33 55 p
prriinnttff((““\\nn%%dd\\tt%%dd””, , &&ii, , &&jj));; 22000000 22000022 x
x==&ⅈ; yy==&&jj;; 20200000 22000022 p
prriinnttff((““\\nn%%dd\\tt%%dd””, , xx, , yy));; 33 55 printf(“\n%d\t%f”,
printf(“\n%d\t%f”, *x, *x, *y); *y); 3030 *x=30; *x=30; printf(“\n%d”, i); printf(“\n%d”, i); } } Operation on Pointers Operation on Pointers
Following operation can be performed on a pointer Following operation can be performed on a pointer
1)
1) AddAdditiition on of of a na numbumber er to to a a poipointenterr
int a[5]={11, 12, 13, 14, 15},*p; int a[5]={11, 12, 13, 14, 15},*p; p
p=&=&a[a[0]0];; ////ThThe ade addrdresess of s of ththe fie firsrst et elelemement ont of a if a is sts storored ied in p in p i.e.e. 2. 2000000 p
p=p=p+2+2;; ////p p nonow w cocontntaiains ns ththe e adaddrdresess s of of ththirird d elelememenent t of of a a i.i.e. e. 20200404 aa[[00]] aa[[11]] aa[[22] ] aa[[33]] aa[[44]]
2
200000 0 2200002 2 2200004 4 22000066 22000088
2) Subtraction of a number from pointer 2) Subtraction of a number from pointer
int a[5]={11, 12, 13, 14, 15},*p; int a[5]={11, 12, 13, 14, 15},*p; p
p=&=&a[a[3]3];; ////ThThe ade addrdresess of s of ththe foe foururth th elelememenent of t of a ia is sts storored ied in p in p i.e.e. 2. 2000066 p
p=p=p-1-1;; ////p np noow cw cononttaainins ts the he aadddrdreess ss of of tthhiird rd eleleemmenent ot of a f a ii..ee. 2. 2000404
Pointers and array:
Pointers and array: There is a close association between pointers and arrays. The array name itself is aThere is a close association between pointers and arrays. The array name itself is a pointer, which will store the base address of the array. For example
pointer, which will store the base address of the array. For example 1