0% found this document useful (0 votes)
3 views

C Language Reading Notes

The document provides an introduction to computers and C programming, detailing the evolution of computer generations from manual counting to artificial intelligence. It categorizes computers by size, such as supercomputers, mainframes, and microcomputers, and explains the architecture of computers, including the CPU, memory, and input/output devices. Additionally, it covers software basics, C programming structure, tokens, keywords, constants, and variables in C.

Uploaded by

vinita sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C Language Reading Notes

The document provides an introduction to computers and C programming, detailing the evolution of computer generations from manual counting to artificial intelligence. It categorizes computers by size, such as supercomputers, mainframes, and microcomputers, and explains the architecture of computers, including the CPU, memory, and input/output devices. Additionally, it covers software basics, C programming structure, tokens, keywords, constants, and variables in C.

Uploaded by

vinita sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 120

Module–1:Introductiontocomputers&c-programming

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.

GENERATIONSOFCOMPUTER:Therearesixgenerationsofcomputersystemare present as follows:

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

A.C.needed. Supporthigh-levellanguagesuchas C, C++andJava.

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.

TYPES OF COMPUTERS:Apart frombeingclassified bygenerations, computerscanalso be categorized


by their size:

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.

MINICOMPUTERS: Minicomputers or midrange computers can be considered as downsized mainframes since


they have essential featuresof mainframes. Minicomputers can serve hundreds of users and are small enough to
partially occupy a room. But they are not affordable enough to be used in the home.Minicomputers are used in
smaller organizations or a department of a large one.

MICROCOMPUTERS: The microcomputer or personal computers(PC) is a late entrant to the computer


family.This was introduced by Apple and later endorsed by IBM, this computer is a single-user machine
powered by a single chip microprocessor. They are used both in the standalone mode (at home) and in network
(in office). They are used both in the standalone mode (at home) and in network (in office). All PCs are
multimedia ready. They can handle images, audio and video files.

SMARTPHONESANDEMBEDDEDCOMPUTERS:Asmartphone isageneralpurpose computer that is also


capable of making phone calls.It also supports gigabytes of main memorybut doesn‟t haveaharddisk for
secondarystorage. Thisrequirement is met byflash memory.Smartphones today run a well-developed operating
system (Android or iOS) and can run awiderangeof applications.Applications arewrittenin ahigh-
levellanguagelike
Objective C for the iPhone and Java for Android phones. Embedded devices is small computer like system that is
part of a larger system which consists of CPU, non-volatile memory, and input and output facilities.we use such
devices in cars, washing machine, MP3 players and cameras.

BITS,BYTESANDWORDS:Ineverydaylife,weusedecimalsystemforcomputing where digit can have ten


values.A computer understands only two states:

Adigit that canhaveonlytwo statesorvalues iscalledas binarydigit, whichisabbreviatedas “bit”.All binary numbers
are represented by combining these 0s and 1s.

Example:Thenumber 13isrepresentedas1101inthebinarysystem.

Thename“byte”wascoinedtorepresent eight bits.Thebyteisthestandardunit ofmeasurement of computer memory,


data storage and transmission speed.

Asimilar relationship exists for bits also. So the speed ofnetwork expressed as 1Mbps(megabits per second) is
same as 1000Kbps.

Eventhoughcomputermemoryisrepresented inbytes,theCPUhandlesmemorydata inlarger units, called “words”,


whereaword isusuallyaneven multipleofbytes(two bytes, four bytes etc.,). Whenwereferto acomputeras32-bit
(4bytes)machine, we meanthesizeofthesizeof its word is 32 bits.

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.

ControlUnit (CU) -doesnot performanycomputationaltasks.Usingsignals,the CU controls the way the data is


moved between moved between the various components of the computer.

Special-purposeregisters-CPUusesafewhigh-speed“registers”,formofmemory to store the current instruction and


its data.

PRIMARYMEMORY:Memoryisoneoftheessentialresourceusedbythecomputer and its users. We categorize


memory into two types:

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.

ParallelPort:ItiscommonlyusedbyprintersiftheyarenotusingtheUSBportand comes with 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.

HighDefinitionMediaInterface:Thisisnowtheindustrystandardfortransferring audio and video data between


computers and HDTVs, projectors and home theatres.

COMPUTERS IN A NETWORK:Most organisations, large or small no longer have standalone


systems. Today, computers cooperate with each other by being connected to a network. The computer (node)
that offers these services would need to be more powerful thanthe computer it serves. That‟s how “servers”
came to existence as the central node in the network.

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.

Ringtopologyusesclosed loopwithout usingahub.Forunidirectionalrings, failureof one node causes the network to


shut down.

Meshtopologyusesnodesconnectedtoeachother,offeringachoiceofmultipleroutes for datato travel. When node


breaks down, the packet simplychanges its route. This is the most expensive of the topologies and found mainly
in corporate networks.

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

MetropolitanAreaNetwork(MAN)-ThistypeissandwichedbetweenaLANand WAN.A MAN is employed for


interconnecting in the same city.

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.

Connectingcomputersinanetworkisrequireadditionaldevicesthatarenotpartofthe computer‟s configuration.Some


of the devices are:

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.

Switch-containsatableofMACaddressesoftheconnecteddevices.Aswitchis efficient and is able to maintain the


speed of the network.

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

Router -connects twosimilarordissimilarnetworks whichmaybeseparatedbylong distances. It is part of both


networks and thus has two addresses.
SOFTWARE BASICS: Software is a collection of code that drives the computer to perform related task.
Comprises one or more programs supported by libraries & configuration files. Programs in software use
languages like C, C++, java etc.

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

