C Language Reading Notes
C Language Reading Notes
COMPUTER:A computeris a machine that accepts data as input, processes that data using programs,
andoutputstheprocesseddataas information. Many computer scan store and retrieve information using
harddrives. Computerscanbeconnectedtogetherto formnetworks,allowing connected computers to communicate
with each other.
ZerothGeneration: Manused his fingers, ropes, beads, bones, pebblesandotherobjects for counting. Electricity
was not yet invented.
First Generation(Vacuum Tubes): Used vacuum tubes for computation, magnetic drumsfor memory, Tookup
lot of space, Very expensive , consumed great deal of electricity, generated a lot of heat, which was often the
cause of malfunctions. Input was based on punched cards and output was obtained on paper.
Second Generation(Transistors): Transistors replaced vacuum tubes which are smaller, faster, cheaper, more
energy-efficient and more reliable than their first-generation predecessors. Still relied on punched cards for input
and printouts for output. Generate less heat and consumed less electricity as compared to First generation
computers.Still very costly.Support assembly language and high level language such as FORTRAN & COBOL.
Third Generation(Integrated Circuits): Integrated circuit was used such as Transistors, resistors, capacitors
and diodes were integrated onto a single chip. Computers of this generation are Smaller, cheaper and energy-
efficient & users interacted through keyboards andmonitors.Memory
capacityincreasedandmagneticharddiskwasusedbutStillcostly
Fourth Generation(Microprocessor): Microprocessor were used, What in the first generation filled an entire
room could now fit in the palm of the hand.As these small computers became more powerful, they could be
linked together to form networks, which eventually led to the development of the Internet.Fourth generation
computers alsosaw the
development of GUIs, the mouse and Hand held devices. Finally Computers became easily available
Fifth Generation(Artificial Intelligence): based on artificial intelligence, are still in development, though there
are some applications, such as voice recognition, that are being used today. The goal of fifth-generation
computing is to develop devices that respond to natural language input and are capable of learning and self-
organization.
SUPERCOMPUTERS: These are the huge machines having the most powerful and fastest processors.A
supercomputer uses multiple CPUs for parallel data processing, which means portions of the same program are
handled independently by multiple processors.Super computersaretoo powerfulto beusedfor
transactionprocessing. Theyareemployed inareas that require enormous numerical computations like weather
forecasting, analysis of geological data, nuclear stimulation, and space exploration.The cost of supercomputers
are too high, they are mainly used by government agencies.
MAIN FRAME COMPUTERS: Before the advent of supercomputers, mainframe computers were the largest
computers available. These are the multiuser machines that can support hundreds or thousands of users using the
feature of “time sharing” supported by systems likeLinux.Todaymainframesareemployedto
handleonlinetransactions(likestock exchange transactions), The capability to handle large amounts ofdata makes
the mainframe suitable for use in government, banks, financial institutions and large corporations.
Adigit that canhaveonlytwo statesorvalues iscalledas binarydigit, whichisabbreviatedas “bit”.All binary numbers
are represented by combining these 0s and 1s.
Example:Thenumber 13isrepresentedas1101inthebinarysystem.
Asimilar relationship exists for bits also. So the speed ofnetwork expressed as 1Mbps(megabits per second) is
same as 1000Kbps.
ARCHITECTUREOFCOMPUTER(VonNeumannArchitecture/Block Diagram of
Computer): Computer is having three basic units such as
TheCentralProcessingUnit(CPU)
TheMainMemoryUnit
TheInput/OutputDevice
Theblock diagramofComputerArchitectureisasshownbelow:
CPU:Itcomprisesthefollowingcomponents:
Arithmetic and Logic Unit (ALU) - It carries out all arithmetic tasks. ALU also comparestwo
numbersandperforms“Boolean”operationssuchasAND,OR,NOT on them.
Primary memory – All of these memory units are housed on the motherboard of the PC such as RAM, ROM &
Cache memory. Except ROM, allthe memorytypes are volatile i.e., they loose the contents when power given to
computer is taken back.
Secondary memory - Computer system also supports secondary memory which is also called as secondary
storage or auxiliary memory.These devices are slower thanprimary memory but they have larger capacities.Some
of the examples include Hard disc, Pen drive, CD, DVD etc.
INPUT/OUTPUT DEVICES:We interact with the operating system for performing the daily chores like
editing, copying and deleting files.Some ofthe common input devices are keyboard, Mouse & Scanners etc.
Theterm outputgenerally referstotheinformation thatcanbeseenorheard.Someof the common output devices are
Monitor, Printer & Speakers etc.
PORTS AND CONNECTORS: Devices like printers and scanners connect to a computer through
docking points called ports.All ports are connected to mother board but are visiblefromoutside. Theyareshaped
differently, so it is impossibleto useawrong connectorfor aport.
Serial Port: Once used by keyboard, mice and modems serial ports are offered in 9-pins and 25-pins.
Video Graphics Array (VGA): This 15-pin port allows transfer of analog (continuous) video data to the
monitor.
RJ45port:ThisisusedbytheEthernetnetwork.
PS/2 port: This port has replaced the serialport for connecting the keyboard and mouse. It has 6 pins but occurs
as a pair in two different colors.
Servers acts as the backbone of the largest network of all- the internet.Networktopology is the arrangement of
the elements (links, nodes, etc.) of a communication network.
There are a number of ways of topologies of connecting computers, each having its own merits and demerits:
Bustopologyusessinglecableasabusto whichallcomputersareconnected.Thefailure of one node doesn‟t disrupt
communication between the remaining nodes.
Star topology uses central hub to which all nodes are connected. Due to network traffic
throughthehub,theentirenetworkfails ifthe hubfailsto work. Newnodescanbeadded without disrupting the service.
Networksareclassifiedbasedontheirsize. Thethreemostcommontypesare:
LocalArea Network - LAN is used bysmall organizations where the area is confined to one building. They
generally use Ethernet technology. Wireless LANs (WLAN) also known as Wi-Fi (Wireless Fidelity) has
become popular. Standard Ethernet speeds are ruling at 100 Mbps. Wi-Fi networks using 802.11g operate at
round20 Mbps.
Wide Area Network - WANs extend the range used by LANs. It can connect a number of cities or
establishments in the same city. Because of the large distances, optic fiber cables, leased telephone lines and
radio transmission are used to connect WAN nodes
The Internet (also called net) is the largest wide area network on theplanet. It‟s a collection ofover 50,000
networks that run a special set of network protocols called TCP/IP.
Network Interface card (NIC) - Network Interface Card (NIC) or network card that is presented in the
computer. Most of the computers use Ethernet technology, this card is often called as Ethernet card.
Hub-acceptsnetworkdata fromacomputerandsimplybroadcaststhedatatoallnodes.
Bridge - maintains a table of MAC addresses of all machines in the segments connected to it. It connects two
networks using the same protocol (say, Ethernet).
Computersoftwarecanbebroadlyclassifiedintotwo types:
System Software - They are run by computer to manage the hardware connected to it. User will not have much
controlover it. Some good examples are OS, Compilers, Device Drivers etc.
Application Software - They are used for specific application. Some good examples are Games, Social media,
Anti-virus etc.
BASICSTRUCTUREOFC-PROGRAM
Documentation section - The documentationsectionconsists ofa set ofcomment lines giving the name of the
program, the author and other details, which the programmer would like to use later.
Link section - The link section provides instructions to the compiler to link functionsfrom the system library.
Definitionsection-Thedefinitionsectiondefinesallsymbolic constants.
Global declaration section - There are some variables that are used in more than
onefunction.Suchvariablesarecalledglobalvariablesandaredeclaredintheglobal
declaration section that is outside ofall the functions. This section also declares all the user-defined functions.
main () function section - EveryC programmust have one main function section. This section contains two
parts; declaration part and executable part. The declaration part declares all the variables used in the executable
part. There must be at least one statement intheexecutablepart. Thesetwo partsmust appear
betweentheopeningand closing braces. The program execution begins at the opening brace and ends at the
closing brace. The closing braceofthe main functionisthe logicalend ofthe program. All statements in the
declaration and executable part end with a semicolon.
C-TOKENS:The characters that can be used to form words, numbers & expressions depend
upon the computer onwhichthe program isrun. The charactersare grouped into the following
categories: Letters(A…Z, a….z), Digits (0…9), Special characters(%,&,:,;,*,!,#,<,>,?,=,”,/,\) &
Whitespaces.
ThesmallestindividualunitsinCprogramareknownas“CTokens”.
Keywords - Every word used in a C program is classified as either a keyword or as an identifier. A keyword in
C is a reserved word which has a specific meaning. Keywords in C cannot be used as identifiers. Keywords serve
as the basic building blocks for program statements
Firstcharactermustbeanalphabetorunderscore.
Mustconsistofonlyletters,digitsorunderscore.
Onlyfirst31charactersare significant.
Cannotuseakeyword.
Mustnotcontainwhitespace.
Constants in C- Constants are fixed values, which do not change during the execution of a program. C supports
several types of constants, which are as shown below:
“Integer Constant” refers to a sequence of digits. Generally in programs, the number systemsused are: decimal,
octaland hexadecimal. “Real Constants” integer numbersare not sufficient to represent quantities that vary
continuously, such as distances, height,
pricesetc.Thesequantitiesarerepresentedbynumberscontainingfractionalpartslike
25.234.Suchnumbersarecalledasrealor floatingpointconstants.
Strings– “SingleCharacterConstants” orcharacterconstant containsa single character enclosedinbetween single
quotes.Somevalid examples of character constants are: „f‟,
„A‟, „/‟, ‟;‟, „ „, „4‟.The character constant „4‟ is not equaltothe number 4. “String Literals or String
Constants” A sequence ofcharactersthat are enclosed betweendouble quotes is known as a string literal or string
constant. The characters in a string literal can be either letters, digits or specialsymbols or white spaces. Some
valid examples ofstring constants are: “hai”, “hEllO”, “hi5”, “Wel come” etc.
VARIABLES IN C: A variable is a placeholder for holding a value in the main memory (RAM).
Asthename implies, thevalue inthevariablecanchangeat anypointofexecutionof the program.
Forusingvariables inourprograms,thereareessentiallytwosteps:
Declarethevariable
Initializethevariable
Before using a variable in the program, we have to declare the variable. The syntax for declaring a variable in a
program is as shown below:
datatypevariable-name;
RulesforVariablesName–
Thevariable name must notbe morethan31 characters.Thesuggested lengthofa variable name is 8 characters.
Ciscasesensitive.So,thevariablename“average”isdifferentfrom “AVERAGE”.
Keywordsmustnotbeusedfordeclaringvariables.
Whitespacesarenotallowedwithinthevariablename.
Initializing a Variable – After declaring the variable, we can assign a value to the variable. This process of
assigning a value to the variable is known as initialization. Syntax for initializing a variable is as shown below:
variable-name=value;
int a; a=10;
Thedeclarationandinitializationcanbecombinedintoasinglelineasshownbelow:
inta=10;
Data Types in C:Adata type specifies the type of value that we use in our programs. Adata type is generally
specified when declaring variables, arrays, functions etc.
InANSIC,thedatatypesaredividedintothreecategories.Theyare:
Primitiveor Fundamentaldatatypes
User-defineddatatypes
Deriveddatatypes
Wecancreateuser-defineddatatypesintwoways:
Byusingthe “typedef”keyword
DefiningConstantsinC:Asthenamesuggeststhenameconstantsisgiventosuchvariablesor values
inCprogramming language whichcannot be modified once theyare defined.
Using#definepreprocessor directive
Usingaconstkeyword
#definepreprocessor directive - This directive is used to declare constant variable or any value. We can use this
to declare a constant as shown below:
#defineidentifierNamevalue
identifierName:Itisthenamegivento constant.
value:Thisreferstoanyvalueassigned to identifierName.
constkeyword - Usingconstkeyword to define constants is as simple as defining variables, the difference is you
will have to precede the definition with a const keyword.
constdatatype identifierName=value;
datatype:typeofdatastoredinplaceof value.
identifierName:Itisthenamegivento constant.
value:ThisreferstoanyvalueassignedtoidentifierName.
Example:constintintVal=10;constfloatfloatVal=4.14;
Declaring a variable as volatile:By declaring a variable as volatile, its value may be changed at any
time by some external source.
ex:volatileint date;
The value of data may be altered by some external factors. When we declare a variable as volatile, the compiler
will examine the value of the variable each time it is encountered to seeany external alteration has changed the
value.
Overflow and Underflow:Problem of data overflow and underflow occurs when the valueof a variable is
either too big or too small for the type to hold. The largest value that a variable can hold also depends on the
machine. An overflow normally results in the largest value,whereas an underflow results in zero. C does not
provide any warning or indication of integer overflow. It simply gives incorrect results.
Operand1OpOperand2
Operand1 and operand2 can be either data or variables or expressions. Op is the operator. In C, based on the
number of operands on which an operator can operate, the operators are dividedinto three types namely:
Unary
Binary
Ternary
ArithmeticOperators(+,-,*,/,%)
RelationalOperators(<,>,==,!=,>=,<=)
3)Logical Operators(&&,||,!)
AssignmentOperators(=,+=,-=,*=,/=,%=)
IncrementandDecrementOperators(++,--)
Conditional Operators(?)
BitwiseOperators(&,|,^,~,<<,>>)
SpecialOperators(,&sizeof)
Arithmetic Operators - C provides all the basic arithmetic operators as shown below. The arithmetic operators
can operate on any built-in data type in C.
Relational Operators - In C, whenever there is a need to compare two values and make a decisionbased onthe
outcome ofthe comparison, we use relationaloperators.The relational operators are generally used in decision
making statements like if, else if and in looping statementslike for,while,do whileetc.
Relationaloperatorsalwaysevaluatesto 0(false)or1 (true).
Logical Operators - The relational operators are used to compare at most two values i.e.
testingonecondition.Totestmorethanonecondition,weuselogicaloperatorsalongwith
relationaloperators.Thelogicaloperatorsalwaysevaluatestoeither0or1likerelational operators.
Assignment Operators - The assignment operators are used to assign value of an expression to a variable. The
general assignment operator is = (equal). In C, there are some special assignment operators known as shorthand
operators.The syntax of shorthand operators is as shown below:
varop=exp;
Increment/Decrement Operators - The increment and decrement operators provided by Care used to increment
or decrement the operand by a value of one. Both the increment and decrement operators are unary
operators.There are two variations in increment/decrement operators
pre-increment/decrement(++var/--var)
post-increment/decrement(var++/var--)
When pre increment is applied, the value of the variable is incremented by one first and then that value is used
for evaluation of the expression. When post increment is applied, the value of the variable is used in the
evaluation of the expression and after the expression is evaluated, the value of the variable is incremented by a
value of one.
Conditional Operator - The conditional operator “? :” in C, is a ternary operator, which operates on three
operands. This operator is used to construct conditional expressions of the form:
exp1?exp2:exp3;
Inthe above syntax, exp1, exp2 andexp3 refer to expressions.It evaluatesthe exp1 first and then based on the
result of the exp1 itevaluates either exp2orexp3. If the resultofexp1 is true or non-zero, then exp2 is executed or
ifthe result of exp1 is false or zero, then exp3 is executed.
Bitwise Operator’s - C supportsaset ofoperatorswhich operateat bit-level. These operators are known as bitwise
operators. The bitwise operators are used for testing a bit, setting a bit, complementing a bit or for shifting the
bits to left orright. The bitwise operators available in C are as shown below:
Special Operator’s - C supports some special operators such as comma “,” operator, sizeof operator, address
“&” operator, pointer operator “*” and some others. Thecomma “,” operator is used to combine multiple related
expressions together. A comma separated list of expressions is evaluated from left to right and the value of the
right most expression is the value of the combined expression. The sizeofoperator computes the size of an
expression or variable or constant or a data type.
sizeof(operand);
Expression evaluation in C:Expressions are evaluated based on operator precedence and associativity
rules when an expression contains more than one operator. Every C operator has a precedence (priority)
associated with it. This precedence is used to determine how anexpression involving more than one operator is
evaluated.
The operators at the higher level of precedence are evaluated first. The operators in the same
levelofprecedenceareevaluatedfromlefttorightorfromrighttoleft,basedon the associativity property of an operator.
In the below table we can look at the precedence levels of operators and also the associativity of the operators
within the same level. Rank 0 indicates the lowest precedence and Rank 14 indicates highest precedence.
Typecasting/conversion:Typecastingisconvertingonedatatypeintoanotherone.Itis also called as data
conversion or type conversion.
Implicittypecasting
Explicittypecasting
Implicit type casting – C automatically converts any intermediate values to the proper typeso that the expression
can be evaluated without loosing any significance.
Explicit type casting - There are some scenarios in which we may have to force type conversion. Suppose we
have a variable div that stores the division of two operands which are declared as an int data type.
(Type_name)expression;
Mathematicalfunctions:
ExampleProgramstobepreparedfromthismodule:
#include<stdio.h>
voidmain()
floatradius,area;
CProgramtocomputesimpleinterest
#include<stdio.h>void main()
intp,n,r,si;
clrscr();
printf("EnterPrinciple,Rateofinterest&Time:\n"); scanf("%d%d%d",&p,&r,&n);
si=(p*n*r)/100;
printf("SimpleInterestis:%d",si);
}
Module –2:Branching &LoopingStatements
INPUT-OUTPUTFUNCTIONS:TherearetwotypesofaconsoleI/Ofunctions:
Formattedinput-outputfunction
Unformattedinput-outputfunction
The major difference is that formatted function allows us to format the input from the keyboard and the output to
be displayed on the screen.
Unformattedinputandoutputfunctionsare
UnformattedInput-OutputFunctions:
only work with character data type. Unformatted inputand output functions donot requireany format specifiers.
Because they only work with character data type.
getchar() functionisusedtoget/readacharacterfromkeyboardinput.
var_name=getchar();
putchar() functionisused towriteacharacteronstandardoutput/screen.
Example:charx; putchar(var_name
x=getchar(); putchar(x);
gets() function can read a full string even blank spaces presents in a string. But, the scanf() function leave a
string after blank space space is detected. The gets() function is used to get any string from the user.
gets(var_name);
puts()functionprintsthecharaterarrayorstringontheconsole.Theputs()functionis similar to printf() function, but we
cannot print other than characters using puts() function.
puts(var_name);
Example:
charc[25];
printf("EnteryourName:"); gets(c);
puts(c);
Therearetwosimpleformsofprintf() statement:
Example:printf(“GOD”);
Thathasliteralstring,conversionspecifierandanyorallofthefollowing:variables,
Syntax:printf(“format specifier/formatstring”,listofvariables);
constantand expressionsvaluesto beprinted.
Example:printf(“%d%f”,x,y);
Cprovidesscanffunction inthestdio.hheader file. Usingthis functionwe canread values from the keyboard and
assign the values to variables. The syntax of scanf function is as shown below:
scanf(“controlstring”,&var1,&var2……)
scanf(“%s”,name);
scanf(“%d”,&a[i]);
SELECTION OR BRANCHING STATEMENTS: The C statements that transfer the control from
one place to other place in the program with or without any condition are called branching or selection
statements.
Theselection/branchingstatementscanbeclassifiedintotwo categories:
Conditional Control /Branch Statements: Conditional branching statements that alter the sequence
ofexecution ofthe program based on some condition are called Conditional branching statements/ selection
statements/decision statements.
Conditional Control /Branch Statements are as follows: simple if (single selection), if-else (two wayselection),
Nested if (multiple if statements), else –if ladder(multi-wayselection), switch ( multi-way selection).
Unconditional Control /Branch Statement: The statements that alter the sequence of execution of the program
based on some uncondition are called Unconditional branching statement.
UnconditionalControl/BranchStatementsareasfollows:GotoStatement,breakStatement,
continueStatementandreturnStatement.
CONDITIONALBRANCHINGSTATEMENTS:
If Statement(Simple If):: It is basically a two way decision statement it is used in conjunction with an
expression. It is used to execute a set of statements if the condition is true. If the condition is false it skips
executing those set of statements.
intage;
printf(“Youareeligibletovote”);
If-else Statement:: It is an extension of if statement .It is used to execute any one set of two set
ofstatementsat atime. If condition istrueit executesoneset ofstatementsotherwise it executes another set of
statements.
#include<stdio.h>void main()
{
intage;
printf("Youareeligibletovote");
else
printf("noteligible");
Nested If-else Statement:: When a series of decisions are involved we may have to use more than one if
else statement in nested form. The nested if else statements are multi decisionstatementswhichconsist ofif else
controlstatement within another ifor elsecontrol statement.
below:
Example:ProgramtofindthelargestofthreenumbersusingNestedifelsestatement
#include<stdio.h>
void main()
inta,b,c;
if (a>b)
if (a>c)
printf("%dislargest\n",a); else
printf("%dislargest\n",c);
else
if(b>c)
printf("%dislargest\n",b); else
printf("%dislargest\n",c);
If-else ladder (Multi-way Selection): In addition to two-way selection, most programming languages
provide another selection concept known as multi way selection. Multi-way selection chooses among several
alternatives.
When an action has to be performed based on many decisions, then this Statement is used when more than one
if-else statements are used in a sequence, it is called as if-else ladder.
Syntaxofif-elseladder:
if(condition-1)
statement-1;
elseif(condition-2)
statement-2; elseif(Condition-3)
statement-3; elseif(conditionn)
statement-n;
else
default-statement;
Statement-x;
#include<stdio.h>void main()
intmarks;
elseif(marks>=90&&marks<=100) printf("Outstanding\n");
else
printf("InvalidEntry\n");
Switch Statement (Multi-way Selection): It is a multi-way decision making control statement used to
make a selection between many alternatives. It is also known as switchcase break and default statement.
SyntaxofSwitchStatement:
switch(choice/expression)
casevalue1:block1; break;
casevalue2:block2; break;
casevaluen:blockn; break;
default:default_block ;
next Statement;
The value of choice or expression is always an integer value/Character. If the value of choice or
expressionis1thenblock1statementswillget executed. Afterexecutingtherespectiveblockthe control comes outside
the switch statement because of the break statement. If no case values matches with the value of the choice, then
the default block will get executed before exiting switch statement.
SwitchStatementRules:
A switch statement begins with the switch keyword that followed by a value expressionin the parenthesis( ).
Itisacombinationofmultiplecaselabelsthatmustbeseparatedbythebreakstatement.
Ifthevalueismatched,thestatementsofthat caselabelareexecuted.
In addition, we can specify the default label, which is executed when the value specified in the switch
expression, does not match with the given case labels.
Example:Programto simulatesimplecalculatorusingswitchstatement
#include<stdio.h>void main()
case'+':res=a+b;
printf("%g%c%g=%g\n",a,op,b,res); break;
case'-':res=a-b;
printf("%g%c%g=%g\n",a,op,b,res); break;
case'*': res=a*b;
printf("%g%c%g=%g\n",a,op,b,res); break;
case'/': if(b==0)
printf("ArthimeticException:CannotDivideanumberby0\n"); return;
else
{
res=a/b;
printf("%g%c%g=%g\n",a,op,b,res);
break;
case'%':res=(int)a%(int)b;
printf("%g%c%g=%g\n",a,op,b,res); break;
default:printf("Invaildoperator\n"); break;
Goto Statement:This statement is used to transfer the control from one point to another point anywhere
intheprogram. Thegotorequires a labelinorderto identifytheplacewhere the branch is to be made.
Thegeneralformsofgotostatement:
Example:
#include<stdio.h>void main()
inta=1; SHOW:
if(a>10)
printf("%d",a); a+=2;
gotoSHOW;
}
BreakStatement: Thebreakstatementisusedtobreakanytypeofloopaswellas switch statement. Breaking a
loop means terminating the loop.
Thegeneralformsofbreakstatement:
break;
Example:
switch(opr)
case'+':
printf("Sum:%f",(a+b)); break;
} controlistransferredtotheend ofblock
Continue Statement:The continue statement is used to transfer the control to the beginning of a statement
block in a loop. In other words, a break statement breaks the entire loop, but acontinuestatement breaksthecurrent
iteration. Thecontinuestatement breaksthe current execution of a loop condition and then continue the loop with
next condition.
The generalformsofcontinuestatement:
continue;
Example:
#include<stdio.h>int main()
inti=1;
//startingaloopfrom1to10 for(i=1;i<=10;i++){
if(i==5)
continue;
}
printf("%d\n",i);
} //endofforloop
return0;}
Return Statement:It is used to return the control to the calling function with/without a value. For example,
if a function is not returning any value, use the return keyword
return;
returnvalue;
Example:
intsumDigits()
for(digit=0;digit<=9;digit++)
sum=sum+digit;
returnsum; //Returningvalue&control
WayofLooping:
EntryControlledLooporpretestlooportoptestloop
Exit ControlledLooporposttestloop
TheCLanguagesupportsthefollowingthreeloopingoperations:
Thewhilestatement
Thedo whilestatement
Theforstatement
While Loop/Statement (Entry Controlled/Pretest loop):The while statement is the pretest loop. It
uses an expression to control the loop. Since it is a pretest loop, it tests the expressions before every iterations of
the loop.
#include<stdio.h>void main()
inti,n,sum=0;
printf("Enterthevalueofn\n"); scanf("%d",&n);
i=0;
while(i<=n)
sum=sum+i; i++;
printf("Thesumofnaturalnumbers=%d\n",sum);
ThesyntaxandflowchartofDo-Whilelooping statementisasillustratedbelow:
Example:Programtofindthe sumofnnaturalnumbersusingdowhile
#include<stdio.h>void main()
inti,n,sum=0;
printf("Enterthevalueofn\n"); scanf("%d",&n);
i=0;
do
sum=sum+i; i++;
while(i<=n);
printf("Thesumofnaturalnumbers=%d\n",sum);
Differencesbetweenwhile& do-whileloopingstatements
For Loop/Statement(Entry Controlled/Pre-test loop):The for statement isa pretest loop that uses
three expressions.
Syntax:
bodyoftheloop;
Theinitialization settheinitialvalueoftheloopcontrolvariable.
Thetestconditiontestthevalueoftheloop controlvariable.
Theincrement/decrement updatetheloopcontrolvariable.
Example:ProgramtoprintN NaturalNumbers
#include<stdio.h>void main()
inti,N;
printf(“EnterthevalueofN\n”); scanf(“%d”,&N);
for(i=0;i<=N;i++)
printf(“%d\n”,i);
for(i=1;i<=100;i++)
{
for(j=1;j<=50;j++)
PASCAL TRIANGLE: Pascal Triangle is a Triangle form which, each number is the sum of immediate
top row nearby numbers. The Value of edge is always 1.
CProgramtoprint pascaltriangle
introws,cal=1,space,i,j;
for(i=0;i<rows;i++) //outerloopfordisplayingrows
else
cal=cal*(i-j+1)/j; //calculatethecoefficient
printf("%d",cal);
printf("\n");
return 0;
CProgramtoprint binomial-coefficients
intn,a,bi_nom; n=0;
do
a=0;bi_nom=1;
while(a<=n)
If(a==0||n==0)
{
printf(“%d”,bi_nom);
else
a=a+1;
printf(“\n”); n=n+1;
while(n<=MAX);
EXAMPLEPROGRAMSTOBEPREPAREDFROMTHISMODULE:
disc=(b*b)-(4*a*c);
if((a==0)&&(b==0))
printf("Invalidco-efficients\n");
elseif(a==0)
elseif(disc==0)
printf("TherootsareRealandEqual\n"); root1=-b/(2*a);
root2=-b/(2*a);
printf("Root1=%f\nRoot2=%f\n",root1,root2);
}elseif(disc>0)
printf("TherootsareRealanddistinct\n"); root1=(-b+sqrt(disc))/(2*a);
root2=(-b-sqrt(disc))/(2*a); printf("Root1=%f\nRoot2=%f\n",root1,root2);
}
else
printf("TherootsareRealandImaginary\n"); real=-b/(2*a);
imag=sqrt(fabs(disc))/(2*a);
#include<stdio.h>void main()
temp=num; while(num!=0)
printf("Thereverseofthenumberis%ld\n”,rev); if(rev==temp)
printf("%ldisapalindrome\n”,temp); else
printf("%ldisnotapalindrome\n”, temp);
An electricity board charges the following rates for the use of electricity: for the first 200 units80 paise perunit:
forthe next 100 units 90 paise perunit: beyond 300 unitsRs 1 per unit. All users are charged a minimum of Rs.
100 as meter charge. If the total amount is more than Rs 400, then an additional surcharge of 15% of total
amount is charged. Write a program to read the name of the user, numberof units consumed and print out the
charges.
if(units<=0)
printf("InvalidUnits,Pleaseentervalidunits\n"); return;
else
printf("TotalCharges=%f\n",charges);
}
Module–3:Arrays &Strings
ARRAYS:“An array is a sequential collection/group of homogeneous (same type) elements which are
referred by the same name”
The type refers to the data types like int, char, float etc. All the elements/values in the arrayare ofthe same type
(data type). We cannot store values ofdifferent data types in the same array.
It is normal in programming to work with a list of values or a group of values at once. For such purposes,
variables cannot be used. So, C language provides the construct array for holding multiple values at once.
TYPESOFARRAYS:
One-dimensionalArrays:Tomaintainalistofvalues.
MultidimensionalArrays:Tomaintainatableofvalues.
Commonusesofonedimensionalarraysare:
Tomaintainalistofnumbers.
Tomaintainthelistofmarks.
Tomaintainalistofstudentnamesetc.
Syntax:for declaringa1-DArrayisshownbelow:
typearrayName[Size];
Example:
inta[10];
Intheaboveexample‟a’isanintegerarray,whichcanhold10integervalues.
Generally,therearetwotypesofinitializinganarray:
StaticInitialization(atcompiletime).
DynamicInitialization(atruntime).
SyntaxforstaticInitialization:
typearrayName[size]={value1,value2,…valueN}; Examples:
inta[10] = {1,2,3,4,5,6,7,8,9,10};
inta[10] = {1,2,3,4,5}
scanf(“%d”,&a[i]);
}
In the above example, the user will be storing the values into the array while executing the program. Until then,
garbage values will be stored in the array. Ifwe use braces i.e., { and }, for initializing the array, the default
values for all the elements in the arraywill be zero.
Example Program on One-dimensional Array: C Program to find Sum and Average of n Number using 1-D
Array
#include<stdio.h>void main()
printf("EnterHowmanyNumberyouwant?\n"); scanf("%d",&n);
printf("Entertheelementsonebyone\n"); for(i=0;i<n;i++)
Average=Sum/n;
Someoftheuses/applicationsofthetwodimensionalarraysare:
Tomaintainthemarksofstudents.
Tomaintainpricesofitemsetc…
Two-dimensionalArrayDeclaration:ForusingarraysinCprograms,justlikeweare declaring variables before using
them, we should declare arrays before using them.
Syntax:for declaringa2-DArrayisshownbelow:
typearrayName[rows][columns];
Example:
int x[3][3];
Intheaboveexample‟x’isanintegerarray,whichcanhold9integervalues.
Generally,therearetwotypesofinitializinganarray:
StaticInitialization(atcompiletime).
DynamicInitialization(atruntime).
Instaticinitialization,theelementsofanarrayareassignedvalueswhentheprogramis compiled.
SyntaxforstaticInitialization:
Example:inta[3][3],i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,a[i][j]);
inta[10][10],t[10][10],m,n,i, j;
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
t[j][i]=a[i][j];
for(j=0;j<n;j++)
printf("%d",t[i][j]);
SEARCHING:Theprocessoffindingaparticulariteminthelargeamountofdataiscalled
“searching”.Theelementtobesearchediscalled “keyelement”. There are two methods of searching:
1]Linearsearch. 2]Binarysearch.
Linear search also called sequential search is a simple searching technique. In this technique we search for a
given key item in linear order i.e. one after the other from first element to last element.If key item is present, the
search is successful, otherwise unsuccessful search.
LINEARSEARCH:
Algorithm:
Linear_search(list, value)
return successful
else
return unsuccessful
endprocedure
CProgramto performLinearSearch:
#include<stdio.h>void main()
inti,n,a[10],key;
printf(“enterarrayelements\n”); scanf(“%d”,&n);
printf(“enterarrayelements\n”);
for(i=0;i<n; i++)
scanf(“%d”,&a[i]);
printf(“enterthekeyelement\n”); scanf(“%d”,,&key);
for(i=0;i<n;i++)
if(key==a[i])
printf(“successfulsearch\n”); exit(0);
}}
printf(“unsuccessfulsearch\n”);
BINARY SEARCH:This search algorithm works on the principle of divide and conquers.For this algorithm to
work properly, the data should be in the sorted.
Thereare3casesinbinarysearchalgorithm
If themiddleitem is greaterthan theitem,then theitemis searchedin thesub-array to the left of the middle item.
Otherwise, the item is searched for in the sub-arrayto the right of the middle item. This process
continuesonthesub-arrayaswelluntilthesizeofthesub-arrayreduces tozero.
CProgramtoperformBinarySearch:
printf("enterthearrayelements\n"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enterthekeyelementtobesearched\n"); scanf("%d",&key);
low=0; high=n-1;
while(low<=high)
mid=(low+high)/2; if(a[mid]==key)
printf("ELEMENT%dFOUNDATPOSITION%d\n",key,mid+1); exit(0);
elseif(a[mid]>key) high=mid-1;
else
low=mid+1;
printf("UNSUCCESSFULLSEARCH\n");
return0;
SORTING: A Sorting is used to rearrange a given array or list elements according to a comparison operator
on the elements. The comparison operator is used to decide the new orderof element in the respective list of
elements.
BUBBLE SORT:Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based
algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in
order.
Thisalgorithmis notsuitableforlargedatasets.
Algorithm: Bubble Sort compares each pair of array element unless the whole array is completely sorted in an
ascending order.
{
for(j=0;j<n-i;j++) //forloopfornumber ofcomparisons
if(a[j]>a[j+1])//Comparison
a[j+1]=temp;
}}
CProgramtoperformBubblesort:
#include<stdio.h>void main()
inta[50],i,j,n,temp;
printf("enterthenumberofterms\n"); scanf("%d",&n);
printf("enterthearrayelements\n"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
for(j=0;j<n-i;j++) if(a[j]>a[j+1])
temp=a[j]; a[j]=a[j+1];
a[j+1]=temp;
printf("\nARRAYELEMENTSAFTERSORTING\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
SELECTION SORT: The Selection sort algorithm is based on the idea of finding the
minimumormaximumelement inanunsortedarrayandthenputting it initscorrect positionina sorted array.
Algorithm:Selection_sort(intA[],intn)
intminimum;//temporaryvariabletostorethepositionofminimumelement
minimum=i;//assumingthefirstelementtobetheminimum.
CProgramtoperformSelection Sort:
inta[100],n,i, j,minimum,temp;
printf("Enter%dintegers\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(inti=0;i<n-1;i++)
minimum = i ; for(intj=i+1;j<n;j++)
if(a[j]<a[minimum])
{
minimum=j;
if(a[minimum]!=a[i])
temp=a[i];
printf("Sortedlistinascendingorder:\n");
for(i=0;i <n;i++)
printf("%d\n",a[i]);
Someoftheexamplesofstringconstantsare: 1)“hai”
“helloworld”
“MynameisNITHIN”
Example:char s[5];
StringDeclaration&Initialization:weshoulddeclarestringsbeforeusingthemin the program. Strings are
implemented as character arrays.
Syntax:char string_name[size];
Example:charstudent_name[26];
When the compiler assigns a character string to a character array, it appends a „\0‟ to the end of the array. So,
the size of the character arrayshould always be number of characters plus 1.
charname[13]={„N‟,‟I‟,‟T‟,‟H‟,‟I‟,‟N‟,‟‟,‟K‟,‟U‟,‟M‟,‟A‟,‟R‟,‟\0‟};
charname[13]=“NITHINKUMAR”;
If less number ofcharacters are provided than the size ofthe string, the rest ofthe characters are initialized to „\0‟.
Unformattedinput/output–gets&puts
Syntaxforformattedinput/output:
Read–char str[10];
scanf(“%s”,str);
Print–printf(“Thestring is%s”,str);
Syntaxforunformatted input/output:
gets(str); //gets(array_name);
ExampleC programtoRead&PrintStrings:
/*Usingscanf&printf*/
strcat(string1,string2);
Thestrcat function acceptstwoparameterswhich arestrings.The strcat function takesthe
contentofstring2andmergesitwiththecontentin string1 andthefinalresultwillbestored in string1.
Example:
String-length (strlen): Thestrlen function is used to retrieve thelength of a given string. The return type
of this function will be an integer. The syntax of strlen function is as shown below:
strlen(string);
Example:
strcmp(string1,string2);
After comparison:
Ifthetwostringsare equal,thenthefunctionreturnsa0.
If1ststringisgreaterthan2ndstringreturns1.
If1ststringis lesserthan2ndstringreturns–1.
Example:
String-copy (strcpy): Thestrcpy function is used to copyone string into another string.
Thisfunctioncanbeusedforcreatingacopyofanexistingstring.Thesyntax of strcpy function is as shown below:
strcpy(string1,string2);
strrev(string);
thestrrev functionreversesthegivenstringandreturnsit back.Thecontentofthestringalso changes.
Example:
EXAMPLEPROGRAMSTOBEPREPAREDFROMTHISMODULE:
CprogramtoprintString LengthwithoutBuilt-infunction
intlen;
printf("Lengthof\"%s\"is%d\n",str1,len);
intmy_strlen(charstr1[])
int i=0;while(str1[i]!='\0')
i++;
return i;
CprogramtoComparetwoString’swithoutBuilt-infunction
#include<stdio.h> #include<string.h>
intcomp;
if(str1[i]=='\0') break;
i++;
returnstr1[i]-str2[i];
#include<stdio.h> #include<string.h>
intcomp;
voidmy_concat(charstr1[],charstr2[])
while(str2[j]!='\0')
str1[i++]=str2[j++];
str1[i]='\0';
printf("Concatenatedstringis\"%s\"\n",str1);
}
Programtofindsumofnarray elements
#include<stdio.h>void main()
inti,n,a[10],sum=0;
printf(“enternumberofarrayelements\n”); scanf(“%d”,&n);
scanf(“%d”,&a[i]);
for(i=0;i<n;i++)
sum=sum+a[i];
}printf(“sumis %d\n”,sum):
#include<stdio.h>void main()
inti,n,a[10],big;
printf(“enternumberofarrayelements\n”); scanf(“%d”,&n);
scanf(“%d”,&a[i]);
big=a[0]; for(i=0;i<n;i++)
if(a[i]>big)
big=a[i];
printf(“thebiggestelementinanarrayis%d\n”,big);
ProgramtoperformMatrixMultiplication.
#include<stdio.h>void main()
inta[10][10],b[10][10],c[10][10],m,n,p,q,i,j,k;
if(n==p)
printf("Entertheelementsoffirstmatrix\n"); for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("Entertheelementsofthesecondmatrix\n"); for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<m;i++)
for(j=0;j<q;j++)
{ c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
printf("Theproductoftwomatrixis\n");
for(i=0;i<m;i++)
for(j=0;j<q;j++)
printf("%d\t",c[i][j]);
printf("\n");
else
printf("Multiplicationisnotpossible \n");
}
Module–4:UserDefinedFunctions&RecursiveFunctions
FUNCTIONS:“In c, we can divide a large program into the basic building blocks knownas function. The
function contains the set of programming statements enclosed by {} that performs a particular task/job”.
A function can be called multiple times to provide reusability and modularity to the C program. Inotherwords,
wecansaythat thecollectionoffunctionscreatesaprogram. The functionisalso known as procedure or subroutine in
other programming languages.
Example:voidhello()
printf("hellonithin");
Need of Functions: Until now, in all the C programs that we have written, the programconsists of a main
function and inside that we are writing the logic of the program.
The disadvantage of this method is, if the logic/code in the main function becomes huge or complex, it will
become difficult to debug the program or test the program or maintain the program. So we‟ll break down entire
logic into different parts, this type ofapproach for solving the given problems is known as Top Down approach.
Advantages of Functions: Functions have many advantages in programming. Almost all the languages support
the concept of functions in some way. Some of the advantages ofwriting/using functions are:
Functionssupporttop-downmodular programming.
Writingfunctionsmakesiteasiertoisolateanddebugtheerrors.
Functionsallowusto reusethecode.
TYPESOFFUNCTIONS:Basedonthenatureoffunctions, theycanbedivided intotwo categories. They are:
In-builtfunctions/Predefinedfunctions/Libraryfunctions
Userdefinedfunctions
In-built functions / Predefined functions: is a function which is already written by another developer. The
users generally use these library functions in their own programs for performing the desired task.
Example:foruserdefined functionismainfunction.
BASICELEMENTSOFUSERDEFINEDFUNCTION:Forcreatinguserdefined functions in C
programs, we have to perform three steps. They are:
FunctionDeclaration:Declaringthe function(blue-print).
FunctionDefinition:Definingthefunction(logic).
FunctionCalling:useoffunctioninprogram(calling)
FUNCTION DECLARATION: The function declaration is the blue print of the function.The function
declaration can also be called as the function’s prototype.
The function declaration tells the compiler and the user about whatis the function‟s name,inputs and output(s) of
the function and the return type of the function.
Syntax:fordeclaringafunctionisshownbelow:
return_typefunction_name(parameterslist);
Example:
intadd(intm, intn);
In the above example, add is the name of the function, int is the return type of thefunction. In our example, add
function has two parameters. The parameters list is optional.
Syntax:offunctiondefinitionisshownbelow
return_typefunction_name(parameterslist)
localvariabledeclaration's;
---
return(expression);
Example:
intadd(inta,int b)
Syntax:offunctiondefinitionisshownbelow
functionwithoutargumentsandwithoutreturnvalue
functionwithoutargumentsandwithreturn value
functionwitharguments andwithreturnvalue
Generally, these types of functions are used to perform housekeeping tasks such as printing some characters etc.
Example:
voidprintstars(){ int i;
for(i=0;i<20;i++)
printf(“*”);
}
In the above example, printstars function does not have any parameters. Its task is to print20 stars whenever it is
called in a program.
Function without arguments and with return value: Inthis type of functions, the function definition does not
contain arguments. But the function returns a value back to the point at which it was called.
Example:
int readint()
intnum;
printf(“Enteranumber:“); scanf(“%d”,&num);
returnnum;
In the above example, readint function has no parameters/arguments. The task of this function is to read an
integer from the keyboard and return back to the point at which the function was called.
Function with arguments and without return value: Inthis type offunctions, the function definition contains
arguments. But the function does not returns a value back to the point at which it was called.
Example:
voidsum(int a,intb)
printf("\nThesumis%d",a+b);
Function with arguments and with return value: In this type of functions, the function definition consists
ofparameters/arguments. Also, these functions returns a value back to the point at whichthe functionwas called.
These types of functions are the most frequentlyused in programming.
Example:intadd(intx,inty)
{
}
Intheaboveexample, the functionadd consistsoftwo argumentsor parameters xandy. The function
addsbothxandyand returns thatvaluestored in thelocal variable result back to the point at which the function was
called.
PROGRAMTOFINDGCD&LCMUSINGFUNCTIONS:
NESTED FUNCTION: A function calling another function within its function definition is known as a
nested function.
So, far we are declaring a main functionand calling other user-defined functions and predefined functionslike
printf,scanf,gets,puts etc.,So, main functioncanbetreatedasanested function.
Example:
voidmain()
{
func1();
voidfunc1()
for(i=1;i<10;i++)
func2();
voidfunc2()
printf(“%d\n”,i);
ActualParameters
FormalParameters
There are two methods to pass parameters from calling function to called function and they areas follows...
PassbyValue
PassbyReference
PASS BY VALUE: In call by value parameter passing method, the copyofactualparameter values are copied to
formal parameters and these formal parameters are used in called function.
The changes made on the formal parameters does not effect the values of actualparameters. That means,
after the execution controlcomes back to the calling function, the actual parameter values remains same.
Example:
a=b;
b=temp;
PASS BY REFERENCE: InCall by Reference parameter passing method, the memory location address ofthe
actualparameters is copied to formalparameters. Thisaddress is used to access the memory locations of the actual
parameters in called function.
Whenever we use these formal parameters in called function, they directly access thememory locations of actual
parameters. So the changes made on the formal parameterseffects the values of actual parameters.
Example:
{
inttemp;
temp=*a;
*a=*b;
*b=temp;
DifferencebetweenPassbyValue&Reference:
SCOPE,VISIBILITY&LIFETIMEOFVARIABLES(STORAGECLASSES)
“auto” Thisisthedefaultstorage classforall thevariables declaredinside afunction ora block. Hence, the keyword
auto is rarelyused while writing programs in C language.
Auto variables can be only accessed within the block/function they have been declared andnot outside them
(which defines their scope).
example:autointi=1;
Theyareassignedagarbagevaluebydefaultwhenever theyaredeclared.
“extern” extern storage class simply tells us that the variable is defined elsewhere andnotwithin the same block
where it is used.
“static” This storage class is used to declare static variables which are popularly used while writing programs in
C language.
example:staticinti=1;
“register” This storage class declares register variables which have the same functionalityas that of the auto
variables.
The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free
register is available. This makes the use of register variables to be much faster than that of the variables stored in
the memory during the runtime of the program.
example:registerint i;
An important and interesting point to be noted here is that we cannot obtain the address ofa register variable
using pointers.
RECURSIVEFUNCTION:Afunctionissaidto berecursive, ifa functioncallsitself within the function‟s
definition.
Intheaboveexample,func1iscallingitselfinthelastlineofitsdefinition.
RecursiveFunction:
5!=5*4!// n*Fact(n-1)
4!=4*3!
3!=3*2!
2!=2*1!
1!=1*0!
0!=1 //StopCondition
#include<stdio.h>
intnum,fact;
printf("\nEnteranyintegernumber:"); scanf("%d",&num);
fact=find_factorial(num);
printf("\nfactorialof%dis:%d",num,fact);
{
if(n==0)
return 1;
else{
return(n*find_factorial(n-1));
FIBONACCI SERIES – a series ofnumbers in whicheach number ( Fibonacci number) is the sum of the two
preceding numbers.
Thefirsttwonumbersoffibonacciseriesare0and1.
RecursiveFunction:Thereare3cases infibonacciseries
ifn=1 onlyonedigittobeprintedi.e“0”.
ifn=2 onlytwodigittobeprintedi.e“1”.
#include<stdio.h>int fib(int);
voidmain()
intn,i=0,c;
printf("%d\n",fib(i)); i++;
}
}
intfib(intn)
if(n==0||n==1) return n;
else
return(fib(n-1)+fib(n-2));
}
EXAMPLEPROGRAMSTOBEPREPAREDFROMTHISMODULE:
intdec,bin;
dec= convert(bin);
printf("TheDecimalEquivalentof%dis%d\n",bin,dec);
intconvert(intbin)
if(bin== 0)
return 0;
else
intres,num;
printf("%disnotaPrimeNumber\n",num); else
printf("%disaPrime Number\n",num);
intisPrime(int num)
{
inti;
if(num==0||num==1) return 0;
for(i=2;i<=num/2;i++)
if(num %i==0)
return 0;
return 1;
}
Module –5:Structures,Pointers&Preprocessor Directives
STRUCTURES:“A structure is a collection ofheterogeneous data elements referred bythe same name”.
Drawback of arrays: arrays can be used to represent a collection of elements of the same data type like int, float
etc. They cannot be used to hold a collection of different types of elements.
structstructure_name
datatypevar1; datatypevar2;
-------
};
Example:
structstudent
introllno;
};
Inthe aboveexample, student isthe nameofthe structure. The membersofthe student structure are: name, rollno
and marks. A structure itself does not occupy any memory in the RAM. Memory is allocated only when we
create variables using the structure.
Declaring Structure Variables: Astructure variable declaration is similar to the declaration of variables of any
other data types.
Syntaxfordeclaring structurevariables:
structstudents1,s2,s3;
structstudent
introllno;
} s1,s2,s3;
introllno;
}student;
The namestudent representsthe structure definitionassociated with it and therefore can be used to declare
structure variables as shown below:
students1,s2,s3;
Accessing Structure Members:We can access and assign values to the members of a structure in a number of
ways.They should be linked to the structure variables in order to make them meaningful members.
Syntaxforaccessingastructure member:
structure-varaible.membername
Example:
s1.name s1.rollno
StructureInitialization: Thevaluescanbeinitializedintwoways
static initialization
dynamic initialization
Exampleforstaticinitialization:
structstudent
introllno;
};
structstudents1={“01”,“nithin”,”96”}; structstudents2={“02”,”gowda”,”56”};
Examplefordynamic initialization:
scanf(“%d”,&s1.rollno);
scanf(“%s”,s1.name);
scanf(“%d”,s1.marks);
ARRAYS OF STRUCTURES:If we want to store details of 100 students it will become difficult to
declare and maintain 100 variables and store the data. Instead, we can declare and array of structure variables as
shown below:
structstudent
introllno;
};
structstudents[100];
Exampleofnestedstructure:
structstudent
structname
charfname[10]; charlname[10];
};
};
Inthe above example, student is the outer structure and the inner structure nameconsists oftwo members: fname
and lname.
WecanpasstheCstructurestofunctionsin3 ways:
Passingthewholestructureasavalue.
Syntaxforpassingthestructurevariableasaparameterisshown below:
return-typefunction-name(structstructnamevar)
{
return expression;
Exampleforpassby value:
intid;
};
structstudentrecord={“01”,“Nithin”,”69”} func(record);
voidfunc(structstudentrecord)
printf("Percentageis:%f\n", record.percentage);
}
PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS : the whole structure is passed to another
function by address. It means only the address of the structure is passed to another function. The whole structure
is not passed to another function with all members.
Exampleforpassby Address(reference)::
intid;
};
structstudentrecord={“01”,“Nithin”,”69”} func(&record);
voidfunc(structstudentrecord)
printf("Percentageis:%f\n",record->percentage);
#include<stdio.h>struct student
{
introll;
};
voidmain()
floataverage=0.0;
printf("Enterthenumberofstudents\n"); scanf("%d",&n);
for(i=0;i<n;i++)
for(i=0;i<n;i++)
sum=sum+s[i].marks;
average=(float)sum/n;
printf("%4d",s[i].roll);
printf("%15s",s[i].name);
else printf("\tNo");
printf("\n");
pointerscanbeusedtoaccessandmanipulatedatastoredinthememory.
Pointersaremoreefficientinhandlingarraysanddatatables.
PointersallowCto supportdynamicmemorymanagement.
Pointerscanbeusedtoreturnmultiplevaluesfromafunctionviafunctionarguments.
Pointersallowpassingafunctionasargumenttootherfunctions.
How a Pointer Works: Whenever we declare a variable in our programs, the system allocatessomewhere inthe
memory, anappropriate locationto hold the valueofthe variable. This location will have its own address number.
Consider the following example:
So, we can access the value 200 either by using the variable name varor byusing the address of the memory
location which is 5000.‟
Pointer Variable, Constants & Values: “The concept of storing memory address ina variable and
accessing the value available atthat addressis known asa pointervariable.”
Sincethepointerisalsovariable,itwillalsohaveamemoryaddressjustlikeanyothervariable.
Pointer Constants: The memory addresses within a computer are referred to as pointer constants.
PointerValues: We cannot assignthe memoryaddresses directlyto a variable. We canonly get the address of a
variable by using the address operator (&). The value thus obtained is known as pointer value.
Pointer Variables: Once we obtain the pointer value, we can store it in a variable. Such variable which stores
the memory address is known as a pointer variable.
Declaring Pointer Variables: In C, every variable must be declared for its type. Since pointer variables
contain addresses that belong to a specific data type, they must be declared as pointers before we use them.
Syntaxfordeclaringapointerisasshownbelow: datatype*pointer-name;
This tells the compiler three things about the variable pointer-name. Theyare: The asterisk (*)
tellsthatthevariablepointer-name isapointervariable, pointer-nameneedsa memorylocation and pointer-name
points to a variable of type datatype.
Example:
int *p;float*p;char*ch;
Initialization of pointer variables: The process ofassigning the address ofa variable to pointer
variable is known as initialization.
Method-1:
intx;//declareadata variable
int*px;//declareapointer variable
Method-2:
intx;//declareadata variable
int*px=&x;//assigntheaddressofdatavariabletopointervariable
Method-3:
intx,*px=&x;//declaredatavariableandassignaddress
Dereferencing: Dereferencing apointer means getting the value that is stored in the
memorylocationpointedbythe pointer.Theoperator*isusedtodothis,andiscalled the dereferencing operator.
Anothernameforthedereferencingoperatoristhe indirectionoperator.
Example:
Example:int**p2
Considerthefollowingexample:
void main()
intx,*p1,**p2; x=100;
p1=&x; p2=&p1;
printf(“%d”,**p2);
RULESOFPOINTERSOPERATIONS:
Apointervariablecanbeassigned thevaluesofanotherpointervariable.
Apointervariablecanbepre-fixedorpost-fixedwithincrementordecrement operators.
Apointervariablecannotbemultipliedbya constant.
Twopointervariablescannotbeadded.
Avaluecannotbeassignedtoanarbitraryaddress(i.e., &x=10;isillegal)
PointersinArrays:Consider an1D-Array
x[5] = {100,101,102,103,104}
If we declare ptr as an integer pointer, then wecan make the pointer ptr topoint to the arrayx by the following
assignment:
ptr=x;this isequivalenttoptr=&x[0];
While working with 2D arrays, we must use two pointers such that one pointer points index “i”& another one
points index “j”.
charname[3][25]; //requires75bytes
char*name[3]={“Mysuru”,“Mandya”,“Hassan”};
Thefollowingstatementwouldprintoutallthethreenames:
for(i=0;i<=2;i++) printf(“%s\n”,name[i]);
This method will directly access the memory locations of actual parameters. So the changesmade on the formal
parameters effects the values of actual parameters.
Example:
*a=*b;
*b=temp;
Passing Structures to Functions (using Pointers):Functions are the basic building blocks of a C program. So,
it is natural for C language to support passing structures as parameters in functions.
return-typefunction-name(structstructname*var)
{
return expression;
Wecanaccessthemembersofstructureusing“arrow()operatorormembershipoperator”.
Example:
intid;
charname[20];
floatpercentage;
};
voidfunc(structstudent*record);
voidmain()
structstudentrecord={“01”,“Nithin”,”69”} func(&record);
voidfunc(structstudentrecord)
printf("Percentageis:%f\n",record->percentage);
DRAWBACKSOFPOINTERS:
Uninitializedpointersmight causesegmentationfault.
Pointersareslower thannormalvariables.
Ifpointersareupdatedwithincorrectvalues,itmightleadtomemory corruption.
Understandingandusingpointersinbestwaypossiblerequiresalotoftime.
PREPROCESSOR DIRECTIVES: C provides manyfeatures like structures, unions and pointers.
Another unique feature of the C language is the preprocessor.
Preprocessor directives are placed in the source program before the main line. Before the source code passes
through the compiler, it is examined by the preprocessor for any preprocessor directives.
“Preprocessor directives are lines included in a program that begin with the character #, which
makethemdifferent froma typical sourcecode text. Theyareinvoked bythe compiler to process some programs
before compilation.”
MacroSubstitutionDirective(#define)
FileInclusionDirective(#include)
CompilerControlDirectives(conditionaldirectives)
ANSICdirectives
Syntax:#defineidentifierstring
Example:#definePI 3.14
There is no space between the#and the worddefine. Also there should be atleast a single space between#define,
identifier and string. Also, there will be no semi-colon at the end of the statement.
Simplemacrosubstitution
Argumentedmacrosubstitution
Nestedmacrosubstitution
Simplemacrosubstitutions:aregenerallyused fordeclaringconstantsinaCprogram.Some valid examples for simple
macro substitution are:
Syntax: #defineidentifier(arg1,arg2….,argn)string
Careshouldbetakenthatthereisnospacebetweentheidentifierandtheleftparentheses.
In the program, the occurrence of a macro with arguments is known as a macro call. When a macro is called, the
preprocessor substitutes the string, replacing the formal parameters with actual parameters.
Exampleforargument macro:
ExampleforNestedMacros:
#defineSQUARE(x)(x*x)
#defineCUBE(x) (SQUARE(x)*x)
FILE INCLUSION DIRECTIVES: The external files containing functions or macro definitions can
be linked with our program so that there is no need to write the functions and macro definitions again.
#include“filename” or #include<filename>
Wecanuseeitheroftheabovestatementstolink ourprogramwithotherfiles.
Directive Purpose
#ifdef Testforamacrodefinition
#endif Specifiestheendof#if
#ifndef Testswhetheramacroisnotdefined
#if Testacompile-timecondition
#else Specifiesalternativewhen#iffails
Thesedirectivesallowtheprogrammertoincludetheportionsofthecodesbasedontheconditions.
ANSI PREPROCESSOR DIRECTIVES: The ANSI committee has added some more
preprocessor directives to the existing list. They are:
Directive Purpose
#elif Providesalternativetestfacility
#pragma Specifiescompilerinstructions
Thesyntax isasshownbelow:
#if expr1 Stmts;#elifexpr2 Stmts;#elifexpr3 Stmts; #endif
Syntax:
#pragmaname
#error<ERROR MESSAGE>
#endif
Example:#include<stdio.h>
#errorMARCONOTDEFINED
#else
printf(“macrofound”) #endif
}
EXAMPLEPROGRAMSTOBEPREPAREDFROMTHISMODULE:
#include<stdio.h>struct employee
inteid;
};
voidmain()
printf("EnterthenumberofEmployees\n"); scanf("%d",&n);
for(i=0;i<n;i++)
for(i=0;i<n;i++)
If(key== e[i].name)
printf("%d",e[i].eid);
printf("%s",e[i].name);
printf("%f",e[i].salary);
else
{
printf(“Nosuchemployeefound\n”);
}
scanf("%f",&a[i]);
ptr=a;
for(i=0;i<n; i++)
sum=sum+*ptr; ptr++;
mean=sum/n; ptr=a;
for(i=0;i<n; i++)
sumstd=sumstd+pow((*ptr-mean),2); ptr++;