C-PROGRAMMINGB_NOTES-1
C-PROGRAMMINGB_NOTES-1
MACHINE LEARNING
REGULATION R2021
IYEAR - II SEMESTER
CS3251–PROGRAMMINGINC
CS3251 PROGRAMMINGINC
COURSEOBJECTIVES:
• To understand the constructs of C Language.
• To develop C Programs using basic programming constructs
• To develop C programs using arrays and strings
• To develop modular applications in C using functions
• To develop applications in C using pointers and structures
• To do input/output and file handling in C
UNITI BASICSOFCPROGRAMMING
Introduction to programming paradigms–Applications of C Language –Structure of C program
- C programming: Data Types - Constants – Enumeration Constants - Keywords – Operators:
Precedence and Associativity - Expressions - Input/Output statements, Assignment statements –
Decision making statements - Switch statement - Looping statements – Preprocessor directives -
Compilation process
UNITIV STRUCTURESANDUNION
Structure - Nested structures – Pointer and Structures – Array of structures – Self referential
structures – Dynamic memory allocation - Singly linked list – typedef – Union - Storage classes
and Visibility.
TOTAL:45 PERIODS
TEXTBOOKS:
1. ReemaThareja,“ProgramminginC”,OxfordUniversityPress,SecondEdition,2016.
2. Kernighan,B.WandRitchie,D.M,“TheCProgramminglanguage”,SecondEdition,Pearson
Education,2015.
REFERENCES:
1. PaulDeitelandHarveyDeitel,“CHowtoProgramwithanIntroductiontoC++”,Eighthedition,
PearsonEducation,2018.
2. YashwantKanetkar,LetusC,17thEdition,BPBPublications,2020.
3. ByronS.Gottfried,“Schaum’sOutlineofTheoryandProblemsofProgrammingwithC”,
McGraw-HillEducation,1996.
4. PradipDey,ManasGhosh,“ComputerFundamentalsandProgramminginC”,SecondEdition,
OxfordUniversityPress,2013.
5. AnitaGoelandAjayMittal,“ComputerFundamentalsandProgramminginC”,1stEdition,
PearsonEducation,2013.
UNIT1
BASICSOFCPROGRAMMING
Introduction to programming paradigms – Applications of C Language - Structure of C program - C
programming: Data Types - Constants – Enumeration Constants - Keywords – Operators: Precedence and
Associativity - Expressions - Input/Output statements, Assignment statements – Decision making
statements - Switch statement - Looping statements – Preprocessor directives - Compilation process .
1. INTRODUCTIONTOPROGRAMMINGPARADIGMS:
C INTRODUCTION:
The programming language “C‟ was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories. Although C was initially developed for writing system software, today it has become such a
popular language that a variety of software programs are written using this language.
The greatest advantage of using C for programming is that it can be easily used on different types
of computers. Many other programming languages such as C++ and Java are also based on C which means
that you will be able to learn them easily in the future. Today, C is widely used with the UNIX operating
system.
PROGRAMMINGPARADIGMS:
Incomputing,aprogramisaspecificsetoforderedoperationforacomputertoperform.Theprocess of
developing and implementing various sets of instruction to enable a computer to perform a certain task is
called PROGRAMMING.
PROGRAMMINGPARADIGMSINCLUDE:
1. IMPERATIVEPROGRAMMINGPARADIGMS:
Command show how the computation takes place, step by step. Each step affects the global
state of the computation.
2. STRUCTUREDPROGRAMMINGPARADIGMS:
It is a kind of imperative programming where the control flow is defined by nested loops,
conditionals, and subroutines, rather than via gotos. Variables generally local to blocks.
3. OBJECTORIENTEDPROGRAMMING(OOP)PARADIGMS:
Itisaprogrammingparadigmsbasedontheconceptsofobjects,whichmaycontaindata,inthe form of
fields, often known as attributes, and code, in the form of procedures, often known as
methods.
4. DECLARATIVEPROGRAMMINGPARADIGMS:
The programmer states only what the results should look like , not how to obtain it. No loops,
no assignments, etc. Whatever engines that interprets this code is just supposed go gets the
desired information and can use whatever approach its wants.
5. FUNCTIONALPROGRAMMINGPARADIGMS:
Infunctionalprogramming,controlflowisexpressedbycombiningfunctionalcalls,ratherthan by
assigning values to variables.
6. PROCEDURALPROGRAMMINGPARADIGMS:
Thisparadigmsincludesimperativeprogrammingwithprocedurecalls.
7. EVENTDRIVENPROGRAMMINGPARADIGMS:
Inwhichtheflowoftheprogramisdeterminedbyeventssuchasuseraction(mouseclicks,key
presses), sensor output, or message from other program/threads. It is the dominant paradigms
used inGUIandother applicationsthat arecentredonperformingcertainaction inresponseto user
input.
8. FLOWDRIVENPROGRAMMINGPARADIGMS:
Programmingprocessescommunicatingwitheachotheroverpredefinedchannels.
9. LOGICPROGRAMMINGPARADIGMS:
Here programming is done by specifying a set of facts and rules. An engine infers the answer
to question.
10. CONSTRAINTSPROGRAMMINGPARADIGMS:
Anenginefindsthevaluethatmeettheconstraints.
One of the characteristics of a language is its support for particular programming
paradigms.Forexample:smalltalkshasdirectsupportforprogrammingintheobjectoriented way, so
it might called an object oriented language.
Very few language implement a paradigms 100%, when they do, they are “PURE”. It is
incredibly rare to have a “pure OOP language” or a “pure functional language”.
A lot of language will facilitate programming in one or more paradigms. If a language is
purposely designed to allow programming in many paradigms is called a “multi paradigms
language”.
APPLICATIONOFC:
1. OPERATINGSYSTEM
2. EMBEDDEDSYSTEM
3. GUI(GRAPHICALUSERINTERFACE)
4. NEWPROGRAMMINGPLATFORMS
5. GOOGLE
6. MOZILLAFIREBOXANDTHUNDERBIRD
7. MYSQL
8. COMPILERDESIGN
9. ASSEMBLERS
10. TEXTEDITORS
11. DRIVERS
12. NETWORK DEVICES
13. GAMING AND ANIMATION
FEATURESOFCPROGRAMMING/ADVANTAGES:
Cisarobustlanguagewithrichsetofbuiltinfunction.
Programswrittenincareefficientandfast.
C is highly portable, programs once written in c can be run on another machine with minor or no
modification.
C is basicallya collectionofc library functions, wecanalso createourownfunctionand add it to the c
library.
Ciseasilyextensible.
DISADVANTAGEOFC:
CdoesnotprovideOOP.
Thereis noconceptsofnamespaceinc.
Cdoesnotprovidesbindingorwrapping upofasingleunit.
Cdoesnotprovideconstructoranddestructor.
STRUCTUREOFC:
Documentationsection:
The documentationsection consists of a setof commentlines giving the nameof the
program, theauthor andother details, whichtheprogrammerwould liketouselater.
Definition section:The definition section defines all symbolic constants such usingthe#define
directive.
Globaldeclarationsection: Therearesomevariables that areusedinmorethan onefunction.
Suchvariablesarecalledglobalvariablesandaredeclaredintheglobaldeclarationsectionthat
isoutsideofallthefunctions.Thissectionalsodeclaresall the user-definedfunctions.
Main()functionsection: EveryCprogrammusthaveonemainfunctionsection.This section contains
two parts; declaration part and executable part.
Declarationpart:
Thedeclarationpartdeclaresallthevariablesusedintheexecutablepart.
Executablepart:
Thereisatleastonestatementintheexecutablepart.Thesetwopartsmustappearbetween
theopening and closing braces. Theprogramexecution begins attheopeningbrace and ends at the
closing brace. The closing brace of the main function is the logical end of the program.All
statements in the declaration and executable part end with a semicolon.
Subprogramsection:
If the program is a multi-function program then the subprogram section contains all the
user-definedfunctionsthatarecalledinthemain()function.User-definedfunctionsare
generallyplacedimmediatelyafterthemain()function,althoughtheymayappearinanyorder.
Allsection,exceptthemain()functionsectionmaybeabsentwhentheyarenot required.
CPROGRAMMING:DATA-TYPES
Adata-typeinC programmingisaset ofvalues andis determinedtoactonthose
values.Cprovidesvarioustypesofdata-typeswhichallowtheprogrammertoselectthe
appropriate typefor the variable to set its value.
The data-type in a programming language is the collection of data with values having
fixedmeaningaswellascharacteristics.Someofthemareinteger,floatingpoint,characteretc.
Usually, programming languages specify the range values for given data-type.
CDataTypesareused to:
• Identifythetypeofavariablewhenitdeclared.
• Identifythetypeofthereturnvalueofafunction.
• Identifythetypeofaparameterexpectedbyafunction.
ANSICprovidesthreetypesofdatatypes:
1. Primary(Built-in)DataTypes:void,int,char,doubleandfloat.
2. Derived DataTypes:Array,References,andPointers.
3. UserDefinedDataTypes:Structure,Union,andEnumeration.
PrimaryDataTypes:
EveryCcompilersupportsfiveprimarydatatypes:
void -As the name suggests it holds no value and is generally used for specifyingthe type of
function or what it returns. If the function has a void type, it means that the function will not
return any value.
int-Usedtodenoteanintegertype.
Char-Usedtodenoteacharactertype.
float,double-Usedtodenoteafloatingpoint
type.
int*,float*,char*-usedtodenoteapointertype.
DeclarationofPrimaryDataTypeswithvariablename:
Aftertakingsuitablevariable names, theyneedtobeassignedwithadatatype.Thisishowthe data types
are used along with variables:
Example:int
age;
charletter;
floatheight, width;
DerivedDataTypes
Csupportsthreederiveddatatypes:
DATATYPES DESCRIPTION
Arrays Arrays are sequences of data items having homogeneous
values. They have adjacent memory locations to store
values.
References Functionpointersallowreferencingfunctionswitha
particular signature.
UserDefinedDataTypes
Callowsthefeaturecalledtypedefinitionwhichallowsprogrammerstodefinetheirown identifier
that would represent an existing data type. There are three such types:
ExampleforDataTypesandVariableDeclarationsinC
#include <stdio.h> int main()
{
float 4 byte
doublelong 8byte
double 10 byte
ListofConstantsinC
Constant Example
TherearetwowaystodefineconstantinCprogramming.
1. constkeyword
2. #definepreprocessor
C constkeyword:
TheconstkeywordisusedtodefineconstantinCprogramming.
Example:
constfloatPI=3.14;
Now,thevalueofPIvariablecan'tbechanged. #include<stdio.h>
intmain()
{
constfloatPI=3.14;
printf("ThevalueofPIis:%f",PI);
return 0;
}
Output:
ThevalueofPIis:3.140000
Ifyoutryto changethevalueofPI,it willrendercompiletimeerror. #include<stdio.h>
intmain(){
const float PI=3.14; PI=4.5;
printf("ThevalueofPIis:%f",PI); return
0;
}
Output: CompileTimeError: Cannot modifyaconstobject.
C#definepreprocessor
The#definepreprocessordirectiveisusedtodefineconstantormicrosubstitution.Itcanuseany basic
data type.
Syntax:#definetokenvalue
Let'sseeanexampleof#definetodefineaconstant. #include
<stdio.h>
#definePI3.14
main()
{
printf("%f",PI);
}
Output:
3.140000
Backslashcharacterconstant:
C supports some character constants having a backslash in front of it. The lists of backslash
charactershaveaspecific meaningwhichisknowntothecompiler.Theyarealsotermedas“Escape Sequence”.
Example:
\tisusedtogive atab
\nisusedtogivenewline
Constants Meaning Constants Meaning
\a beepsound \n newline
\v verticaltab \\ backslash
\b backspace \r carriagereturn
\’ singlequote \0 null
\f formfeed \t horizontaltab
\” double quote
ENUMERATIONCONSTANTS:
An enum is a keyword, it is an user defined data type. All properties of integer are
appliedonEnumerationdatatypesosizeoftheenumeratordatatypeis2byte.Itwork like the
Integer. It is used for creating an user defined data type of integer. Using enum we can
create sequence of integer constant value.
Syntax:enumtagname{value1,value2,value3,….};
• Inabovesyntaxenumisakeyword.Itisauserdefineddatatype.
• Inabovesyntaxtagnameisourownvariable.tagnameisanyvariablename.
• value1,value2,value3,arecreatesetofenumvalues.
It is start with 0 (zero) by default and valueis incremented by 1 for the sequential
identifiersinthelist.Ifconstantonevalueisnotinitializedthenbydefaultsequencewillbestart from
zero and next to generated value should be previous constant value one.
Example:
enumweek{sun,mon,tue,wed,thu,fri,sat};enumweek today;
• Inabovecodefirstlineiscreateuserdefineddatatype calledweek.
Example:
#include<stdio.h>
#include<conio.h>e
num abc{x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf(“sum: %d”,a);
getch();
}
Output:
Sum:3
KEYWORDS:
Akeywordisareserved word.Youcannotuseit asavariablename, constant nameetc.Thereare only 32
reserved words (keywords) in C language.
Alistof32keywords inc languageisgivenbelow:
OPERATORS:
OperatorisaspecialsymbolthattellsthecompilertoperformspecificmathematicalorlogicalOperation.
ArithmeticOperators
RelationalOperators
LogicalOperators
BitwiseOperators
AssignmentOperators
TernaryorConditionalOperators
ArithmeticOperators:
Giventableshowsallthe ArithmeticoperatorsupportedbyCLanguage. LetssupposevariableA hold 8
and B hold 3.
Operator Example(intA=8,B=3) Result
A+B 11
A-B 5
A*B 24
A/B 2
% A%4 0
RelationalOperators:
Whichcanbeusedto checktheCondition, it alwaysreturntrueorfalse.Letssupposevariable hold 8 and
B hold 3.
LogicalOperator:
WhichcanbeusedtocombinemorethanoneCondition?.Supposeyouwanttocombinedtwo
conditionsA<BandB>C,thenyouneedtouseLogicalOperatorlike(A<B)&&(B>C).Here&&is Logical Operator.
TruthtableofLogical Operator
Assignmentoperators:
Whichcan beused toassignavalueto avariable.LetssupposevariableAhold8 andBhold3.
Post-decrement(variable--):
InPost-decrement first value ofvariable is used inthe expression(initialize into another variable)
and then decrement the value of variable.
Syntax:
variable--;
Example:
#include<stdio.h>
#include<conio.h>voi Output:
d main() Pre-decrementx::9
{ i::9
intx,i;i=10; Post-decrementx::10
i::9
x=--i;
printf(“Pre-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
i=10;
x=i--;
printf(“Post-decrement\n”);
printf(“x::%d”,x);
printf(“i::%d”,i);
}
TernaryOperator:
IfanyoperatorisusedonthreeoperandsorvariableisknownasTernaryOperator.Itcanbe represented
with ? : . It is also called as conditional operator
AdvantageofTernaryOperator
Using ?:reducethenumberoflinecodesandimprovetheperformanceofapplication.
Syntax:
Expression1?Expression2:Expression3;
In the above symbol expression-1 is condition and expression-2 and expression-3 will be either
value Or variable or statement or any mathematical expression. If condition will be true expression-2 will
be execute otherwise expression-3 will be executed.
ConditionalOperatorflowdiagram
Example:
findlargestnumberamong3numbersusingternaryoperator
#include<stdio.h>
voidmain()
{
int a,b,c,large; Output:
printf(“Enteranythreenumbers:”); scanf(“%d%d Enteranythreenumbers:126798 The
%d”,&a,&b,&c); largest number is 98
large=a>b?(a>c?a:c):(b>c?b:c);
printf(“Thelargestnumberis:%d”,large);
}
SpecialOperators:
Csupportssome specialoperators
Operator Description
sizeof() Returnsthesizeofanmemorylocation.
* Pointerto avariable.
Expressionevaluation
• Ifparenthesesarenested,theevaluationbeginswiththeinnermostsubexpression.
expressions.
• Theassociabilityruleisappliedwhentwoormoreoperatorsarehavingsameprecedenceinthesub
expression.
EXPRESSION:
Anexpressionisasequenceofoperatorsandoperandsthatspecifiescomputationofavalue.
SimpleExpressions&CompoundExpressions:
An expression that has only one operator is known as a simple expression. E.g: a+2
Anexpressionthatinvolvesmorethanoneoperatoriscalledacompoundexpression. E.g:
b=2+3*5.
IOSTATEMENT:
TheI/Ofunctionsareclassifiedintotwotypes:
FormattedFunctions
Unformattedfunctions
FORMATTEDINPUTFUNCTION:
SCANF():
Itisusedtogetdatainaspecified format.Itcanacceptdifferentdatatypes.
Syntax:
scanf(“ControlString”,var1address,var2address,…);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
inta,b,sum;
clrscr();
scanf(“%d%d”,&a,&b);
sum= a+b;
}
FORMATTEDOUTPUTFUNCTION:
PRINTF():
Theprintf() functionisused toprintdataofdifferentdatatypesontheconsoleinaspecified
format.
Syntax:
printf(“ControlString”,var1,var2,…);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
Void main()
{
inta,b,sum;
clrscr();
printf(“entertwonumbers:”); Entertwonumbers:5 4
scanf(“%d %d”,&a,&b); Sumis 9
sum= a+b;
printf(“sumis:%d”,sum);
}
UNFORMATTEDINPUTFUNCTION:
getchar()
getch()
getche()
gets()
getchar():
Thisfunctionreadsasinglecharacterdatafromthestandardinput.
Syntax:
variable_name=getchar();
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> j
void main()
{
Char ch;
ch=getchar();
Printf(“%c”,ch);
}
getch():
getch()acceptsonlyasinglecharacterfromkeyboard.Thecharacter enteredthroughgetch()isnot displayed
in the screen (monitor).
Syntax:
variable_name=getch();
Example:
#include<stdio.h>
#include<conio.h>
void main()
OUTPUT:
{ Ch=a
Char ch;ch=getch();
Printf(“ch=%c”,ch);
}
getche():
screen. getche()alsoacceptsonlysinglecharacter,butgetche()displaystheenteredcharacterinthe
Syntax:
variable_name= getche();
Example:
#include<stdio.h>
#include<conio.h>v
oid main()
OUTPUT:
{ a
Ch=a
Char ch;
ch=getche();
Printf(“ch=%c”,ch);
}
gets():
Thisfunctionisusedforacceptinganystringthroughstdin(keyboard)untilenterkey is
pressed.
Syntax:
gets(variable_name);
Example:
#include<stdio.h>
#include<conio.h>
voidmain()
{
Char ch[10]; OUTPUT:
cprogram
gets(ch); Printf(“ch= Ch=cprogram
%s”,ch); getch();
}
UNFORMATTEDOUTPUTFUNCTION:
putchar()
putch()
puts()
putchar():
This functionprintsonecharacteronthescreenatatime.
Syntax:
putchar(variablename);
Example:
#include<stdio.h>
OUTPUT:
#include<conio.h> enteracharacter:j j
void main()
{
Charch;
printf(“enteracharacter:”);
ch=getchar();
putchar(ch);
getch();
}
putch():
putchdisplaysanyalphanumericcharacterstothestandardoutputdevice.It displaysonlyone character at a
time.
Syntax:
putch(variable_name);
Example:
include<stdio.h>
#include<conio.h>v
oid main()
{ OUTPUT:
Press any character:
charch; Pressedcharacteris:e
clrscr();
printf(“Pressanycharacter:”);
ch = getch();
printf(“\nPressedcharacteris:”);
putch(ch);
getch();
}
puts():
Thisfunctionprintsthestringorcharacter array.
Syntax:
puts(variable_name);
Example:
include<stdio.h>
#include<conio.h>v
oid main()
{ OUTPUT:
Enterastring:cprogramming
charch[20]; cprogramming
clrscr();
puts(“enterastring”);
gets(ch);
puts(ch);
}
ASSIGNMENTSTATEMENT:
Theassignment statement hasthefollowingform:
Syntax:
variable=expression/constant/variable;
Itspurposeissavingtheresultoftheexpressiontotherightoftheassignmentoperatortothe variable on
the left. Here are some rules:
Ifthetypeofthe expressionis identicaltothatofthevariable, theresultissavedinthevariable.
Otherwise,theresultisconvertedtothetypeofthevariableandsavedthere.
Ifthetypeofthevariable isintegerwhilethetype oftheresult isreal,thefractional part,
including the decimal point, is removed making it an integer result.
Ifthetypeofthevariable isrealwhilethetypeoftheresult is integer,thenadecimal point is
appended to the integer making it a real number.
Oncethevariablereceivesanewvalue,theoriginalonedisappearsandisnomoreavailable.
Examples of assignment statements,
b=c;/* b isassigned thevalue ofc*/
a=9;/* ais assigned thevalue 9*/
b=c+5;/*bisassignedthevalueofexpr c+5*/
Theexpressionontherighthandsideoftheassignmentstatementcanbe:Anarithmetic
expression;
Arelationalexpression;
Alogicalexpression;
Amixedexpression.
Forexample,
int a;
floatb,c,avg,t;
avg=(b+c)/2;/*arithmeticexpression*/ a =
b && c; /*logical expression*/
a=(b+c) &&(b<c);/*mixedexpression*/
DECISIONMAKINGSTATEMENTS:
Decisionmakingstatement isdependingontheconditionblockneedto beexecutedornotwhich is
decided by condition.
Iftheconditionis"true"statementblockwillbeexecuted,ifconditionis"false"thenstatement block will
not be executed.
Inthissectionwearediscussaboutif-then(if),if-then-else(ifelse),andswitchstatement.InC language there
are three types of decision making statement.
• if
• if-else
• switch
ifStatement:
if-thenismost basicstatementofDecisionmakingstatement. Ittellstoprogramtoexecutea certain part
of code only if particular condition is true.
Syntax:
if(condition)
{
Statementsexecuted iftheconditionistrue
}
FLOWCHART:
else
Flowchar
t:
In the above syntax whenever condition is true all the if block statement are executed remaining
statementoftheprogrambyneglectingelseblock statement.Iftheconditionisfalseelseblockstatement remaining
statement of the program are executed by neglecting if block statements.
Example:
#include<stdio.h>v
oid main()
{
int age;
printf(“enterage:”)
scanf(“%d”,&age);
Output:
if(age>=18) Enterage:18
Eligibletovote Enter
{ age: 17
Noteligible to vote
printf(“age:%d”,age);
printf(“eligibletovote”);
}
else
{
printf(“age:%d”,age);
printf(“noteligibletovote”);
}
Nested if:
Whenanifelsestatement ispresent insidethebodyofanother“if”or“else”thenthisiscalled nested if
else.
SyntaxofNestedifelse statement:
if(condition){
//Nestedifelseinsidethebodyof"if"if(condition2) {
//Statementsinsidethebodyofnested "if"
}
else{
//Statementsinsidethebodyofnested"else"
}
}
else{
//Statementsinsidethebodyof"else"
}
Flowchart:
EXAMPLE:
#include<stdio.h>vo
id main() Output:
Enterageand salary: 5555000
{ 65000
intage, salary;
printf(“enter age and salary”);
scanf(%d%d”,&age,&salary);
if(age>50)
{
if(salary<60000)
{
salary=salary+10000
;printf(“%d”,salary);
}
else
{
salary=
salary+5000;
printf(“%d”,salary);
}
}
else
{
salary=salary+1000;
printf(“%d”,salary);
}
printf(“endofprogram”);
getch();
}
Switch:
Aswitchstatementwork withbyte,short,charandintprimitivedatatype,italsoworkswith enumerated types
and string.
Syntax:
switch(expression/variable)
{
case value1:
statements;
break;//optional
case value2:
statements;
break;//optional
default:
statements;
break;//optional
}
Rulesforapply switch:
Example:#include
<stdio.h>
#include<math.h>
#include<stdlib.h>
void main()
{
//declarationoflocalvariableop; int op,
n1, n2;
printf("enter2number:"); scanf(%d
%d”,&n1,&n2);
printf("\n1Addition\t\t2Subtraction\n3Multiplication\t 4Division\n5Exit \n\nPlease, Make a
choice ");
scanf("%d",&op);//acceptsanumericinputto choosetheoperation switch
(op)
{
case1:
printf("sumis:%d",n1+n2); break;
case2:
printf("differenceis:%d",n1-n2);
break;
case3:
printf("multiplication:%d",n1*n2); break;
case4:
printf("division:%d",n1/n2); break;
case5:
printf("exit”);
break;default:
printf(“enterthenumberbetween1to 5:”);
}
}
LOOPINGSTATEMENTS
Sometimesitisnecessaryfortheprogramtoexecutethestatementseveral times,andCloops execute a
block of commands a specified number of times until a condition is met.
Whatis Loop?
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do a task
tens ofthousands of times. Every programming languagehas the featureto instruct to do such repetitive
tasks with the help of certain form of statements. The process of repeatedly executing a collection of
statement iscalled looping.Thestatementsgetexecutedmanynumbersoftimesbasedonthecondition. But if
the condition is given in such a logic that the repetition continues any number of times with no fixed
condition to stop looping those statements, then this type of looping is called infinite looping.
Csupportsfollowingtypesofloops:
• whileloops
• dowhileloops
• forloops
whileloops:
Cwhile loopsstatement allowsto repeatedlyrunthesame block ofcodeuntilacondition is met.
whileloopisa mostbasicloopinCprogramming.whileloophasone controlcondition,and executesas long the
condition is true.
Theconditionoftheloop istestedbeforethebody oftheloopisexecuted,henceitiscalled an entry-
controlled loop.
Syntax:
while (condition)
{
statement(s);Incrementstatement;
}
Flowchart:
Flowchart:
Example:#include<stdio.h>voidmain()
{
int i=1;
clrscr();
while(i<=10)
{
printf(“%d”,i);
i++;
} getch();
}
Output:
12345678 910
Do..whileloops:
Cdowhileloopsareverysimilartothewhile loops,but it alwaysexecutesthecodeblockat least once
and furthermore as long as the condition remains true. This is an exit- controlled loop.
Syntax:
do{
statement(s);
}while(condition);
Flowchart:
EXAMPLE:
#include<stdio.h>vo
id main ()
{ Output:
int i=1; 12345678910
clrscr();
do
{
printf(“%d”,i);
i++;
}while(i<=10);
getch();
}
Forloop:
C forloops is very similarto a while loops in that it continues to process a block ofcode until a
statementbecomesfalse,andeverythingisdefined inasingleline.Theforloopisalsoentry-controlled loop.
Syntax:
for(init;condition;increment )
{
statement(s);
}
Flowchart:
Example:
#include<stdio.h>voi
d main ()
{ Output:
int i; 12345678 910
clrscr();
for(i=1;i<=10;i++)
{
printf(“%d”,i);
getch();
}
PRE-PROCESSORDIRECTIVES
The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation.Itiscalled micropreprocessorbecauseitallowsusto addmacros.Preprocessordirectivesare
executed before compilation.
Allpreprocessordirectivesstartswithhash#symbol. Let's
see a list of preprocessor directives.
#include
#define
#undef
#ifdef
#ifndef
#if
#else
#elif
#endif
#error
#pragma
s.no Preprocessor purposes syntax
directive
1 #include Used to paste code of given file into #include<filename>#incl
currentfile.Itisusedincludesystem- ude“filename”
definedanduser-definedheaderfiles.
Ifincludedfileisnotfound,compiler
renders error.
2 #define Used to define constant or #definePI3.14
microsubstitution.Itcanuseany basic
data type.
3 #undef Usedtoundefinetheconstantor macro #undefPI
defined by #define.
4 #ifdef Checks if macro is defined by #define. #ifdefMACRO
Ifyes,itexecutesthecode //code
otherwise#elsecodeisexecuted,if present. #endif
• #include<stdio.h> is missing instead we see lots of code. So header files has been
expanded andincluded in our source file.
Compiling:
Thenextstepistocompilefilename.iandproducean;intermediatecompiledoutputfile filename.s.
Thisfileisinassemblylevelinstructions.Let’sseethroughthis fileusing$vi filename.s
Assembly:
In this phase the filename.s is taken as input and turned into filename.o by assembler.
This file contain machine level instructions. At this phase, only existing codeis converted into
machinelanguage,thefunctioncallslikeprintf()arenotresolved.Let’sviewthisfileusing$vi
filename.o
Linking:
Thisisthe finalphase inwhichallthelinkingoffunctioncallswiththeirdefinitionsare done.
Linkerknows where all these functions are implemented.
Linker does some extra work also, it adds some extra code to our program which is
required whenthe program starts and ends.
Forexample,thereisacodewhichisrequiredforsettinguptheenvironmentlikepassing
commandline arguments. This task can be easily verified by using $size filename.o and $size
filename.
Throughthesecommands,weknowthathowoutputfileincreasesfromanobjectfileto an
executable file. This is because of the extra code that linker adds with our program.
UNIT II
ARRAYSANDSTRINGS
IntroductiontoArrays:Declaration,Initialization–Onedimensionalarray– Two
dimensional arrays - String operations: length, compare, concatenate, copy – Selection
sort, linear and binary search.
INTRODUCTIONTOARRAYS:DECLARATION,INITIALIZATION:ONE
DIMENSIONAL ARRAYS:
Array in C language is a collection or groupofelements (data). All the elements ofc
array are homogeneous (similar). It has contiguous memory location.
C array is beneficial if you have to store similar elements. Suppose you have to store
marks of 50 students, one way to do this is allotting 50 variables.
Soitwillbetypicalandhardtomanage.
For examplewecannotaccessthevalueof thesevariableswith only 1or 2 linesof code.
Anotherwaytodothisisarray.Byusingarray,wecanaccesstheelementseasily.Only few lines
of code is required to access the elements of array.
AdvantageofC Array:
1) CodeOptimization:Less codetotheaccessthe data.
2) Easytotraversedata:Byusingtheforloop,wecanretrievetheelementsofanarray easily.
3) Easytosort data:Tosorttheelementsofarray,weneedafewlinesofcodeonly.
4) RandomAccess:Wecanaccessanyelementrandomlyusing thearray.
DisadvantageofC Array:
1) Fixed Size: Whatever size, we define at the time ofdeclaration ofarray, we can't
exceed the limit. So, it doesn't grow the size dynamically like Linked List.
DeclarationofC Array:
Wecandeclareanarrayintheclanguageinthefollowing way.
Syntax:
data_typearray_name[array_size];
Now,letusseetheexampletodeclarearray.
intmarks[5];
Here,intisthedatatype,marksisthearray_nameand 5isthearray_size.
Howtoaccesselement ofanarrayin C:
Youcanusearraysubscript(orindex)toaccessanyelementstoredinarray.Subscript starts with
0, which means arr[0] represents the first element in the array arr.
Ingeneralarr[n-1]canbeusedtoaccessnthelementofanarray.wherenisanyinteger number.
Initialization ofCArray:
A simple wayto initialize array is by index. Notice that array index starts from0 and
ends with [SIZE - 1].
marks[0]=80;//initializationofarray
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Example:
#include<stdio.h>
intmain()
{ Output:
inti=0; 80
intmarks[5];//declarationofarray 60
marks[0]=80;//initializationofarray 70
marks[1]=60; 85
marks[2]=70; 75
marks[3]=85;
marks[4]=75;
//traversalofarray
for(i=0;i<5;i++)
{
printf("%d\n",marks[i]);
}//endoffor loopreturn0;
}
CArray:Declaration withInitialization:
Wecaninitializethecarrayatthetimeofdeclaration.Let'sseethecode. int marks[5]={20,30,40,50,60};
Insuchcase,thereisnorequirementtodefinesize.Soitcanalsobewrittenasthe following
code
.
Example:intmarks[]={20,30,40,50,60};
Programs:
#include<stdio.h> Output:
int main() 20
{ 30
inti=0; 40
intmarks[5]={20,30,40,50,60};//declarationandinitializationofarray 50
//traversalofarray 60
for(i=0;i<5;i++)
{
printf("%d\n",marks[i]);
}
return 0;
}
TWODIMENSIONALARRAYS(2D arrays):
ThetwodimensionalarrayinClanguageisrepresentedintheformofrowsand columns, also
known as matrix. It is also known as array ofarrays or list ofarrays.
Thetwodimensional,threedimensionalorotherdimensionalarraysarealsoknown as
multidimensional arrays.
DeclarationoftwodimensionalArrayin C:
Wecandeclareanarrayintheclanguageinthefollowing way.
Syntax:
data_typearray_name[size1][size2];
Asimpleexampletodeclaretwodimensionalarrayisgivenbelow.
Example:inttwodimen[4][3];
Here,4istherownumberand3isthecolumnnumber.
Initializationof2DArrayinC:
Awayto initializethe twodimensionalarrayat thetimeofdeclarationisgiven
below.
Example:intarr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Programs:
#include<stdio.h> Output:
int main() arr[0][0]=1
{ arr[0][1]=2
inti=0,j=0; arr[0][2]=3
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}}; arr[1][0]=2
//traversing2Darray arr[1][1]=3
for(i=0;i<4;i++) arr[1][2]=4
{ arr[2][0]=3
for(j=0;j<3;j++) arr[2][1]=4
{ arr[2][2]=5
printf("arr[%d][%d]=%d\n",i,j,arr[i][j]); arr[3][0]=4
}//endofj arr[3][1]=5
}//endofireturn0; arr[3][2]=6
}
STRINGOPERATION:
What ismeantby String?
StringinClanguageisanarrayofcharacters thatisterminatedby\0(nullcharacter).
Therearetwowaystodeclarestringinclanguage.
1. Bychararray
2. Bystringliteral
Let'sseetheexampleofdeclaringstringbychararrayinC language.
charch[10]={'j','a','v', 'a', 't','p','o','i','n','t','\0'};
As you know well, array index starts from0, so it will be represented as in the figure
given below.
Whiledeclaringstring,sizeisnotmandatory.Soyoucanwritetheabovecodeas given
below:
charch[]={'j','a','v','a', 't','p','o','i','n','t','\0'};
YoucanalsodefinestringbystringliteralinClanguage.
Forexample:charch[]="javatpoint";
Insuchcase,'\0'will beappendedat theend ofstring bythe compiler.
Differencebetweenchararrayand stringliteral:
Theonlydifferenceisthat stringliteralcannotbechangedwhereasstringdeclaredby char
array can be changed.
Programs:
Let'sseeasimpleexampleto declareandprint string.The'%s'isusedtoprint string in c
language.
#include<stdio.h>#in Output:
clude<string.h> int Char Array Value is: javatpoint
main() StringLiteralValueis:javatpoint
{
charch[11]={'j','a', 'v','a','t', 'p','o','i', 'n','t','\0'};
charch2[11]="javatpoint";
printf("Char Array Value is: %s\n", ch);
printf("StringLiteralValueis:%s\n",ch2);
return 0;
}
1. Stringoperations:length-strlen()
Thestrlen()functionreturnsthelengthofthegivenstring.Itdoesn't countnull character
'\0'.
Example:
#include<stdio.h>#in
clude<string.h> int Output:
main() Lengthofstringis: 10
{
charch[20]={'j','a', 'v','a','t', 'p','o','i', 'n','t','\0'};
printf("Lengthofstringis:%d",strlen(ch));
return 0;
}
2. Stringoperations:compare-strcmp():
Thestrcmp(first_string,second_string)functioncomparestwostringandreturns0if both
strings are equal.
Here,weareusinggets() functionwhichreadsstringfromtheconsole.
Programs:
#include<stdio.h>#in
clude<string.h> int Output:
main() Enter 1st string: hello
{ Enter2ndstring:hello
char str1[20],str2[20]; Strings are equal
printf("Enter1ststring:");
gets(str1);//readsstringfromconsole
printf("Enter 2nd string: ");gets(str2);
if((strcmp(str1,str2)==0)printf("Strings are
equal");
else
printf("Stringsarenotequal");
return 0;
}
3. Stringoperations:concatenate-strcat():
Thestrcat(first_string,second_string)functionconcatenatestwostrings andresultis
returned to first_string.
Programs:
#include<stdio.h>#i Output:
nclude<string.h> Valueoffirststringis:helloc
int main()
{
charch[10]={'h','e','l','l','o','\0'}; char
ch2[10]={'c', '\0'}; strcat(ch,ch2);
printf("Valueoffirststringis:%s",ch);return
0;
}
4. Stringoperations:copy-strcpy():
Thestrcpy(destination,source)functioncopiesthesourcestring indestination
Programs:
#include<stdio.h>#in
clude<string.h> int Output:
main() Valueofsecondstring is:javatpoint
{
charch[20]={'j', 'a','v','a','t','p','o','i','n','t', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Valueofsecondstringis:%s",ch2);
return 0;
}
5. Stringoperations:Reverse- strrev():
The strrev(string) function returns reverse ofthe given string. Let's see a simple example
of strrev() function.
Programs:
#include<stdio.h>#incl
ude<string.h>int
main() Output:
{ Enterstring:javatpoint
char str[20]; String is:
printf("Enterstring:"); javatpointReverseStringis:tn
gets(str);//reads string from console ioptavaj
printf("String is: %s",str);printf("\
nReverseStringis:%s",strrev(str));
return0;
}
6. Stringoperation:lower-strlwr():
The strlwr(string) function returns string characters in lowercase. Let's see
asimpleexample of strlwr() function.
Programs:
#include<stdio.h>#includ Output:
e<string.h>int main() Enter string: JAVATpoint
{ String is: JAVATpoint
char str[20]; LowerStringis:javatpoint
printf("Enterstring:");
gets(str);//readsstringfromconsole
printf("String is: %s",str);
printf("\nLowerStringis:%s",strlwr(str));
return 0;
}
7. Stringoperation:upper-strupr():
Thestrupr(string)functionreturnsstringcharactersinuppercase.Let'sseeasimple example of
strupr() function.
Programs:
#include<stdio.h>#in Output:
clude<string.h> int Enterstring:javatpoint
main() String is: javatpoint
{ UpperStringis:JAVATPOINT
char str[20];
printf("Enterstring:");
gets(str);//readsstringfromconsole
printf("String is: %s",str);
printf("\nUpperStringis:%s",strupr(str));
return 0;
}
SamplePrograms:
1. Programto calculatetheaveragemarksoftheclass
#include<stdio.h>void
main()
{intm[5],i,sum=0,n;float
Output:
avg;
Enternumberofstudents 5
printf(“enternumberofstudents\n”);
Entermarksofstudents
scanf(“%d”,&n);
55
printf(“entermarksofstudents\n”); for(i=0;i
60
<n;i++)
78
sum=sum+m[i];avg=float(sum)/n;
85
printf(“averageof:%f”,avg);
} 90
Averageof:73.6
2. Additionoftwonumbersin array:
#include<stdio.h>
void main()
{
inta[10],b[10],c[10],n,i;
printf("Enterthenumberofelements:\t");
scanf("%d", &n);
printf("Enter%delementsforarray1:\n",n); for (i
= 0; i < n; i++)
scanf("%d",&a[i]);
printf("Enter%delementsforarray2:\n",n); for (i
= 0; i < n; i++)
scanf("%d",&b[i]);
for (i = 0; i < n; i++)
c[i]=a[i]+b[i];
printf("Sumoftwoarrayelementsare:\n"); for
(i = 0; i < n; i++)
printf("%d\n",c[i]);
}
Output:
Enterthenumberofelements:5Enter5
elements for array 1:
93
37
71
03
17
Enter5elementsforarray2:
29
84
28
75
63
Sumoftwoarrayelementsare:122
121
99
78
80
3. Subtractionoftwonumber:
#include < stdio.h >
intmain()
{
intm,n,c,d,first[10][10],second[10][10],difference[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", & m, & n);
printf("Entertheelementsoffirstmatrix\n"); for
(c = 0; c < m; c++)
for(d=0;d<n;d++)scanf("%d",&first[c][d]); printf("Enter the
elements of second matrix\n");
for(c=0;c<m;c++)
for(d=0;d<n;d++)scanf("%d",&second[c][d]);
printf("Difference of entered matrices:-\n");
for(c=0;c<m;c++)
{
for(d =0;d<n;d++)
{
difference[c][d]=first[c][d]-second[c][d];
printf("%d\t",difference[c][d]);
}
printf("\n");
}
return0;
}
4. Multiplicationoftwonumbersinarray:
#include<stdio.h>
#include<stdlib.h> int
main(){
inta[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enterthenumberofrow=");
scanf("%d",&r);
printf("enterthenumberofcolumn=");
scanf("%d",&c);
printf("enterthefirstmatrixelement=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enterthesecondmatrixelement=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("multiplyofthematrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//forprintingresult
for(i=0;i<r;i++)
{
for(j=0;j<c;j++) Output:
{ enter the number of row=3
printf("%d\t",mul[i][j]); enterthenumberofcolumn=3
} enterthefirst matrixelement=
printf("\n"); 111
} 222
return 0; 333
} enterthesecondmatrixelement=
111
222
333
multiplyofthematrix= 6
66
121212
181818
UNITIIIFUNCTIONSANDPOINTERS
Introduction to functions: Function prototype, function definition, function call, Built-in functions
(string functions, math functions) – Recursion – Example Program: Computation of Sine series,
Scientificcalculatorusingbuilt-infunctions,BinarySearchusingrecursivefunctions–Pointers–Pointer
operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program: Sorting
ofnames–Parameterpassing:Passbyvalue,Passbyreference–ExampleProgram:Swappingoftwo numbers
and changing the value of a variable using pass by reference.
FUNCTIONS
Definition
Cenablesitsprogrammerstobreakupaprogramintosegmentscommonlyknownasfunctions
TerminologiesIn Functions
Afunctionfthatusesanotherfunctiongisknownasthecallingfunction,andgisknownasthe called
function.
Theinputs thatafunction takes areknown as arguments.
When a called function returns some result back to the calling function, it is said
toreturnthat result.
The calling function may or may not pass parameters to the called function. If
thecalledfunctionacceptsarguments,thecallingfunctionwillpassparameters,elsenot.
Function declarationis a declaration statement that identifies a function’s name, alist
ofarguments that it accepts, and the type of data it returns.
Function definition consists of a function header that identifies the function, followedby
the bodyof the function containing the executable code for that function.
FunctionDeclaration
Thegeneralformatfordeclaringafunctionthatacceptsargumentsandreturnsavalue asresult can be given
as:
return_data_typefunction_name(data_typevariable1,data_typevariable2,..);
ofunction_name-isavalidnameforthefunction.Namingafunctionfollowsthe
samerulesthatarefollowedwhilenamingvariables.Afunctionshouldhavea
meaningful name that must specify the task that the function will perform.
o return_data_type-thedatatypeofthevaluethatwillbereturnedtothecalling
function asa result of the processing performed by the called function.
o (data_typevariable1,data_typevariable2,...)-isalistofvariablesofspecified data
types. These variables are passed from the calling function to the called
function. They are also known as arguments or parameters that the called
function accepts to perform its task.
FunctionDefinition
When a function isdefined,space isallocatedfor that functioninthe memory.Afunctiondefinition comprises of
two parts:
Functionheader
Functionbody
Thesyntaxofafunctiondefinition canbegivenas:
return_data_typefunction_name(data_typevariable1,data_typevariable2,..)
{
.............
statements
.............
return(variable);
}
return_data_typefunction_name(data_typevariable1,data_typevariable2,...)isknownasthe
functionheader,therestoftheportioncomprisingofprogramstatementswithinthecurlybrackets
{}isthefunctionbodywhichcontainsthecodetoperformthespecifictask.
Thenumberofargumentsandtheorderofargumentsinthefunctionheadermust be
the same as thatgiven in the function declaration statement.
Thefunctionheaderissameasthefunctiondeclaration.Theonlydifference between
the two is thata function header is not followed by a semi-colon.
FunctionCall
Thefunctioncallstatementinvokesthefunction.Whenafunctionisinvoked,thecompilerjumpstothe called
function to execute the statements that are a part of that function. Once the called function is executed,
the program control passes back to the calling function. A function call statement has the following
syntax:
function_name(variable1,variable2,...);
If the return type of thefunction is not void, then the value returned by
thecalled functionmay be assigned to some variable as given below.
variable_name=function_name(variable1,variable2,...);
Eg://programtofindwhetheranumberisevenoroddusingfunctions.
#include<stdio.h>
intevenodd(int);//FUNCTIONDECLARATION int
main()
{
intnum, flag;
printf("\nEnterthenumber:");
scanf("%d",&num);
flag=evenodd(num);//FUNCTIONCALL if
(flag == 1)
printf("\n%disEVEN", num);
else
printf("\n%disODD",num);
return 0;
}
intevenodd(inta)//FUNCTIONHEADER
{
if(a%2==0)
return1;
else
return0;
}
Output:
Enterthenumber:7878 isEVEN
PASSINGPARAMETERSTOFUNCTIONS
Therearetwowaysinwhichargumentsorparameterscanbepassedtothecalledfunction.
1. Callbyvalue-Thevaluesofthevariablesarepassedbythecallingfunctionto the
calledfunction.
2. Call by reference - The addresses of the variables are passed by the calling
function to thecalled function.
1. CallbyValue
In call by value method, the value of the actual parameters is copied into the formal
parameters.
In call by value method, we cannot modify the value of the actual parameter by
the formalparameter.
Incallbyvalue,differentmemoryisallocatedforactualandformalparameters.
The actualparameteristheargumentwhichisusedinthe functioncallwhereasformal parameter
isthe argument which is used in the function definition.
Eg://Programforcallbyvalue
#include<stdio.h>i
nt main()
{
intx,y;
void swap(int,int); printf("Enter two
numbers:");scanf("%d%d",&x,&y); printf("\n\
nBeforeSwapping:x=%d\ty=
%d",x,y);
swap(x,y);
printf("\n\nAfterSwapping:x=%d\ty=%d",x,y);
}
voidswap(inta,int b)
{
a=a+b;
b=a-b;
a=a-b;
printf("\n\nInswapfunction: x=%d\ty=%d\n\n",a,b);
}
Output:
Prosandcons
Thebiggestadvantageofusingthecall-by-valuetechniqueisthatargumentscanbepassedas variables,
literals, or expressions.
1. Its main drawback is that copying data consumes additional storage space. In addition, it can take
alot of time to copy, thereby resulting in performance penalty, especially if the function is called
many times.
allByReferen
ce:
C Themethod ofpassing arguments by address orreferenceis also knownas call by address or call by
reference. Here, the addresses of the actual arguments are passed to the formal parameters of the
function.
Iftheargumentsarepassedbyreference, changes intheformalparameters alsomakechangeson actual
parameters.
g//ProgramforCallbyreference
E
#include<stdio.h>in
t main()
{
int x ,y;
void swap (int*,int*);
printf(“enterthetwonumbers”);
scanf(“%d%d”,&x,&y);
printf("\n\nBeforeSwapping:\n\nx=%d\ty=%d",x,y); swap(&x,&y);
printf("\n\nAfterSwapping:\n\nx=%d\ty=%d\n\n",x,y);
}
voidswap(int*a,int*b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
printf("\n\nInswapfunction:x=%d\ty=%d\n\n",a,b);
}
utput:
O
Entertwonumbers:2 3
BeforeSwapping:x=2 y=3
InSwapfunction:x=3 y=2
AfterSwapping:x=3 y=2
Advantages
1. Sincearguments arenotcopiedintothenewvariables,itprovidesgreatertimeandspace
efficiency.
2. Thefunctioncanchangethevalueoftheargumentandthechangeisreflectedinthecalling function.
3. Afunction can return onlyonevalue. In case we needto return multiple values,we can pass those
arguments by reference, so that the modified values are visible in the calling function.
Disadvantage:
1.ifinadvertentchangesarecausedtovariablesincalledfunctionthenthesechangeswould bereflected in calling
function as original values would have been overwritten.
RECURSIVEFUNCTION
Functioncallsitselfagainandagainiscalledrecursion.
Arecursivefunctionisdefinedasafunctionthatcallsitselftosolveasmallerversionofitstaskuntilafinal call is
made which does not require a call to itself.
Everyrecursivesolutionhastwomajorcases.Theyare,
Basecase-inwhichtheproblemissimpleenoughtobesolveddirectlywithoutmakinganyfurther calls to the
same function.
Recursive case - in which first the problem at hand is divided into simpler sub-parts. Second, the
function calls itself but with sub-parts of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.
Eg:Writeaprogramtocalculatethefactorialofagivennumber.
#include<stdio.h>
intFact(int);//FUNCTIONDECLARATION int
main()
{
int num, val;
printf("\nEnterthenumber:");
scanf("%d",&num);
val = Fact(num);
printf("\nFactorialof%d =%d",num,val);
}
intFact(intn)
{
if(n==1)
return;
else
return(n*Fact(n–1));
Output:
Enterthenumber:5
Factorialof5=120
TypesofRecursion
1. DirectRecursion
Afunctionissaidtobedirectlyrecursiveifitexplicitlycalls itself.
2. IndirectRecursion
Afunctionissaidtobe indirectlyrecursiveifitcontainsacalltoanotherfunctionwhich ultimately calls it
.
3. TailRecursion
A recursive function is said to be tail recursive if no operationsare pending to be performed
whenthe recursive function returns to its caller.
4. NonTailRecursion:
A recursive function is said to be non tail recursive if operations are pending to be performed when
the recursive function returns to its caller.
intFact(intn)
{
if(n==1)
return 1;else
return(n*Fact(n–1));
}
Advantages
Recursivesolutionsoftentendtobeshorterandsimplerthannon-recursiveones.
Codeisclearerandeasierto use.
Recursionworkssimilarto theoriginalformulatosolveaproblem.
Recursionfollows adivideand conquertechniqueto solveproblems.
disadvantages
Recursionisimplementedusingsystemstack.Ifthestackspaceonthesystemislimited,
recursion to a deeper level will be difficult to implement.
#include<stdio.h>#defin
e size 10
intbinsearch(int[],int,int,int); int
main()
{
intnum,i,key,position; int
low, high, list[size];
printf("\nEnterthetotalnumberofelements");
scanf("%d", &num);
printf("\nEntertheelementsoflist:"); for (i =
0; i < num; i++)
{
scanf("%d",&list[i]);
}
low =0;
high=num -1;
printf("\nEnterelementtobesearched:"); scanf("%d",
&key);
position=binsearch(list,key,low,high); if
(position != -1)
{
printf("\nNumberpresentat%d",(position+1));
}
else
printf("\nThenumberisnotpresentinthelist"); return
(0);
}
//BinarySearchfunction
intbinsearch(int a[],intx,int low,inthigh)
{
int mid;
if(low>high) return
-1;
mid=(low+high)/2; if
(x == a[mid])
{
return(mid);
}
elseif (x<a[mid])
{
binsearch(a,x,low,mid-1);
}
else
{
binsearch(a,x,mid+1, high);
}
Output:
Enter the total number of elements : 5
Entertheelementsoflist:1122334455
Enterelementtobesearched:33
Number present at 3
POINTERS
Apointeris avariablethatcontains thememorylocationofanothervariable.
DeclaringPointerVariables
datatype*ptrname;
Here,datatypeis thedatatype ofthevaluethat thepointerwill point to.Forexample,
Ex:
intx=10
int *ptr;
ptr=&x
ex:programusingpointer
#include<stdio.h>i
nt main()
{
int num,*pnum;
pnum=#printf(“enter
thenumber”);
scanf(“%d”,&num);
printf(“thenothatwasenteredis%d”,*pnum); return
0;
}
Output
Enterthenumber: 10
Thenumberthatwasenteredis:10
ThePointerOperators:
Therearetwo pointeroperators :
1. valueataddress operator (* )
2. addressofoperator(&)
Valueataddressoperator(*)
The*isaunaryoperator. Itgivesthevaluestored ataparticularaddress.The‘valueataddress’ operator is
also called ‘indirection’ operator.
q=*m;
ifmcontainsthememoryaddressofthevariablecount,thenprecedingassignmentstatement canplaces the
value of count into q.
Addressofoperator(&)
The&isaunaryoperator that returnsthememoryaddressofits operand
.m=&count;
Theprecedingassignmentstatementcan be“The memoryaddressofthevariablecount isplacesintom”.
Outputoftheprogram:
Address of a = 12345
Address of a = 12345
Address of b = 12345
Value of b = 12345
Value of a = 5
Valueofa=5
Valueofa=5
PointerArithmetic
Therearefourarithmetic operatorsthat canbeusedon pointers:++,--,+, and –
ValidPointerArithmetic InvalidPointerArithmetic
Operations
Addinganumberto pointer.
Subtractinganumberforma
pointer.
Incrementingapointer.
Decrementingapointer.
Subtractingtwopointers.
#include<stdio.h>int main()
{
intm=5,n=10,q=0; int
*p1;
int*p2;
int*p3;
OUTPUT:p1
p1 = &m; //printingtheaddressofm
=2680016
p2 = &n; //printing the address of n
p2=2680012
printf("p1 = %d\n", p1);
*p1+*p2=15
printf("p2=%d\n",p2); q
p1-p2=1
= *p1+*p2;
p1++=2680020
printf("*p1+*p2=%d\n",q);//point1 p3
p2--=2680008
= p1-p2;
printf("p1-p2=%d\n",p3);//point2 p1+
+;
printf("p1++=%d\n", p1);//point3
p2--;
printf("p2--= %d\n", p2);//point4
//Belowlinewillgive ERROR
printf("p1+p2=%d\n", p1+p2);//point5return0;
}
NULLPOINTER
null pointer which is a special pointer value and does not point to any value. This means that a
nullpointer does not point to any valid memory address.
int*ptr= NULL;
Thenullpointer isused in threeways,
1. Tostopindirectioninarecursivedatastructure.
2. Asanerrorvalue
3. Asasentinelvalue
#include<stdio.h>
int main()
{
int*ptr=NULL;
printf("Thevalueofptris %u",ptr);
return 0;
}
Output:
Thevalue ofptr is 0
POINTERSANDARRAYS:
Syntax:int *ptr;
ptr=&arr[0];
Eg://programtodisplayanarrayofgivennumbers.
#include<stdio.h>i
nt main()
{
intarr[]={1,2,3,4,5,6,7,8,9};
int*ptr1,*ptr2; ptr1
= arr;
ptr2 = &arr[8];
Output
while(ptr1<=ptr2) 1234567
{
printf("%d",*ptr1); ptr1+
+;
}
return0;
}
ARRAYOFPOINTERS:
Anarrayofpointerscanbedeclared
as.
datatype*array_name[size];
Eg:int *ptr[10];
Theabovestatementdeclaresanarrayof10pointerswhereeachofthepointerpointstoanintegervariable.
Example2://ProgramonArrayofPointers
int main()
{
int *ptr[10];
intp=1,q=2,r=3,s=4,t=5; ptr[0] =
&p;
ptr[1]=&q; OUTPUT:4
ptr[2]=&r;
ptr[3]=&s;
ptr[4] = &t;
printf("\n%d",*ptr[3]);
return 0;
}
Example2://ProgramonArrayofPointers
int main()
{
intarr1[]={1,2,3,4,5};
intarr2[]={0,2,4,6,8};
Output
intarr3[]={1,3,5,7,9};
101
int*parr[3]={arr1,arr2,arr3}; int
i;
for(i = 0;i<3;i++)
printf(«%d»,*parr[i]);
return 0;
}
ApplicationsofPointers
Pointersareusedtopassinformationbackandforthbetweenfunctions.
Pointers enable the programmers to return multiple data items from a function via function
arguments.
Pointersprovideanalternatewaytoaccess theindividualelementsofan array.
Pointersareusedtopassarraysandstringsasfunctionarguments.
Pointers are used to create complex data structures, such as trees,linkedlists,
linkedstacks,linkedqueues, and graphs.
PROGRAMTOSORTNAMES
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,count;
charstr[25][25],temp[25];
puts("Howmanystringsu aregoingtoenter?: ");
scanf("%d",&count);
puts("EnterStringsonebyone:");
for(i=0;i<=count;i++)
gets(str[i]);
for(i=0;i<=count;i++)
for(j=i+1;j<=count;j++)
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("OrderofSortedStrings:");
for(i=0;i<=count;i++)puts(str[i]);
return0;
}
2. WriteaprogramtoprinttheFibonacciseriesusingrecursion.
#include<stdio.h>int
Fibonacci(int); int
main()
{
intn, i=0, res;
printf("Enterthenumberofterms\n");
scanf("%d",&n);
printf("Fibonacciseries\n");
for(i = 0; i < n; i++ )
{
res=Fibonacci(i);Stacks 247printf("%d\t",res);
}
return0;
}
intFibonacci(intn)
{ output:
if ( n == 0 ) enterthetermsofFibonacciseries01123
return 0;
elseif(n==1)
return1;
else
return(Fibonacci(n–1)+Fibonacci(n–2)))
}
3. Writeaprogramtoaddtwointegersusingpointersandfunctions.
#include<stdio.h>
voidsum(int*,int*,int*);int main()
{
int num1,num2, total;
printf("\nEnterthefirstnumber:");
scanf("%d", &num1);
printf("\nEnterthesecondnumber:");
scanf("%d", &num2);
sum(&num1,&num2,&total);
printf("\n Total = %d", total);
return 0;
}
voidsum (int*a, int*b,int *t)
{
*t = *a+*b;
}
Output
Enter the first number : 23
Enterthesecondnumber:34
Total = 57
UNIT4STRUCTURESAND UNION
Structure-Nestedstructures–PointerandStructures–Arrayofstructures–Example
Program usingstructuresandpointers –Selfreferentialstructures – Dynamicmemory
allocation - Singly linked list – typedef-union storage classes and visibility
STRUCTURES:
A structure is a user-defined data type that can store related informationtogether.
Astructure isacollection of variables under a single name.
the major difference between a structure and an array is that, an array contains
related informationof the same data type.
Thevariables within a structureareof different data types and each has a name that is
used to selectit from the structure.
Featuresofstructures
Structurescanstoremorethanonedifferentdatatypedataundera
single variable.
Structureelements arestoredinsuccessivememorylocations.
Nesting ofstructureis possible.
Structureelementscan bepassedas argumenttothefunction.
Syntax:
//Structurecreation
structstructurename
{
Datatype1
variablename;Datatype2
variablename;
.
.
};
//ObjectCreation
struct structnameobjname;
It ispossibletocreatestructurepointers.
Example://Programtodisplayapoint
#include<stdio.h>structpoint
intx,y;
};
void main()
Output:
{ (2,3)
printf(“(%d,%d)”,p1.x,p1.y);
Initializationofstructures:
Syntax:
structstruct_name
datatypemembername1;
datatypemembername2;
datatypemembername3;
}sturct_var={constant1,constant2,constant3,….};
Example:
structstudent
{
int rno;
char name[20];
charcourse[20];
float fees;
}stud1={01,”Rahul”,”BCA”,45000};
or
structstudentstud2={02,”Rajiv”};
Accessingthemembersofastructure:
Astructuremembervariableisgenerallyaccessedusinga‘.’(dot)operator.
Syntax:
struct_var.membername;
Example:
stud1.rno=01;stud1.name=”Rahul”;stud1.course=”BCA”;stud1.fees=45000;
Receivinguserinput:
scanf(“%d”,&stud1.rno);
scanf(“%s”,stud1.name);
Displayingoutput:
printf(“RollNo:%d”,stud1.rno);printf(“Name:%s”,stud1.name);
TYPEDEFDECLARA
TION:
The typedef keyword enables the programmer to create a new data type name
from an existing data
type.
Syntax:
typedefexistingdatatype newdatatype;
Example1:
typedefintINTEGER;INTEGERnumber=5;
Example 2:
typedefstructstudent
int rno;
charname[20]; charcourse[20];floatfees;
};
COPYINGANDCOMPARINGSTRUCTURES:
Valuesof structurevariables
Copy
Wecanassignastructuretoanotherstructureofthe same
type.struct student
stud1={01,”Rahul”,”BCA”,45000};
structstudent stud2=stud1;
Compare:
if(stud1.fees==stud2.fees)
printf(“Feesofs2ands1areequal”);
TRUCTURESWITHINSTRUCTURES(NESTEDSTRU
CTURES):
S Structurescanbeplaced withinanotherstructures ie.,astructuremaycontain another
structure as itsmember. A structure that contains another structure as its member is
called as nested structures.
Example:writeacprogramtoreadanddisplayinformationofstudentsusing nested
structure
#include<stdio.h>in
t main()
{
intday;
intmonth;
int year;
};structstudent
{
int rollno;
charno[100];
floatfees;
structDOBdate;
};
structstudentstud1;
clrscr();
printf(“enter the roll no”);
scanf(“%d”,&stud1.roll_no);
printf(“enter the name”);
scanf(“%s”,stud1.name);
printf(“enter the fees”);
scanf(“%f “,&stud1.fees);
printf(“enter theDOB”);
printf(“%d%d%d”,&stud1.date.day,&stud1.date.month,&stud1.date.year); Printf(“\
n ******students details******”);
Printf(“\nROLLNo=%d”,stud1.roll_no);
Printf(“\n NAME=%s”,stud1.name);
Printf(“\n FEES = %f”,stud1.fees);
Printf(“\nDOB=%d-%d-%d”,stud1.date.day,stud1.date.month,stud1.date.year);
getch();
return 0;
}
Output:
ARRAYSOFSTRUCTURES.
Intheaboveexamples,wehaveseenhowtodeclareastructureand assign
valuestoitsdatamembers.
PASSINGSTRUCTURESTHROUGHPOINTERS:
Passing large structures to functions using the call by value method is very inefficient.
Therefore, it is preferred to pass structures through pointers. It is possible to create a
pointer to almost any type in C, including the user-defined types.
It is extremely common to create pointers to structures. A pointer to a structure is a
variablethatholdstheaddressofastructure.Thesyntaxtodeclareapointertoastructure can be
given as,
structstruct_name
{
data_typemember_name1;
data_typemember_name2;
data_typemember_name3;
.......................
}*ptr;
Or
structstruct_name*ptr;
Forourstudentstructure,wecandeclareapointervariablebywriting
structstudent *ptr_stud, stud;
Thenextthingtodoistoassigntheaddressofstudtothepointerusingtheaddress
operator(&), as we would do in case of any other pointer. So to assign theaddress,
we will write
ptr_stud =&stud;
Toaccessthemembersofastructure,wecanwrite
(*ptr_stud).roll_no;
Writeaprogramtoinitializethemembersofastructurebyusingapointertothestructure.
#include<stdio.h>
#include<conio.h>
structstudent
{
int r_no; Output
charname[20]; Enter the
structstudentstud1,*ptr_stud1;
clrscr();
ptr_stud1 =&stud1;
printf("\nEnterthedetailsofthestudent:
printf("\n Enter the Roll Number =");
scanf("%d", &ptr_stud1 -> r_no); printf("\
n Enter the Name = ); gets(ptr_stud1 ->
name);
printf("\nEntertheCourse="); gets(ptr_stud1 -
> course);
printf("\n Enter the Fees = ");
scanf("%d",&ptr_stud1->fees);
printf("\nDETAILSOFTHESTUDENT");
printf("\nROLLNUMBER=%d",ptr_stud1–>r_no);
printf("\n NAME = %s", ptr_stud1 –> name);printf("\n
COURSE = %s", ptr_stud1 –> course); printf("\n
FEES = %d", ptr_stud1 –> fees);
return 0;
}
SELF-REFERENTIALSTRUCTURES
Self-referential structures arethosestructures that containareference tothe data of
its same type. That is, a self-referential structure, in addition to other data, contains a pointer to
adatathatisofthesametypeasthatofthestructure.Forexample,considerthestructurenodegiven below.
structnode
{
int val;
structnode*next;
};
Here, the structure node will contain two types of data: an integer val and a pointer
next. You must be wondering why we need such a structure. Actually, self-referential
structure is the foundation of other data structures. We will be using them throughout this
bookandtheirpurposewillbeclearertoyouwhenwediscusslinkedlists,trees,andgraphs.
LINKEDLISTS
Array is a linear collection of data elementsin which the elementsare stored inconsecutive
memorylocations. Its size is fixed.
A linked list does not store its elements in consecutive memory locations and the user can
add anynumber of elements to it.
However,unlikean array,alinkedlist doesnotallowrandomaccess ofdata.Elementsin a
linked listcanbeaccessed only inasequential manner.But likeanarray,insertions anddeletions can
be done at any point in the list in a constant time.
A linked list can be perceived as a train or a sequence of nodes in which each node contains one
ormore data fields and a pointer to the next node
Start
Simplylinked list
Declarationofnode:
structnode
{
int data;
structnode*next;
}
Structnode*new_node;
new_node=(structnode*)malloc(sizeof(struct node));
INGLYLINKEDLi
sts
S Asinglylinkedlististhesimplesttypeoflinkedlistinwhicheverynodecontainssomedata and a
pointer to the next node of the same data type. By saying that the node contains a pointer to the next
node,we mean that the node stores the address of the next node in sequence.
Asinglylinkedlistallowstraversalofdataonlyin oneway.Figure6.7showsasinglylinked list.
START
Singlylinked list
Case1:InsertingaNodeattheBeginningofaLinkedList
.
structnode*insert_beg(structnode*start)
{
structnode*new_node;intnum;
printf(“\n Enter the data : “);
scanf(“%d”, &num);
new_node=(structnode*)malloc(sizeof(structnode));
new_node -> data = num;
new_node->next=start;
start = new_node;
returnstart;
}
Case2:InsertingaNodeattheEndofaLinkedList
structnode*insert_end(structnode*start)
{
structnode*ptr,*new_node;
int num;
printf(“\nEnterthedata:“);
scanf(“%d”, &num);
new_node=(structnode*)malloc(sizeof(structnode));
new_node -> data = num;
new_node->next=NULL; ptr
= start;
while(ptr->next!=NULL)ptr=ptr->next; ptr -
> next = new_node;
returnstart;
}
Case1:DeletingtheFirstNodefromaLinkedList
structnode*delete_beg(structnode *start)
{
struct node *ptr;ptr = start;
start=start->next;free(ptr);
return start;
}
Case2:DeletingtheLastNodefromaLinkedList
structnode*delete_end(structnode*start)
{
structnode*ptr,*preptr;ptr=start;
while(ptr -> next != NULL)
{
preptr=ptr;
ptr=ptr->next;
}
preptr->next=NULL;free(ptr);
return start;
}
Case3:DeletingtheNodeequaltoaGivenValueinaLinked List
structnode*delete_node(structnode*start)
{
structnode*ptr,*preptr; int
val;
printf(“\nEnterthevalueofthenodewhichhastobedeleted:“); scanf(“%d”,
&val);
ptr=start;
if(ptr->data==val)
{
start=delete_beg(start);
returnstart;
}
else
{
while(ptr->data !=val)
{
preptr=ptr;
ptr=ptr->next;
}
preptr->next=ptr->next;
free(ptr);
returnstart;
}
ProgrammingExample
Declareastructuretostoreinformation ofaparticulardate.
structdate
{
intday;
intmonth;
int year;
};
Declareastructuretocreateaninventory record.
structinventory
{
charprod_name[20];
float price;
int stock;
};
Writeaprogram,usinganarrayofpointerstoastructure,toreadanddisplaythedataof students.
#include
<stdio.h>#include<conio.
h>
#include<alloc.h>
struct student
intr_no;
char name[20];
charcourse[20];
int fees;
};
structstudent*ptr_stud[10]; int
main()
int i, n;
printf("\nEnterthenumberofstudents:"); scanf("%d",
&n);
for(i=0;i<n;i++)
{
ptr_stud[i]=(structstudent*)malloc(sizeof(structstudent)); printf("\nEnter
the data for student %d ", i+1);
printf("\n ROLL NO.: ");
scanf("%d",&ptr_stud[i]–>r_no);
printf("\n NAME: ");
gets(ptr_stud[i]->name); printf(“\
ncourse”);
gets(ptr->stud[i]->course);
printf(“/n FEES”);
scanf(“%d”,&ptr_stud[i]->fees);
}
printf(“\nDETAILSOF STUDENT”);
for(i=0;i<n;i++)
{
printf((“\n ROLL NO=%d”,ptr.stud[i]->r.no);
printf(“\n NAME=%s,ptr->stud[i]->name);
printf(“\nCOURSE=%s,ptr->stud[i]->course);
printf(“n FEES=%d”,ptr->stud[i]->fees);
}
return 0;
}
Output
Enterthenumberofstudents:1
Enter the data forstudent 1
ROLL NO.: 01
NAME: Rahul
COURSE:BCA
FEES:45000
DETAILSOFSTUDENT
SROLLNO.=01
NAME = Rahul
COURSE=BCA
FEES = 45000
Writeaprogramthatpassesapointertoastructuretoafunction. #include
<stdio.h>
#include<conio.h>
#include <alloc.h>
struct student
{
intr_no;
char name[20];
charcourse[20];
int fees;
};
voiddisplay(structstudent*);
int main()
{
structstudent *ptr;
ptr=(structstudent*)malloc(sizeof(structstudent));
printf("\n Enter the data for the student ");
printf("\nROLLNO.:");
scanf("%d",&ptr–>r_no);
printf("\n NAME: ");
gets(ptr–>name); printf("\
nCOURSE:"); gets(ptr–
>course);
}
printf(“/nFEES”);
scanf("%d",&ptr–>fees);
display(ptr);
getch();
return
}
voiddisplay(structstudent*ptr)
{
printf("\nDETAILSOFSTUDENT");
printf("\n ROLL NO. = %d", ptr–>r_no);
printf("\n NAME = %s", ptr–>name);
printf("\nCOURSE=%s",ptr–>course);
printf("\n FEES = %d", ptr–>fees);
}
Output
Enterthedata forthe student
ROLLNO.:01
NAME: Rahul
COURSE:BCA
FEES:45000
DETAILSOFSTUDENT
ROLL NO. = 01
NAME = Rahul
COURSE=BCA
FEES = 45000