KeywordsinCarealwaysinlowercase.ANSICsupports32keywordswhichare listed below:


Identifiers - refer to the names of variables,functions and arrays. These are user-definednamesandconsistof
sequenceoflettersanddigits,withaletterasafirst
character.Bothuppercaseandlowercaseletterscanbeused,althoughlowercase letters are generally used. The
underscore character is also permitted in identifiers. There certain rules while writing identifiers. They are as
follows:

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;

The“type”intheabovesyntaxrepresentsthedatatype.The“variable-name”isthe identifier. There are certain rules that


must be followed while writing the variable name.

RulesforVariablesName–

Avariablenamemustalwaysstart withanalphabet (letter)oranunderscore(_ ).

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;

Thevalue weassigntothe variable dependsonthedatatype ofthevariable.

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

PrimitiveorFundamentaldatatypes - Theprimitivedatatypes in ANSI Careas shownin the below diagram:


User-Defined data types - ANSI C allows the users to define identifiers as their own data types, based on the
already existing primitive or fundamental data types. This concept is known as “type definition” and the data
types thus created are known as user-defined data types.

Wecancreateuser-defineddatatypesintwoways:

Byusingthe “typedef”keyword

typedefintrollno; rollno r1, r2;

Byusing the “enum”keyword

enumidentifier{value1,value2…valuen}; enum days{sun,mon,….sat}

Deriveddatatypes- Thedatatypeswhicharecreatedusingthealreadyexistingprimitiveor fundamentaltypes are


knownas derived data types. Examples ofderived datatypes in C are: Arrays, Functions, Structures, Unions &
Pointers.

DefiningConstantsinC:Asthenamesuggeststhenameconstantsisgiventosuchvariablesor values
inCprogramming language whichcannot be modified once theyare defined.

There can be any types of constantslikeinteger,float,octal,hexadecimal,characterconstants etc. In C program we


can define constants in two ways as shown below:

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.

Example:#definePI 3.14#defineCLASS_SIZE 62#definecharVal„G‟

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.

Operators&Expressions:Anoperator isasymbolthat tellsacomputerto performcertain mathematical or


logical operations. Operators are used in programs to manipulate data and variables. Generally the usage of an
operator is as shown below:

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

DifferentTypesofOperators:InC,basedonthe functionality,operatorsareclassified into 8 categories. They


are:

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.

The generalsyntaxofsizeofoperatorisas shownbelow:

sizeof(operand);

Theoperand can beeither avalueorvariableordatatypeoranexpression.

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.

'C'programming providestwo typesoftypecastingoperations:

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;

Examples: x= (int)7.5a=(int)21.3/(int)4.5b= (double)sum/ny= (int)(a+b) z = (int)a + b


Typecasting orconversionhierarchy:

Mathematicalfunctions:
ExampleProgramstobepreparedfromthismodule:

CProgramto computearea ofa circle

#include<stdio.h>

voidmain()

floatradius,area;

printf("EntertheradiusofCircle:\n"); scanf("%d", &radius);

area = 3.14 * radius * radius; printf("AreaofCircle:%f",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);

FormattedInput-OutputFunctions:InCprogramminglanguagetheoutputisprinted using printf()


statement.

Therearetwosimpleformsofprintf() statement:

That hasaliteralstring, asequenceofcharacterswithinquotationmarks.


Syntax:printf(“string”);

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……)

Thecontrolstring specifiesthetypeofvaluetoreadfromthekeyboardandtheampersand symbol & is an operator to


specify the address the variable(s).

Example: scanf(“%d%f%d”,&a,&b,&c); scanf(“%c”,&h);

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.

Thesyntaxandflowchart ofifstatementisasillustrated below:

Example:Programto determinewhether apersoniseligibletovoteusingif.


#include<stdio.h>void main()

intage;

printf(“Entertheage:”); scanf(“%d”,&age); if(age>=18)

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.

Thesyntaxandflowchart ofif-else statementisasillustratedbelow:

Example:Programtodeterminewhether apersoniseligibletovote usingif-else statement.

#include<stdio.h>void main()

{
intage;

printf("Entertheage"); scanf("%d",&age); if(age>=18)

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.

The syntax and flow chart of nested if-else statement is as illustrated

below:

Example:ProgramtofindthelargestofthreenumbersusingNestedifelsestatement
#include<stdio.h>

void main()

inta,b,c;

printf("Enterthevaluesofa,bandc\n"); scanf("%d %d %d",&a,&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;

Disadvantage: difficulttounderstandandmodifywhenproblemisbig,whichcanbe overcome by using switch


Statement.

Example: Programto print thegradeobtained bythe student basedonthegiventableusingelse- if ladder.

#include<stdio.h>void main()

intmarks;

printf("Enterthemarks\n"); scanf("%d",&marks); if(marks>=0&&marks<=39) printf("Grade F\n");

elseif(marks>=40&&marks<=49) printf("Grade E\n");


elseif(marks>=50&&marks<=59) printf("Grade D\n");

elseif(marks>=60&&marks<=69) printf(" Grade C\n");

elseif(marks>=70&&marks<=79) printf("Grade B\n");

elseif(marks>=80&&marks<=89) printf("Grade A\n");

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.

Everycaselabelcontainsaconstantvaluethatismatchedagainstthevalue,whichis specified in the switch expression.

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()

floata,b,res; char op;

printf("EnteranExpression\n"); scanf("%g %c %g",&a,&op,&b); switch(op)

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;

UNCONDITIONAL BRANCHING STATEMENTS:The unconditional branching statements


transfer the control from one statement to another statement in the program without any conditions.

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;

Ifafunction isreturning avalue,then

returnvalue;

Example:

intsumDigits()

intsum=0; int digit;

for(digit=0;digit<=9;digit++)

sum=sum+digit;

returnsum; //Returningvalue&control

CONDITIONAL BRANCHING STATEMENTS:The statement which is used to repeat a set of


statements repeatedly for a given number of times or until a given condition is satisfied is called as looping
statements. The set or block ofstatements used for looping is called loop.

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.

Thesyntax andflowchartofWhile loopisasillustratedbelow:

Example:Programtofind thesumofnnaturalnumbersusing whileloop

#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);

Do-While Loop/Statemen(Exit Controlled Loop/Post-test):It is an exit controlled loop. It is also


known as posttest or bottom test looping statement.

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:

for(initialization; testcondition ;increment/decrement)

bodyoftheloop;

Thefirstexpressioncontainsanyinitializationstatements,thesecondcontainsthelimit-test expression, and the third


contains the updating expression.

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);

Nestedfor-loop:Nestedloopsconsistofanouterloop withoneor moreinner loops.

for(i=1;i<=100;i++)

{
for(j=1;j<=50;j++)

Theaboveloopwillrun for100*50 iterations.

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

#include<stdio.h> int main()

introws,cal=1,space,i,j;

printf("Enter number of rows: "); //enternumberofrowsforgeneratingthepascal triangle


scanf("%d",&rows);

for(i=0;i<rows;i++) //outerloopfordisplayingrows

for(space=1; space <= rows-i; space++) //space printf("");


for(j=0;j<=i; j++) //innerloopfordisplayingthepascaltriangleofnumbers

if (j==0 || i==0)//eitherouterloopvalueorinner-loopvalueis"0" itprints1 cal = 1;

else

cal=cal*(i-j+1)/j; //calculatethecoefficient
printf("%d",cal);

printf("\n");

return 0;

Computing binomial-coefficient:binomial coefficient is the number of ways of picking unordered


outcomes from possibilities, also known as a combination or combinatorial number.

CProgramtoprint binomial-coefficients

#include<stdio.h> #define MAX 10 void main()

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

bi_nom=bi_nom*(n-a+1)/a; print(“%d”, bi_nom);


}

a=a+1;

printf(“\n”); n=n+1;

while(n<=MAX);

EXAMPLEPROGRAMSTOBEPREPAREDFROMTHISMODULE:

CProgramto computetherootsofaquadraticequationbyacceptingthecoefficients. Print appropriate messages.

#include<stdio.h> #include<math.h>void main( )

floata,b,c,disc,root1,root2,real,imag; printf("Enter a,b,c values \n"); scanf("%f%f%f",&a,&b,&c);

disc=(b*b)-(4*a*c);

if((a==0)&&(b==0))

printf("Invalidco-efficients\n");

elseif(a==0)

printf("Linearequation\n"); root1=-c/b; printf("Root=%f\n",root1);

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);

printf("Root1=%f+i%f\n”,real,imag); printf ("Root2=%f - i %f \n”, real, imag);

Cprogramto findthereverseofapositiveintegerand checkforpalindromeornot.

#include<stdio.h>void main()

longinttemp,rev=0,i,num,remainder; printf("Enter the number \n"); scanf("%ld",&num);

temp=num; while(num!=0)

remainder=num%10; num=num/10; rev=rev*10+remainder;

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.

#include<stdio.h> #include<string.h>void main()

charname[25]; int units;


floatcharges=0.0;

printf("EnterCustomerNameandNumberofUnits:\n"); scanf("%s %d",name,&units);

if(units<=0)

printf("InvalidUnits,Pleaseentervalidunits\n"); return;

elseif(units>=0&&units<=200) charges= 100+ 0.80* units;

else if(units>201 && units<=300) charges=100+160+0.90*(units-200); else if(units>300)

charges= 100 + 250+1.0 * (units-300); printf("CustomerName=%s\n",name); if(charges>400)

charges=charges + 0.15*charges; printf("TotalCharges=%f\n",charges);

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.

ONE-DIMENSIONAL ARRAYS(1-D Array):For maintaining a list of items in C, we


candeclareanarraywithasingle subscript (index). Sucharrayswithonlyasinglesubscript are known as “one
dimensional arrays”.

Commonusesofonedimensionalarraysare:

Tomaintainalistofnumbers.

Tomaintainthelistofmarks.

Tomaintainalistofstudentnamesetc.

One-dimensionalArrayDeclaration:ForusingarraysinCprograms,justlikeweare declaring variables before using


them, we should declare arrays before using them.

Syntax:for declaringa1-DArrayisshownbelow:

typearrayName[Size];
Example:

inta[10];

Intheaboveexample‟a’isanintegerarray,whichcanhold10integervalues.

One-dimensionalArrayInitialization:Initializationmeansassigningvalues.Toassign values to the elements in the


array.

Generally,therearetwotypesofinitializinganarray:

StaticInitialization(atcompiletime).

DynamicInitialization(atruntime).

Instatic initialization, theelementsofanarrayareassigned valueswhentheprogramis compiled.

SyntaxforstaticInitialization:

typearrayName[size]={value1,value2,…valueN}; Examples:

inta[10] = {1,2,3,4,5,6,7,8,9,10};

inta[5]; a[2] =10;

inta[10] = {1,2,3,4,5}

Indynamic initialization, thevaluesareassignedtotheelementsofthearrayduringthe execution of the program.

Example:inta[10],i; for(i = 0; i < 10; i++)

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()

inti,n,Sum=0,num[100]; float Average;

printf("EnterHowmanyNumberyouwant?\n"); scanf("%d",&n);

printf("Entertheelementsonebyone\n"); for(i=0;i<n;i++)

scanf("%d",&num[i]); Sum = Sum + num[i];

Average=Sum/n;

printf("Sum of the Numbers = %d", Sum); printf("Averageofthe%dNumbers=%.2f",Average);

TWO-DIMENSIONAL ARRAYS(2-D Array): A two dimensional array is used to storea table of


values which has rows and columns. An array that has two subscripts (index), for example: a[i][j] is known as a
two dimensional.

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.

Two-dimensionalArrayInitialization:Initializationmeansassigningvalues.Toassign values to the elements in the


array.

Generally,therearetwotypesofinitializinganarray:

StaticInitialization(atcompiletime).

DynamicInitialization(atruntime).

Instaticinitialization,theelementsofanarrayareassignedvalueswhentheprogramis compiled.

SyntaxforstaticInitialization:

typearrayName[row][columns]={value1,value2,…valueN}; arrayName[row] [coumns] = value;


Examples: a[0] [0]=1; inta[3][3]={1,1,1,2,2,2,3,3,3};

Thememoryrepresentationofthetwodimensionalarraywillbe asshown below:


Indynamic initialization, thevaluesareassignedtotheelementsofthearrayduringthe execution of the program.

Example:inta[3][3],i,j;

for(i=0;i<3;i++)

for(j=0;j<3;j++)

scanf(“%d”,a[i][j]);

ExampleProgramon Two-dimensionalArray:CProgramtofind Transposeofa matrix

#include<stdio.h> void main()

inta[10][10],t[10][10],m,n,i, j;

printf("Enterrowsandcolumnsofmatrix:"); scanf("%d %d", &r, &c);

printf("\nEnterelementsofmatrix:\n"); for(i=0; i<m; i++)

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];

printf("\nTransposeofMatrix:\n"); for(i=0; i<m; i++)

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)

foreachiteminthelist if key == value

return successful

else

return unsuccessful

endif end for

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

Comparing themiddlemostitem of the collection.If amatch occurs,then theindex of item is returned.

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:

#include<stdio.h> #include<stdlib.h>int main()

int a[50],n,i,key,low,mid,high; printf("enterthenumberofelements\n"); scanf("%d",&n);

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.

There aretwomethods ofsorting:

1]BubbleSort. 2]Selection Sort.

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(i=1;i<n;i++) //forloopfornumber ofpasses

{
for(j=0;j<n-i;j++) //forloopfornumber ofcomparisons

if(a[j]>a[j+1])//Comparison

temp=a[j]; //Swapusingtemp a[j]=a[j+1];

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

for(inti=0; i<n-1 ; i++)//reducesthecomparisonsizebyoneineachiteration.


{

minimum=i;//assumingthefirstelementtobetheminimum.

for(intj=i+1;j<n; j++) //givesthe effectivesize ofthe unsortedarray

if(A[ j ] < A[ minimum ]){ //findstheminimumelement minimum = j ;

swap( A[minimum], A[ i]);//puttingminimumelementonitsproper position.

CProgramtoperformSelection Sort:

#include<stdio.h> void main()

inta[100],n,i, j,minimum,temp;

printf("Enternumberofelements\n"); scanf("%d", &n);

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];

a[i] = a[minimum]; a[minimum]=temp;

printf("Sortedlistinascendingorder:\n");

for(i=0;i <n;i++)

printf("%d\n",a[i]);

STRINGS:Astring isasequenceofcharactersterminatedwithanullcharacter \0.Agroupof characters enclosed in


double quotes is known as a string constant.

Someoftheexamplesofstringconstantsare: 1)“hai”

“helloworld”

“MynameisNITHIN”

InCprogramming,thereisno predefineddatatypetodeclareandusestrings.So,weuse character arrays to declare


strings in C programs.

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.

Characterarrayscanalsobeinitializedwhentheyaredeclared.Someoftheexamplesfor initializing the string are as


shown below:

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

Reading&WritingStrings: Therearetwowaysread&writethe strings


Formattedinput/output–scanf&printf

Unformattedinput/output–gets&puts

Syntaxforformattedinput/output:

Read–char str[10];

scanf(“%s”,str);

Print–printf(“Thestring is%s”,str);

Syntaxforunformatted input/output:

Read –char str[10];

gets(str); //gets(array_name);

Print – printf(“The string is:”); puts(str);//puts(array_name);

ExampleC programtoRead&PrintStrings:

/*Usingscanf&printf*/

#include<stdio.h> void main()

char name[20]; printf("Entername:"); scanf("%s", name);


printf("Yournameis%s.",name);

/*Usinggets&puts*/ #include <stdio.h>void main()

char name[20]; printf("Entername:"); gets(name); printf("Name: "); puts(name);

STRING-MANIPULATION FUNCTIONS(Built-in String Functions): C provides


predefined functions for performing all operations or manipulations on strings. Most of these predefined
functions are available in string.h header file. The list of predefined functions isgiven below:

String-concatenate (strcat): Thestrcat predefined function is used to concatenate/join two strings


together. The syntax of the strcat function is shown below:

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);

The functionreturnsthelengthofthe stringwhichwillbethenumberofcharactersinthestring excluding the „\0‟


character.

Example:

String-compare(strcmp):Thestrcmp predefinedfunctionisusedtocomparetwo strings. The syntax of


strcmp function is as shown below:

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);

Thestring instring2 iscopied intostring1andtheresult willbestoredinstring1 Example:


String-reverse (strrev): Thestrrev function is used to reverse a given string. We can use this predefined
function to check whether a given string is a palindrome or not. The syntax for using the strrev function is as
shown below:

strrev(string);
thestrrev functionreversesthegivenstringandreturnsit back.Thecontentofthestringalso changes.

Example:

EXAMPLEPROGRAMSTOBEPREPAREDFROMTHISMODULE:

CprogramtoprintString LengthwithoutBuilt-infunction

#include<stdio.h> #include<string.h>intmy_strlen(char[]); void main()

intlen;

char str1[26]]; printf("EnterString1:"); scanf("%s",str1); len=my_strlen(str1);

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>

intmy_strcmp(char[],char[]); void main()

intcomp;

char str1[26], char str2[26]; printf("Enter String1:"); scanf("%s",str1); printf("Enter String2:");


scanf("%s",str2); comp=my_strcmp(str1,str2); if(comp==0)

printf("%sisequalto%s\n",str1,str2); else if(comp>0)

printf("%s is greater than %s\n",str1,str2); elseprintf("%sislessthan%s\n",str1,str2); int my_strcmp(char


str1[],char str2[])

int i=0; while(str1[i]==str2[i])

if(str1[i]=='\0') break;
i++;

returnstr1[i]-str2[i];

Cprogramtoconcate two String’swithoutBuilt-infunction

#include<stdio.h> #include<string.h>

voidmy_concat(char[],char[]); void main()

intcomp;

charstr1[26],charstr2[26]; printf("Enter String1:"); scanf("%s",str1); printf("Enter String2:");


scanf("%s",str2); my_concat(str1,str2);

voidmy_concat(charstr1[],charstr2[])

int i=0,j=0; while(str1[i]!='\0') i++;

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);

printf(“enterarrayelements\n”); for(i=0; i<n; i++)

scanf(“%d”,&a[i]);

for(i=0;i<n;i++)

sum=sum+a[i];

}printf(“sumis %d\n”,sum):

Programtofindlargest ofnelementsstoredin anarray

#include<stdio.h>void main()

inti,n,a[10],big;

printf(“enternumberofarrayelements\n”); scanf(“%d”,&n);

printf(“enterarrayelements\n”); for(i=0; i<n;i++)


{

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;

printf("Enterthesizeoffirstmatrix\n"); scanf("%d %d",&m,&n);

printf("Enterthesizeofsecondmatrix\n"); scanf("%d %d",&p,&q);

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.

Byusingfunctions,the lengthofthe source codedecreases.

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.

Thepredefinedfunctionsareavailableintheheaderfiles.So,theuserhastoincludethe respective header file to use the


predefined functions available in it.

Example:theprintf functionwhichisavailableinthe <stdio.h>headerfileisusedfor printing information.

Otherexamplesofpredefinedfunctionsare:scanf, strlen, strcat, sqrt,fabsetc.

Userdefined functions: Auserdefinedfunctionisa functionwhichisdeclaredanddefined by the user himself.


While writing programs, if there are no available library functions for performing a particular task, we write our
own function to perform that 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.

FUNCTIONDEFINITION:Thefunctiondefinitionspecifieshowthefunctionwillbe working i.e the logic of the


function will be specified in this step.

Syntax:offunctiondefinitionisshownbelow

return_typefunction_name(parameterslist)

localvariabledeclaration's;

---

return(expression);

Example:

intadd(inta,int b)

int res;res=a+b; returnres;

FUNCTIONCALLING:Afterdeclaringanddefiningthefunctions,wecanusethe functions in our program. For


using the functions, we must call the function by its name.

Syntax:offunctiondefinitionisshownbelow

function_name(parameterslist); Example: add(m,n);


Whenever the compiler comes across a function call, it takes the controlof execution to the
firststatementinthefunction‟sdefinition.Afterthecompletionoffunctioni.e.,wheneverthe compiler comes across the
return statement or the closing brace ofthe function‟s body, the control will return back to the next statement
after the function call.
CATEGORIES OF USER DEFINED FUNCTIONS: A function may or may not accept any
argument. It may or may not return any value. Based on these facts, there are four different aspects of function
calls.

functionwithoutargumentsandwithoutreturnvalue

functionwithoutargumentsandwithreturn value

functionwithargumentsand without return value

functionwitharguments andwithreturnvalue

Function without argumentsandwithoutreturnvalue:Inthistypeoffunctionsthereare no


parameters/argumentsinthe functiondefinitionand thefunctiondoesnotreturnanyvalue back to the calling function.

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);

Intheaboveexample, sumfunctionhastwoparameters/arguments.Thetaskofthisfunction is to print the sum without


using return value.

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)
{

int result; result=x+y; return result;

}
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);

PARAMETERS PASSING IN C FUNCTION:When a function gets executed in the program, the


execution control is transferred from calling-function to called function and executes function definition, and
finally comes back to the calling function.

Whentheexecutioncontrolistransferred fromcalling-functiontocalled-function it maycarry one or number ofdata


values. These data values are called as parameters.In C, there are two types of parameters and they are as
follows:

ActualParameters

FormalParameters

There are two methods to pass parameters from calling function to called function and they areas follows...

PassbyValue

PassbyReference

InC,therearetwotypes ofparameters andtheyareas follows:


Therearetwomethodstopassparametersfromcallingfunctiontocalledfunction:

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:

voidswap(inta,int b)//called function

int temp; temp=a;

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:

voidswap(int *a,int *b)//calledfunction

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

Themainpurposeofusingexternvariablesisthattheycanbeaccessedbetweentwo different files which are part of a


large program.

example: int i=1;---------externinti;

anormalglobalvariablecanbemadeexternaswellbyplacingthe„extern‟keywordbefore its declaration/definition in


any function/block.

“static” This storage class is used to declare static variables which are popularly used while writing programs in
C language.

Staticvariableshaveapropertyofpreservingtheirvalueevenaftertheyareoutoftheir scope! Hence, static variables


preserve the value of their last use in their scope.

example:staticinti=1;

Globalstatic variablescanbeaccessedanywhere intheprogram.Bydefault,theyare assigned the value 0 by the


compiler.

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

Whenwritingrecursivefunctions,propercaremustbetakenthattherecursivecallsreturna value back at some point.


Otherwise, the function calls itself infinite number oftimes.
Example:

Intheaboveexample,func1iscallingitselfinthelastlineofitsdefinition.

FACTORIALOFANUMBER–Factorialofnisthe productofallpositivedescending integers. Factorial of n is


denoted by n!

Example:5!= 5*4*3*2*1 =120

RecursiveFunction:

5!=5*4!// n*Fact(n-1)

4!=4*3!

3!=3*2!

2!=2*1!

1!=1*0!

0!=1 //StopCondition

Programto find factorialofgiven numberusing recursion:

#include<stdio.h>

intfind_factorial(int); void main()

intnum,fact;

printf("\nEnteranyintegernumber:"); scanf("%d",&num);
fact=find_factorial(num);

printf("\nfactorialof%dis:%d",num,fact);

//recursivefunctiondefinition int find_factorial(int n)

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

Example: 0,1,1,2, 3,5,8, etc.

Thefirsttwonumbersoffibonacciseriesare0and1.

RecursiveFunction:Thereare3cases infibonacciseries

ifn=1 onlyonedigittobeprintedi.e“0”.

ifn=2 onlytwodigittobeprintedi.e“1”.

ifn >2lasttwo digitstobeadded&printed so “fib(n-1)+fib(n-2)”

Programto findFibonacciSeriesusing recursion:

#include<stdio.h>int fib(int);

voidmain()

intn,i=0,c;

printf(“enterNvalue\n”); scanf("%d", &n);

printf("Fibonacciseriestermsare:\n"); for (c = 1; c <= n; 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:

ProgramtoConvert Binary numberto Decimal:

#include<stdio.h> int convert(int); void main()

intdec,bin;

printf("EnteraBinarynumber\n"); scanf("%d", &bin);

dec= convert(bin);

printf("TheDecimalEquivalentof%dis%d\n",bin,dec);

intconvert(intbin)

if(bin== 0)

return 0;

else

return(bin %10 +2* convert(bin/10));

Programto checkwhetherthegiven numberisprimeornot:

#include<stdio.h>int isPrime(int); void main()

intres,num;

printf("Enterthenumber:"); scanf("%d",&num); res=isPrime(num); if(res==0)

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.

SyntaxofStructure: structuresmust befirst definedfirst fortheir lateruse.Thesyntaxfor defining a structure is as


shown below:

structstructure_name

datatypevar1; datatypevar2;

-------

};

Thekeyword struct declaresastructure.The structure_namerepresentsthenameofthe structure. The structure


definition is always terminated with a semicolon.

Example:

structstudent

introllno;

charname[26]; int marks;

};

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:

structstructurenamevar1,var2, …., varN


Example:

structstudents1,s2,s3;

Wecanalsocombinethestructuredefinitionandthedeclarationofstructurevariablesintoa single line such structures


are called “Tagged Structures” as shown below:

structstudent

introllno;

charname[26]; int marks;

} s1,s2,s3;

Wecanusethekeywordtypedeftodefineastructureasfollows: typedef struct

introllno;

charname[26]; int marks;

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

Thelinkbetweenamemberandavariableisestablishedusingthememberoperator„.‟which is also known as dot


operator or period operator.

Syntaxforaccessingastructure member:

structure-varaible.membername

Example:

s1.name s1.rollno
StructureInitialization: Thevaluescanbeinitializedintwoways

static initialization

dynamic initialization

Exampleforstaticinitialization:

structstudent

introllno;

charname[26]; int marks;

};

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;

charname[26]; int marks;

};

structstudents[100];

Intheaboveexample,wearedeclaringanarray„s‟with100elementsofthetype studentwhich is a structure.


NESTEDSTRUCTURES:InC,structurescanbenested.Astructurecanbedefined within in another
structure.

Exampleofnestedstructure:

structstudent

structname

charfname[10]; charlname[10];

};

introllno; int marks;

};

Inthe above example, student is the outer structure and the inner structure nameconsists oftwo members: fname
and lname.

The members of the inner structure can be accessed as shown below:


outer_structure_variable.inner_structure_variable.member_name; Example: s1.name.fname;

PASSINGSTRUCTURESTOFUNCTIONS: Functionsarethebasicbuildingblocks ofa C program.


So, it is natural for C language to support passing structures as parameters in functions.

WecanpasstheCstructurestofunctionsin3 ways:

Passingeach individual itemofthestructureasafunctionargument.

Passingthewholestructureasavalue.

Passing theaddressofthe structure(passbyreference).

Syntaxforpassingthestructurevariableasaparameterisshown below:

return-typefunction-name(structstructnamevar)

{
return expression;

PASSINGSTRUCTURETOFUNCTIONINCBYVALUE :thewholestructureis passed to another function by


value. It means the whole structure is passed to another function with all members and their values. So, this
structure can be accessed fromcalled function.

Exampleforpassby value:

#include <stdio.h> #include<string.h> struct student

intid;

char name[20]; floatpercentage;

};

voidfunc(structstudentrecord); void main()

structstudentrecord={“01”,“Nithin”,”69”} func(record);

voidfunc(structstudentrecord)

printf(" Id is: %d \n", record.id); printf("Nameis:%s\n",record.name);

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

#include <stdio.h> #include<string.h> struct student

intid;

char name[20]; floatpercentage;

};

voidfunc(structstudent*record); void main()

structstudentrecord={“01”,“Nithin”,”69”} func(&record);

voidfunc(structstudentrecord)

printf(" Id is: %d \n", record->id); printf("Nameis:%s\n",record->name);

printf("Percentageis:%f\n",record->percentage);

Cprogram to read,write& computeaveragemarksofNstudentsusingstrurcture

#include<stdio.h>struct student

{
introll;

charname[50]; int marks;

};

voidmain()

structstudents[10]; int i,n,sum=0;

floataverage=0.0;

printf("Enterthenumberofstudents\n"); scanf("%d",&n);

for(i=0;i<n;i++)

printf("Entertherollnumber:"); scanf("%d",&s[i].roll); printf("Enter the Name:"); scanf("%s",s[i].name);


printf("Enter Total Marks:"); scanf("%d",&s[i].marks);

for(i=0;i<n;i++)

sum=sum+s[i].marks;

average=(float)sum/n;

printf("ClassAverageis%g\n",average); printf("Record details of students:\n"); for(i=0;i<n;i++)


{

printf("%4d",s[i].roll);

printf("%15s",s[i].name);

printf("%15d",s[i].marks); if(s[i].marks>=average) printf("\tYes");

else printf("\tNo");

printf("\n");

POINTERS:Apointer isaderived datatype in C. It is built fromoneofthe fundamentaldata types available in


C. Pointers contain memory addresses as their values. Since these memory addresses are the locations in the
computer memory where program instructions and data are stored.

pointerscanbeusedtoaccessandmanipulatedatastoredinthememory.

AdvantagesofPointers:PointersareusedfrequentlyinC,astheyofferanumberof benefits to the programmers. They


include the following:

Pointersaremoreefficientinhandlingarraysanddatatables.

PointersallowCto supportdynamicmemorymanagement.

Pointersprovideanefficient wayformanipulatingdynamicdatastructuressuchas structures, linked lists, queues,


stacks and trees.

Pointersincreasetheexecutionspeed and thusreducetheprogramexecutiontime.

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:

Theabovestatement intvarcreatesalocationinthe memoryto hold integervalue.That location willhaveanaddress


forexampleassume it is5000. Thestatement var=200storesthevalue200 at the location whose address is 5000. So,
in our example, varis the variable name, 200 is the value stored in var and 5000 is the address of the memory
location containing the variable var.

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

px=&x//copythe addressofdata variable topointervariable

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:

intquantity,*p,n; quantity=179; p=&quantity; n=*p;

CHAINOFPOINTERS(MULTIPLEINDIRECTIONS):It ispossibletomakea pointer to point


to another pointer, thus creating a chain of pointers.

Avariablethatisapointertoapointermustbedeclaredusingadditionalindirectionoperator symbols in front of the name


Here, the pointer variable p2 contains the address of the pointer variable p1, which points to the location that
contains the desired value.

Example:int**p2

Considerthefollowingexample:

void main()

intx,*p1,**p2; x=100;

p1=&x; p2=&p1;

printf(“%d”,**p2);

RULESOFPOINTERSOPERATIONS:

Apointervariablecanbeassigned the addressofanothervariable.

Apointervariablecanbeassigned thevaluesofanotherpointervariable.

Apointer variablecanbeinitialized withNULLorzero value.

Apointervariablecanbepre-fixedorpost-fixedwithincrementordecrement operators.

Aninteger valuemaybeadded or subtractedfromapointervariable.

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];

Wecanaccesseveryvalue ofxusingp++tomove fromoneelementtoanother

Theaddressofanelement iscalculatedusing its index andthescale factorofthedatatype address of x[n] = base


address+(n * scale factor of datatype)

Example: consider1000asbaseaddress&scale factorofint =2bytes x[3] = 1000+(3*2) = 1006.

While working with 2D arrays, we must use two pointers such that one pointer points index “i”& another one
points index “j”.

ARRAYS OF POINTERS:Oneofthe important usesofpointer is in handling ofatableof strings.


Consider thefollowing arrayofstrings:

charname[3][25]; //requires75bytes

Insteadofmakingeachrowa fixed number ofcharacters, wecanmake it apointer toastring of varying length.

char*name[3]={“Mysuru”,“Mandya”,“Hassan”};

Declaresnametobeanarrayofthreepointerstocharacters,whichrequiresonly21bytes, sufficient to hold all the


characters.

Thefollowingstatementwouldprintoutallthethreenames:

for(i=0;i<=2;i++) printf(“%s\n”,name[i]);

Thecharacterarrayswiththerowsofvaryinglengtharecalled“raggedarrays”andtheyare better handled by pointers.

POINTERS AS FUNCTION ARGUMENTS: When we pass the address of a variable as an


argument the receiving parameter should be pointers. This process of calling a function using pointers to pass the
addresses of variables is known as “Call by reference”.

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:

voidswap(int*a,int *b)//called function

int temp; temp=*a;

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

WecanpasstheCstructurestofunctionsusingpointersitsalsocalledas“Passingthe address of the structure (pass by


reference)”.

Syntaxforpassingaddressthestructure variable using pointerasaparameter:

return-typefunction-name(structstructname*var)

{
return expression;

Wecanaccessthemembersofstructureusing“arrow()operatorormembershipoperator”.

Example:

#include <stdio.h> #include<string.h>struct student

intid;

charname[20];

floatpercentage;

};

voidfunc(structstudent*record);

voidmain()

structstudentrecord={“01”,“Nithin”,”69”} func(&record);

voidfunc(structstudentrecord)

printf(" Id is: %d \n", record->id); printf("Nameis:%s\n",record->name);

printf("Percentageis:%f\n",record->percentage);

DRAWBACKSOFPOINTERS:

Uninitializedpointersmight causesegmentationfault.

Dynamicallyallocatedblockneedstobefreedexplicitly.Otherwise,itwouldleadto memory leak.

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

Thepreprocessordirectivesaredivided into fourcategories.Theyare:

MacroSubstitutionDirective(#define)

FileInclusionDirective(#include)

CompilerControlDirectives(conditionaldirectives)

ANSICdirectives

MACRO SUBSTITUTION DIRECTIVES: Macro substitution is a process where an identifier in


a program is replaced by a predefined string composed of one or more tokens.

Thepreprocessoraccomplishesthistaskunderthedirectionof #define statement.This statement, usually known as a


macro definition

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.

Therearedifferentformsofmacro substitution.The mostcommonare:

Simplemacrosubstitution

Argumentedmacrosubstitution

Nestedmacrosubstitution
Simplemacrosubstitutions:aregenerallyused fordeclaringconstantsinaCprogram.Some valid examples for simple
macro substitution are:

Exampleforsimple macro: #definePI3.14 #definesize 100


Argumented macro substitution: The preprocessor allows us to define more complex and
moreusefulformofsubstitutions. The Argumentedmacro substitutiontakesthefollowing form:

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:

#define CUBE(x) (x*x*x) //Macrodefinition volume = CUBE(side) //Macro Call volume =


side*side*side //Execution

NestedMacros: Wecanuseone macro insidethedefinitionofanother macro.Suchmacros are known as nested


macros.

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.

Thiscanbeachievedbyusingthe #includedirective.Thesyntaxforthisdirectiveisas shown below:

#include“filename” or #include<filename>

Wecanuseeitheroftheabovestatementstolink ourprogramwithotherfiles.

Ifthe filename isincludedindoublequotes,thefileissearchedinthelocaldirectory.If the filename is included in


angular brackets, then the file is searched in the standard directories.
COMPILER DIRECTIVES: The following are the compiler control directives used in c programming:

Directive Purpose

#ifdef Testforamacrodefinition

#endif Specifiestheendof#if

#ifndef Testswhetheramacroisnotdefined

#if Testacompile-timecondition

#else Specifiesalternativewhen#iffails

Thesedirectivesallowtheprogrammertoincludetheportionsofthecodesbasedontheconditions.

#ifdefand #endif directive:


#ifndef and #else directive: The #ifndef works exactly opposite tothat of #ifdef preprocessortests whether the
identifier has defined substitute text or not.

If identifierisdefinedthen #elseblockiscompiledandexecutedandthecompilerignores#if block.

ANSI PREPROCESSOR DIRECTIVES: The ANSI committee has added some more
preprocessor directives to the existing list. They are:

Directive Purpose

#elif Providesalternativetestfacility

#pragma Specifiescompilerinstructions

#error Stopscompilationwhenanerror occurs


#elif directive:”#elif directive”:enablesustoestablish an “if…else…if”sequencefor testing multiple conditions.

Thesyntax isasshownbelow:
#if expr1 Stmts;#elifexpr2 Stmts;#elifexpr3 Stmts; #endif

#pragmadirective: directiveisanimplementationorienteddirectivethatallowstheuserto specify various instructions


to be given to the compiler.

Syntax:

#pragmaname

Where name isthenameofthepragmawewant.Forexample,underMicrosoftC, #pragma loop_opt(on)causes loop


optimization to be performed.

“#errordirective”: isusedtodisplayuserdefined messageduringcompilationoftheprogram. Syntax: #if !


defined(identifer)

#error<ERROR MESSAGE>

#endif

Example:#include<stdio.h>

#define B1 void main(){ #if!defined(A)

#errorMARCONOTDEFINED

#else

printf(“macrofound”) #endif

}
EXAMPLEPROGRAMSTOBEPREPAREDFROMTHISMODULE:

Cprogramtoread,write&findtheemployeeinNemployeesusing structure based on Employee Name

#include<stdio.h>struct employee

inteid;

charename[26]; float salary;

};

voidmain()

structemployeee[100]; int i,n,key;

printf("EnterthenumberofEmployees\n"); scanf("%d",&n);

for(i=0;i<n;i++)

printf("Entertheemployeeid:"); scanf("%d",&e[i].eid); printf("Enter the Name:"); scanf("%s",e[i].ename);


printf("Enter Total Salary:"); scanf("%f",&e[i].salary);

printf(“entertheemployeenametosearch\n”); scanf(“%s”, key);

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”);
}

Cprogramusingpointerstocomputethesum,meanandstandard deviation of all elements stored in an array of n real


numbers.

#include<stdio.h> #include<math.h>void main()

floata[10],*ptr,mean,std,sum=0,sumstd=0; int n,i;

printf("Entertheno.ofelements\n"); scanf("%d", &n);

printf("Enterthearrayelements\n"); for(i=0; i<n; i++)

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++;

std=sqrt(sumstd/n); printf("Sum=%.3f\t",sum); printf("Mean=%.3f\t",mean); printf("StandardDeviation=


%.3f\t",std); printf("\n");

You might also like