B.E./B.Tech.DEGREEEXAΜΙΝΑΤΙΟΝ
MODEL QUESTION PAPER-1 Second
Semester.
CS 8251-PROGRAMMING IN C (Common to CSE and IT)
PART–A
1. Whatisexternalstorageclass.
Ans:
ExternalStorageClass
Theexternal storageclassvariables are declared outside allfunctionsusingkeyword “extern”.
Syntax
Externdata_typevariable; Example: Extern int
j:
2. What is a datatype? Give an example.
Ans:
A data type is used to indicate the type of data value stored in a variable. The data type of a variable is
specified at the time of its declaration and is attached till the end of execution of the program. Example
Int a, b;
Int c;
Short int num;
Doubledata;
Char ch;
Here, int, float, short int, double and char are the data types.
3. What isstring? Writeshort notesonstringdeclaration. Ans:
StringStringisdefinedasaseriesofcharacterswhichisconsidered asa singledataitem. They are
enclosed in double quotes.
Example“SIA GROUP”
Declaration of Strings
InC,thereis nospecificdata type forthe declaration ofstrings. Therearetwoapproaches for
declaration of strings. In the first approach, strings are implemented as an array of characters. The
generalformat ofdeclaringastringisasfollows,
Char str_var[size];
Example
CharS[10];
Thestring‘S’will holdupto10charactersincludingdelimiter(0)
4. What conditionsmust besatisfiedbytheentire elementsofanygivenarray? Ans:
Elementsofanarraycanbeinitializedat thetimeand placeoftheirdeclaration. Consider an array
with its elements.
Int a[4] = {5, 6, 7, 8};
Intheaboveexample,fourelementsarestored inanarray‘a’.Thearrayelementsarestored incontiguous
(adjacent) memorylocations. The arraybegins from‘0’i.e., a[0] is assigned thevalue'5'.Similarlya[1]
isassignedthevalue6.Thenumber'4'Ina[4]representsthetotal
S S I A G R O U P O
number ofelements. Theconditionsthat must besatisfied bytheentireelement ofthe givenarrayis
that, thoseelementsmust beofthesamedatatypeofthedeclared
5. Definepointer.Givethesyntaxfordeclaringapointer. Ans:
APointerisdefinedasavariablewhich holdsthe memoryaddressofanothervariable. Syntax for
Pointer Declaration
Thesyntaxforpointerdeclarationisshownbelow, Datatype
*ptr_name;
*** denotes that ptr_name isa pointervariablewhich Gives a
value stored at a specific address
6. List the advantages of recursion.
AdvantagesofRecursion
(i) It solvestheprobleminthemost generalwayaspossible.
(ii) It isusedtosolvethe morecomplex problemsthat haverepetitivestructure.
(iii) It is more useful because sometimes a problem is naturally recursive.
(iv) It helpsinunderstandingaproblemmoreeasily.
7. Define structure.
Ans:
A structure is identical to records which is used to store the data of an entity. It is a user defined data
type which can store the data simultaneously. It is also defined as a set of variables of different
datatypesthat arestoredundera singlename.
Thestructureisdefinedwithakeywordnamed“struct”andthenfollowed bythenameof thestructure
(structure_Name).
Syntax:
Struct tag_name
{
Datatypeml;
Datatypem2;
•
•
•
•
Datatype mn;
};
Intheabovesyntax
Structisakeyword,
Tagnameisnameofstructureandm1,m2, m3 are
the members of structure.
8. What do youmeanbynested structure?
Anested structureis a structurewhich contains another structure. Consider a structure ‘Department’of a
college. Each department will have name associated with it like
Computer Science department, Mechanical department etc. Each department will be
assigned‘Staff’. Staff inturn has attributes suchas name and designation as shownbelow. Here, both
department and staff are structures.
9. What isafile?
Afileis a permanent named unit that holds largevolumes ofrelated data. It storesthedata in secondary
or auxiliary memory such as CDs, tapes, DVDs and hard disks. Hence, it is a permanentlystored
memory. It isused tosupport thevolatilenature ofmainmemory. That is, whenthesystem is shut
down, mainmemorylooses thedata and relies onsecondary storage.Whenthesystemisswitchedon,
mainmemorygetsloadedwiththedatafromthe files.Moreover,mainmemorycannotholdtheentire
dataat anypoint.Rather,it accesses the data from files as and when needed.
10. Whatarethevariousmodesof openinga file?
The various modes of opening a file are discussed below,
1. “r” (Read) Mode
2. “w”(Write) Mode
3. “a” (Append) Mode
4. “r+” (Read and Write) Mode
5. “w+” (Write and Read) Mode
6. “a+”(Append and Read) Mode
7. “wb” (Write Binary) Mode
8. “rb”(ReadBinary)Mode9. “ab”(AppendBinary)Mode.
PART-B
11.(a)(i)ExplainthestructureofCprogramwithhelpofneatdiagram. Ans:
GeneralStructureofa‘C’Program
‘C’isa structuralprogramminglanguage.A‘C’programis acollectionorset offunctions. Each
function is a collectionofstatements, which performs a specifictaskintheprogram.
A‘C’program ingeneral, consist ofvarious sections which can be elaborated as follows,
Documentation Section
Toenhancethereadabilityoftheprogram,programmerscanprovidecommentsaboutthe programin
thissection.Thecommentsare includedbetweenthedelimiters‘/*’and‘*/’.
These statements are not executable rather they are ignored by compiler. Comments can beused
anywhereintheprogram but too manycomments should beavoided.
Header Files Section
A‘C’program depends on theheader files toa great extent. A header filecontainsthe information
requiredbythecompiler.The headerfilesareoftwotypes, onethat arewritten byprogrammersandother
that originates fromthecompiler.
AheaderfileinCprogram isincludedalongwithapreprocessingdirective#include. The most
commonly used header files in C are stdio.h and conio.h.
These header files appears along with the compiler that holds the information regarding the input
functions (like scanf and the output functions (like printf).
Global Declaration Section
Thissection isused fordeclaringtheglobalvariables. That is,thissectionis used in‘C’ program for
declaringa variablecommontoallotherfunctions existing intheprogram.
Main ProgramSection
Thissectionstartswithafunctionnamedasmain().Every‘C’program must containonly one
main()function. Itisthestartingpoint forprogramexecution. Thefunctionmain()has no parameters
or arguments.
Theprogram executionstarts from theopening brace“{“andterminates at theclosing brace,“}”
occurringafter themain(). Themain()function consists ofdeclaration and executablestatements.
Thegroupofstatements inmain()areexecutedsequentially.
User-defined FunctionSection
‘C’ language provides the facility for the user to define their own functions such functions are called
as user defined function. These functions are defined after the main() function. This section is not
mandatoryinallthe‘C’programs.
Consider a sample program (printing a line of text on monitor) to get a clear concept of the basic
structure of a ‘C’program
11.(a).(ii)What is meant by operator precedence? What arethe relative precedence of arithmetic
operators?
Ans:
Operator Precedence
Thevarious arithmetic operators in“C”has a precedenceassociated withthem. This precedenceis
usedtodetermine, how eachexpressioninvolvingmorethanone operator is evaluated. There are
distinct levels of precedence and anoperator may belong to one of thelevels.Theoperatorat thehigher
levelofprecedenceareevaluatedfirst andthe
Operatorsofthesameprecedenceareevaluatedeitherfromlefttorrightorfromrightto left,
dependinguponthelevel.
Precedenceof ArithmeticOperators
Anarithmeticexpressioninvolvingparenthesiswillbeevaluated from left toright usingthe rulesof
precedence ofoperators. Therearetwodistinct prioritylevels ofarithmetic
operatorsinC.
1Highpriorityarithmeticoperatorsare,%and 2
Low priority arithmetic operators are
Thebasicevaluationprocedureincludestwoleft-to-right passesthroughtheexpression. Duringthe
first pass,thehighpriority operators (if any) areapplied whentheyare
encountered. During thesecond pass,the low priority (if any) operators are applied when they are
encountered.
Example
Considerthebelowarithmeticexpression, X = a
+ (- b) / 3 + x + 2 – 1
When, a=9,b=12,c=3thenthestatement becomes, x = 9 –
12/3 + 3 * 2 – 1
The above operationis evaluated as follows,
First Pass
Step1:x-9-4-3-2-1 Step
2:x 9-4-6-1
Second Pass
Step3/x=5+6–1
Step4/x=11–1
Step 5 / x = 10
Y =a+(-b)/(3+c)*(2 –1) y=9–12/(3+3)*(2 –1)
When parenthesis are used, the expressions within the parenthesis assume highest
Priority. Iftwoormoresetsofparenthesisappearoneaftertheanother,theexpression containedinthe
left most set is evaluatedfirstandtheright most isthelast.
First Pass
Step1:y=9-12/6*(2–1) Step
2: y = 9 – 12/6 *1
Second Pass
Step3: y=9-2^ *1
Step4 : y= 9 –2
Third Pass
Step 5 / y = 7
Now, parenthesiscanbenested, insuchcases evaluationofthe expressionwillproceed outward
from the innermost set of the parenthesis.
So,z=a-(b/(3+c)^*2)-1 The
result is,
Step 1:z =9-(12/6^ *2)-1
Step2: z =9-(2^ *2)-1
Step 3: z =9 – 4– 1
Step 4: z =5 –1
Step5:z =4
Program
#include<stdio.h>
#include<conio.h> //Header file section main()
Main() //Main function
{
Float a,b,c,x,y,z;
a =9; b=12; c=3;printf(“ Evaluationsofexpressions n”);
//Evaluationsofexpressionsx=a+(-b)/3+c^ *2-1; y=a-b/(3+c)^ * (2-1);
z=a-(b/(3+c)^*2)-1;printf(“x=%fn”,x);printf(“y=%fn”,y); printf(“z
=%fn”,z); getch(); return0;
}
Output
(OR)
11.(b) Explain the following,
a. C Tokens
b. Keywords
c. Identifiers.
Ans:
1.CTokens
Thesmallest unit ina program is knownas C token. It consists ofa set ofoneor more characters
sequentially. Therearesix types oftokens inC language. Theyare as follows,
1. Keywords
2. Identifiers
3. Strings
4. Constants
5. Operators
6. Special symbols
(ii).Keywords
KeywordshavethespecialmeaningsinClanguage. Theyarealwayswritteninlowercase letters and
havethespecificpurpose. Thesekeywords are alsocalled reserved words.
Thereare32keywords inC.Theyareasfollows in alphabeticalorder.
(iii) Identifiers
Identifiersdesignatethenamesofvariables, functionsand arrays. Theyareuser-defined names
containingsequenceoflettersanddigits. Identifiers maybewritteneitherusing uppercaseor
lowercaseletter. Moreover, special character“underscore”canalsobeused inidentifiers. (It is
generallyusedinlongidentifiersforconnectingtwowords).
Example
Max, a14, nRules for Identifiers
Rules foridentifiers
The following are the rules for identifiers,
1. Identifiermust beginwithanalphabet oranunderscore.
2. Identifier namemust not beakeyword.
3. Theymust contain onlyletters, digits or underscore.
4. Thelengthofidentifiermust not exceed 31 characters.
5. Theymust notincludeanywhitespace.
12.(a)Explainthevariousoperationsperformed onone-dimensionalarrays. Ans:
Thevarious operations that areperformed on arrays areas follows,
1. Insertion
2.Deletion
3. Traversal
4.Merge.
1. Insertion
Insertoperationisusedfor insertinganewdata element at a specificindexin an array.
New value can be inserted at either, of the following position, (i) At
themiddleorat aparticularpositionofanarray.
(ii) Attheendofanarray.
(1) Algorithmtoinsert atthemiddleorataparticularpositionofanarray.
Toinsertavalueintothearray,thealgorithmgivenbelowusesthefollowingdeclaration, INSERT
(array_name, n, insert_POS, new_value)
Intheabovedecleration,
InsertPOS: indexpositionofarraytoinsert thenewvalue.
new_value:new_valuetoinsertinthearray array_name:
namegiventothearrayn:totalnumberofelementsthat can be
inserted in array.
The algorithm is as follows,
Step 1: Initialize index [i] to the total number of elements
Step2:whileindex[i]>=insert_POS, repeat step3to4untilXgetsprocessed Step 3:
SET X[i + 1] = X[i]
Step 4: SETi=i-1
[END OF LOOP]
Step5: Increasenumber ofelementsn= n+1
Step-6: SET X[linsert_POS] = new_value
Step-7: Exit
Intheabovealgorithm,step!Declaresthesizeofanarray(n)byassigningittotheindex[i].
Step 2 executes‘while’conditiontoshift alltheelementsofarraytotheir next index
positions, whoseindex values are greater thanor equal totheinsert position of index to allocate
memorytoinsert new element inthearraybyincrementingnby1.Step 6 inserts thenew element
valueinthevalueallocatedindexposition.
Considerthebelowexampletoinsert avalueintoanarrayInsert (X,6,2,30)
(ii).Algorithm to insert value to an existing array
Thealgorithmtoinsert valuetoanexistingarrayisasfollows,
Algorithm
Step1:Performthefollowingactions;
Upper_bound =Upper_bound+ 1
Step2:SETarrayX[Upper_bound]=newvalue
Step 3: Exit
In the above algorithm, step1 is used to increase the size of index by adding 1 to the
upper_bound value. This creates and allocates a new empty space at the end of the array. Step 2 is used
to assign the new element at the newly allocated empty position of array at index [i].
Consider an example arraywhich is declared as follows, int
X[10] ={2,3,4,5, 6, 7}
Theupper_boundofthisarrayis5. Thefollowingactions areperformed to insert a new value‘8’atthe
endofthearray,
(a) Increment the upper bound by1
(b) Insert thenew value‘8’atthenewupperboundi.e.,newlyallocatedemptyspace.
2. Deletion
Deleteoperationisusedto removeanalreadyexistingelement fromanarray. The existing
elements canbe delete from the array inthe following ways,
(i) Deletinganelementfromtheendofarray,
Thealgorithmtodeleteanelement fromtheendofanarrayisasfollows,
Algorithm
Step 1: SET Upper_bound = Upper_bound-1 Step
2: Exit
InStep1,Upper_bound valuei.e.,indexvaluethat holdsthelast element in arrayis
subtractedby1.Subtractinganupper_boundvalueofthearray automaticallydeletesthe
arrayelements holdingbyit.
(ii) Deletinganelement from a particularpositionor middleofanarray.
Todeleteanelementfromanyparticularpositionfromanarray, eachelement(after the position
of deleting element) must be shifted to their preceding index value
position.Thesyntax todeletean element from a particularpositionofanarrayis given below,
Syntax
DELETE(array_name,N,delete_position)
Intheabovedecleration, array_nameisthenameofthearrayfromwhichthe element must be
deleted.Nisthetotalnumber of elementsinan array.
delete_position is the position from which deletion must be done.
Thealgorithmfordeletionis asfollows,
Step1:SETi=delete_position
Step2: Whilek=N -1 repeat steps3to4 Step 3:
SETX[i] = x[i + 1]
Step 4: SET i = i + 1
Step5: SETN= N -1
Step 6: EXIT.
Intheabovealgorithm,step1initializetheindex[i]withthepositionat whichthe element hasto
bedeleted. Step2 executesa 'while'looptoshift allelementswhich are stored in index position
greater than 'delete_position' to their preceding index
positionin ordertoocupytheindexpositionofdeleteelement instep 3 and 4. After theelements
wereshifted, step 5 decreasesthetotalnumber ofelementsby1.
Example 2
DELETE(X,5,2)
3.Traversal
Traversal operation is performed on anarray to access each element exactly once.
This operation helps in
(a) Printingelementsofthearray
(b) Determiningthetotalnumberofelementspresent inanarray (c)
Calculatingthe sizeofan array, etc.
Since array is a homogeneous data structure that stores only single type of elements
in a linear or sequential manner,Traversal operation can be done easily and quickly.
Algorithmfor Traversing an Array
Step 1: Initialize index [i] to lower_bound of an array
Step2: Whileindex [i]<= Upper_bound, repeat steps 3 to4 until each element of array
(X) gets processed Step 3: Process the array X[i]
Step4: Increment thevalueofIi.e., I=i+1[ENDofLOOP] Step 5:
Exit
Here,Upper_boundisthehighest/endvalueofindex[i]
Lower_boundisthelowest/beginningvalueofindex[i].
Intheabovealgorithm,step1initializesthearrayindex(i)byassigningit witha lower_bound value.
Step2 contains a“while”conditiontoevaluatetheindex value
[i]ofarray, andonlyallowstoprocessfurther(step3and4),ifindex[i]islessthanor equal to
the upper_bound.
Arraytraversingisdoneinstep3,untileacharrayelement canbeaccessedto
perform aspecifictask.Step4incrementsorincreasesthevaluetoanarrayindex toaccessthe
nextelementofarrayduringnextiteration,untilendofthearrayor upper_bound is reached.
4. Merge
Mergeoperationisusedtocombinetheelements oftwoarraysintoasinglearray. In C,merge
operationhelpsincopyingtheelements oftwoarraysintoathirdarraysin asequentialmanner
i.e.,copyingallthearrayelements ofonearrayaftertheother array. Merging can bedoneon
both sorted and unsorted array.
Mergingtwounsorted arrays requires nosortingofthethird arrayaftermerging(as theyare
notsortedbeforemerging).Butmergingtwosortedarrayrequirestosort thethirdarrayafter
merging.
Consideredthebelow twoillustration regardingmerging,
(OR)
12.b)(i)What issearching? Explainindetailaboutlinearsearch. Ans:
Searching
Searchingis aprocess offindingthecorrect location ofanelement from alist orarrayof elements. In
an array, elements arestored inconsecutivememory locations. Searching is done by comparing a
particular element withthe remaining elements until the exact match is found. Iftheelement is found,
thesearch process is said to besuccessful or elsethe search process is terminated unsuccessfully.
The time complexity of searching technique depends on the number of comparisons made to find the
exact match.
Searching Techniques
The searching techniques can be categorized into two Types,
1. Sequential/Linear search
2. Binary search.
Sequential/Linear Search
Thesequential/linearsearchmethodismainlyapplicableforsearchinganelement within an
unordered list. Theprinciplebehind sequential/linear search is that each element ofthe list iscompared
ormatchedwiththekey(i.e., searchargument)inasequentialorder. The search (i.e., comparison)
begins from thestarting element andproceeds untila matchis foundortheendoflist isencountered.
Ifamatch isfound(i.e.,successfulsearch),the
position(i.e.,index)ofthematchedelementisre-turned. Ifamatchisnotfoundbutthe end of list is
encountered then1 is returned (i.e., unsuccessfulsearch).
AlgorithmofLinearSearch Input
n: [i.e.,thenumberofelementsinalist] Index:[i.e,
thepositionofelementsinalist] Key[i.e,the
element tobesearched]
Step1: Initializeindex(i.e.,position) I=0andnumberofelementsinlist=n Step 2:
Check, if (I< n) then
Gotostep3
else
Gotostep5
Step3:Compare,if(keymatcheswithlistelement ati)then printf(“Element
found!Successfulsearch”)
Returntheindex(i)ofthefoundelement Goto
step 6 else
Step4: Increment Iby1
Gotostep2
Step5:printf(“Endoflist; Elementnotfound!Unsuccessfulsearch”) Step 6: Stop.
Example
Let theelementtobesearchedis‘15’.Thelinear/sequentialsearchalgorithmstartsfrom thefirst
element i.e.,4andcomparesit withthekeyelement i.e., 15.
Theindexelement isset to‘0’.
Since 4≠15,‘i’is moved to the next element i.e., 10.
Nowtheelement ati=1iscomparedwiththekeyelement 15.
Since 10 ≠15, ‘i’ is moved to the next element i.e., 5.
Now,theelement at i= 2iscomparedwiththekeyelement 15.
Since, 5≠15,‘i’ is moved to the next element ie., 15.
Now,theelementi=3iscomparedwiththekeyelement‘15’.
Since,thecurrentelement matcheswiththekeyelement(i.e.,15=15)atlocationi=3,the search is
successful andthelocation ofelement‘i’i.e., 3is returned uponsuccess
Program
#include<stdio.h> #include<conio.h> int
linearsearch(int[],int,int); int main()
{
Int n,A[20], i, key, index; Clrscr():
Printf(“Enter the number of elements in the list:n”);
Scanf(“%d”,Cn);
Printf(“Enter the elements of the list:n”); for(i=0; i<n; i++)
Scanf(“%d”, CA[i]);
Printf(“Enterthekeyelementtobesearchedinthelist:n”); Scanf(“%d”, Ckey);
index linear_search(A, n, key);
if(index==-1)
Printf(“Search completed, element not foundn”); else
Printf(“Search completed, element %dfoundinthelist at position%d”, key, index); getch(); return 0;
}
Int linear_search(int I[ ], int n, int e)
{ int i; for(i=0;
i<n; i++)
if(1[i]==e) return
1; return
-1;
}
Time Complexity :
TimecomplexityoflinearsearchisO(n). It requiresatmost‘n’comparisonstosearchan element in a
list containing‘ elements
12.(b).(ii)WriteaCprogramtoperformscalarmatrix multiplication. Ans
Program
#include<stdio.h>
#include<conio.h>int
main()
{
int i, j, row, col, A[10][10], num; Clrscr();
Printf(“ Enter Number of rows: “); Scanf(“%d”,
Ci);
Printf(“EnterNumberofcolumns:“).
Scanf(“%d”, C j);
Printf(“ Enter the elements of the matrix: n”); // Input elements in matrix for(row 0; row <I;
row++)
{
for(col=0;col<j;col++)
{
scanf(“%d”,C A[row][col]);
}
}
Printf(“ Enter the Multiplication Value:“); Scanf(“%d”, Cnum);
for(row=0; row<I; row++)//Performscalarmultiplicationof matrix
{
for(col=0; col j; col++)
{
A[row][col] = num*A[row][col];
}
}
Printf(“ The Resultant Scalar Matrix is: n”); for(row
= 0; row <I; row++)
{
for(col = 0; col <j; col++)
{
printf(“%d t”, A[row][col]);
}
Printf(“n”);
}
getch(); return
0; }
13.(a) (i)What isa pointer? Explaintheprocessofdeclaringandinitializingapointer. Explain about
thereason forusingpointer.
Ans:
Pointer
Apointerisdefinedasa variablewhichholdsthememoryaddressofanothervariable.
Example
int x= 2
This statement will allow the system to locate integer variable ‘x’ and store ‘2’ in that location. If
‘x’ is stored at location ‘ 1210’ by the system, then address of the variable ‘x’ will be‘1210’.
Declaration of Pointers
Pointers are declared in the same way the variables are declared. But a symbol called precedesthe
nameofthevariable. Thisindicates that apointervariablehasbeencreated.
Syntax
Thesyntaxforpointerdeclarationis asshownbelow, datatype
*ptr_name;
‘*’denotesthat ptr_nameisapointervariablewhichgivesavaluestoredat aspecific address.
Example
int *p
Initialization of Pointers
Theprocessofallocatingaddressofvariabletopointervariableiscalled as“pointer initialization”.
Syntax
Thesyntaxforpointerinitializationisasshownbelow, int
*P;
*P = 6 ;
Whentheabovestatements arecompiled, thevariable valueis stored at theaddress
pointedbyP. Let‘P’points toanaddress1028. Thus,thevalue6 isstored at thelocation 1028.
Hence, thevalueofP is‘1028’and*P is‘6’.
Assigning Address ofVariable to PointerVariable
Apointervariablepointsto thememory address ofother variables.
Example
int *P: int
a = 6;
P =Ca;
Here, *P pointsthevaluepresent at location1005i.e., *P =6whichissameasthevalueof‘ ‘a’.
Reasons for Using Pointers
Thefollowingarethe reasons for usingpointers,
1. Pointersareusedinindirect addressingwhichismost oftenlyused inassembly
languages.
2. Pointersareusedindynamicmemorymanagement (i.e.. dynamicmemory
allocation and deallocation).
3. Apointer is used to access a dynamically memoryal- located storage. This
dynamically allocated storageis called a heap.
4. Thevariablesthat aredynamicallyallocated from theheap areknown asheap dynamic
variables.Thesevariablesdonot havetheassociatedidentifiers. Hence, theycanbe
referencedonlybypointersandreferencetypevariables.
5. Useof pointers makes the codingprocess simple and easy.
6. Pointersareusedtocreaterecursivetypesthat areimportant indatastructuresand algorithms.
7. Pointersareusedtoenhancethelanguage’swritability.
13.(a). (ii) Write a C program for scientific calculator using built-in-functions. Ans:
Scientific Calculator
Scientificcalculator is defined as a graphing calculatorthat contains mathematical and trigonometricsymbols.
It iscapableofperformingmanyarithmetic(i.e..add,subtract,
multiplication)andtrigonometriccalculations(modules,sin,tan,d/dxetc)Generally, itis used in many
scientifical, engineering and mathematical applications.
Program
#include<stdio.h>
#include <math.h>
VoidprintMenu(){
Printf(“ScientificCalculatorn”);
Printf(“1.Addition (+)n”);
Printf(“2.Subtraction (-)n”); Printf(“3.
Multiplication (*)n”); Printf(“4. Division
(/)n”);
Printf(“5.SquareRoot(sqrt)n”);
Printf(“6.Power(^)n”);
Printf(“7. Sine (sin)n”);
Printf(“8. Cosine (cos)n”);
Printf(“G. Tangent (tan)n”);
Printf(“0.Exitn”);
Printf(“Enter your choice: “);
}
Int main() {
Intchoice;
Double num1, num2, result;
Do { printMenu();
scanf(“%d”, schoice);
switch(choice){
case 1:
printf(“Enter two numbers: “);
scanf(“%lf %lf”, snum1, snum2); result =
num1 + num2;
printf(“Result:%.2lfn”,result);
break;
case 2:
printf(“Entertwonumbers:“);
scanf(“%lf %lf”, snum1, snum2); result
= num1 – num2;
printf(“Result:%.2lfn”,result); break;
case 3:
printf(“Entertwonumbers:“);
scanf(“%lf %lf”, snum1, snum2); result
= num1 * num2;
printf(“Result:%.2lfn”,result); break;
case 4:
printf(“Entertwonumbers:“);
scanf(“%lf %lf”, snum1, snum2);
if (num2 != 0) { result=
num1/ num2; printf(“Result:
%.2lfn”, result);
}else{
Printf(“Error: Division by zero!n”);
}
Break;
Case 5:
Printf(“Enter a number: “);
Scanf(“%lf”, snum1);
If (num1 >= 0) {
Result = sqrt(num1);
Printf(“Result:%.2lfn”,result);
}else{
Printf(“Error:Cannot computesquare root ofanegative number!n”);
}
Break;
Case 6:
Printf(“Enterthebaseandtheexponent:“);
Scanf(“%lf %lf”, snum1, snum2);
Result = pow(num1, num2);
Printf(“Result:%.2lfn”,result);
Break;
Case 7:
Printf(“Enteranangleindegrees:“); Scanf(“%lf”,
snum1);
Result=sin(num1 *M_PI/180.0); //Converttoradians
Printf(“Result: %.2lfn”, result);
Break;
Case 8:
Printf(“Enteranangleindegrees:“); Scanf(“%lf”,
snum1);
Result=cos(num1*M_PI/180.0); //Convertto radians
Printf(“Result: %.2lfn”, result);
Break;
Case G:
Printf(“Enteranangleindegrees:“); Scanf(“%lf”,
snum1);
Result=tan(num1*M_PI/180.0); // Convertto radians
Printf(“Result: %.2lfn”, result);
Break;
Case 0:
Printf(“Exiting…n”);
Break;
Default:
Printf(“Invalid choice! Please try again.n”);
}
} while (choice != 0);
Return0;
}
--------------------------------------------------------------------------------------------------------------
(OR)
13.(b) Explainthepurposeofa functionprototype. Andspecifythedifference between user
defined function and built in function.
Ans :
Function Prototype
User-defined Function
User-definedfunctionallowsusertodefinetheirownfunctionsaccordingtothe requirement of
programs.
Elements of User-defined Functions
Theelementsofuserdefinedfunctionsareas follows,
1. Function Declaration
2. Function Definition 3. Function Prototype
4. FunctionCall.
1. Function Declaration
Afunctiondeclarationdeclaresafunctionthat consistsofafunctiontype(or returntype),
functionnameparameter(or argument)list andaterminating semicolon. Function
declaration is also called function prototype. In C, a function must be declared before it
is invoked.
Syntax
Function-type function-name(parameter-list);
Where,parameter-list is a list ofargumentswithdata typesseparatedbya comma.
However,it isnot necessaryfortheparameternamestobesameinthe prototype
declaration and the functiondefinition, but their types must match.
Example
Float sum(float x, float y);
Thisexampleisafunctionprototypeforthefunctionsum()that takestwofloat arguments and
returns a float valueas result.
Moreover, functions canevenbe a declared without anyparameter list and the return
value. Insuch cases,thefunctionprototypeis written as,
Voiddisplay(void);
Inadditiontothese,thefunctiondeclarationisreferred asglobalprototypeifitis declared beforeall
thefunctions, and localprototypeifdeclared inthefunction definition. Globalprototypecanbe
usedbyallthefunctionspresent inthe
program.Whereas,localprototypeisonlyusedbytherespectivefunctions which
contain it.
2. Function Definition
Afunctiondefinition isthecompletedescription ofafunction. It specifieswhat a function
does and how it performs. It contains a function body (a block of statements) in addition
to function name, arguments list and return type. It has thefollowing generalsyntax.
Syntax
return_type function_name(parameter_list)
{
local variable declarations;
Statements;
(expression);
}
return
Example
float sum(float x, float y) float z;
z= x + y;
return(z);
}
3. Function Prototype
Afunction prototype is a declaration ofa subroutine(or a function) that specifies the
function name, an argument list withdatatypes and thereturntype ofa function without the
function body. It specifies the function name, the argument list and returntype that a
function expects, but it does not specifywhat the function does.
Afunctionprototypeisusedtoenforcestrongtypechecking.That isithelpsthe compiler
to check whether the data types of arguments passed to a function matchwithwhat the
functionexpects.Therefore, everyfunctionshouldhavea functionprototypewhich is
declaredinthedeclarationpart ofa program.
Syntax
return-type function-name(parameter-list);
Where, parameter-list isa list ofargumentswithdatatypesseparated bya comma.
Afunction prototypes ends witha semicolon. It should be given beforemain().
Example
Float sum(float x, float y);
Thisexampleisafunctionprototypeforthefunctionsum()that takestwofloat arguments and
returns a float value.
4. Function Call
Afunction can be called withfunction name and a list ofactual parameters. When a
function callis encountered, the control is transferred tothe respective function. Then, it is
executed and theresultingvalueis returned tothemain function.
Afunctioncall Is a postfix expression. Theoperator (..)has highest precedence. Therefore,
whenevera functioncalappearsinanexpression, it isevaluatedfirst.
Syntax
F(…)
Here,‘F’representstheoperandorthefunctionname,and(….)indicatesthe operator or
theparenthesis set whichconsists of actualparameters.Multiple
actual parameters areseparated bycommas. A function can be called in various ways. For
example,considera function'mul()'it canbecalledinsixdifferent
Ways,
(i) Mul(8,6)
(ii) Mul(z, 6)
(iii) Mul(8, z)
(iv) Mul(z+8, 6)
(v) Mul(6, mul(z, i))
(vi) Mul(Expressiont, Expression2).
Here, thefirstthreeexamplesindicatethat mul()is called withprimary expressions. Inthe
fourthexample,mul()iscalledwithbinaryexpressionz+8as thefirst argument value. The
fifthexampleshows that mul()is called withmul(z, i)asitsownfirst argument.Thesixth
exampleisthesummationoftheabovefive examples.
Example
#include<stdio.h>
#include<conio.h>
#include<math.h>
Void Add();
Int main()
{
Int a, b, c;
Clrscr();
Add();
getch();
return0;
}
VoidAdd()
{
Int x= 3,y2, z;
z= x + y;
Printf(“Theadditionofx andyis%d”, z);
}
14.(a) What is a structure? Explain how a structure is defined. Ans:
A structure is identical to records which is used to store the data of an entity. It is a user defined data
type which can store the data simultaneously. It is also defined as a set of variables of different
datatypesthat arestoredundera singlenameThestructureIs
defined with a keyword nained ‘struct” and then followed by the name of the structure
(structure_name)Thesyntax ofthestructureisshownbelow,
Syntax
Struct tag_name 1
{
Datatypem1;
Datatype m2;
•
•
•
• Datatype
mn;
};
Here,
Struct isa keyword.
Tag_nameisthenameofthestructure.
m1,m2,…mnaremembersofstructureswhichbelongstoanydatatypelikeinteger, character etc.
Definitionofa structureholdsthefollowingsyntax,
1. Specifythesemicolon (;) after closingbracket.
2. Declaretheindividualmembers withtheirtypeand name.
3. Usethenameofthestructurewhiledeclaringthevariableofitstype.
Considerthefollowingexamplethat definesastructureofstudent detailscontainingthe data fields
name, branch, ageand rollno.
Struct stud_details
{
Char name[20];
Char branch[5];
Int age;
Int rollno;
};
Thisstructurespecifiesatemplatethat displaysthedataasfollows,
Thedata fields name,branch, ageandrollno arecalledmembersorstructureelements. Themembers
may belongtodifferent data types.Structurename i.e., stud_details is also known as structure tag that
maydeclare structure type variables later.
Since,thestructureisauserdefineddatatypethevariablewhichisdeclaredinastructure areknownas
membersofthestructure. Theabovestructuredeclarationdoesn’t require any memory (or) storage
space. It only specifies storage or structure with in memory.
Besidesthis,typeofdeclarationprovidedetails ofthemembernamesdefinedwithina structure.
However,thememoryallocatedtostructuresisdoneondeclarationofits variables.
Thefollowingprogramillustratesanexampleofstructureinc
Program
#include<stdio.h>
#include<conio.h> Struct
EmployeeDetails
{
Char*name;
int id, age;
};
int main()
{
StructEmployeeDetailse;
Clrscr();
e.name=“John”;
e.id=5678.;
e.age=26;printf(“nEmployeeNameis
%s”,e.name); printf(“nEmployee Idis:
%d”,e.id); printf(“nEmployeeAgeis%d”, e.age);
getch(); return0;
}
(OR)
14.(b). (i)Explainindetailabouttheconcept ofarrayofstructuresalongwithan example
program.
Ans:
Theprocess ofgrouping a set ofdistinct structurevariables intoonearray is referred toasan
arrayofstructures. Thisorganizationwhenthereisa need ofdeclaring
distinctvariableintooneisreferredthatis,forexampleconsideranthathas
different departmerits and eachdepartment hascertain numbermucturefor every
employee, it is easytodefinea singlestructureforalltheemployees ofan organization. of
employees, insteadofdefiningaseparate
Syntax
struct struct_name
{
data_typemember_name1;data_type member_name 2;
• •
•
Data_type member_name n:
}
struct struct_name struct_variable [index];
Intheabovesyntax, struct isakeyword struct_nameisthenameofthestructure and
data_type member_name 1,................arethemembersofthestruture. struct_variable
[index];isthenameofthevariablewhichisoftypestructand [index]representsthe total number
ofelements present in an array.
Example
struct employee
{
charemp_name[20]; int
emp_id;
float emp_sal;
};
struct employeearray_employee[4]; Intheaboveexample,array_employee[4] representsan
arrayof4 elementswhichare oftype "struct"(i.e..struct employee array, employee[4]:)
employeerepresents thestructurevariable
[4] representsthe[index]
The above example is diagrammatically represented as follows,
Here,
Array_employee[0]pointstothefirst element ofanarray. Array_employee[1]
pointstothesecondelementofanarray. Similarly,
Array_employee[3]pointstothethirdelementofanarrayAn arrayof
structurewith15 employee is declared as.
Struct employee emp [15];
Inordertoassignvaluestotheemployeewhichisstoredatposition10iswrittenas.
Employee[10].Name=“John”; Employee
[10]. Id = 666;
Employee[10]. Salary= 15000;
Here, the array subscript ([]) is used first followed by a dot (.) operator.
Initializing Array of Structures
Thearrayofstructureis initialized asfollows.
Struct struct_namestruct_variable[N]= {{const01, const 02, …….const0n},{const 11, const 12,
const……,const1n},…..{constN1,constN2,……, Const Nn}}; Here, struct is a keyword,
struct_nameis nameofstructure.
Struct_variableisthestructurevariableand const 01, const 02
canbeint, char, floatingpoint constants.
Example
Struct employeeemp[2]={{“John”,666,20000},{“Dennis”, 777,250001}}; Here,
Employeeisstruct_name emp is
struct_variable
[2] representstheindex[N].
Program
#include<stdio.h>
#include<conio.h>int
main()
{
Struct employee
{
Char name[50]:
int id_no: int
salary:};
struct employee emp[25];
int n,I; clrscr(); printf(“n Enter the number of employees: “); scanf(“%d”,Cn);
for(i=0;i<n;i++)
{
Printf(“Enterthenameofemployee:“);scanf(“%s”,Cemp[i].name);
Printf(“ Enter the id_no of employee: “); scanf(“%d”,Cemp[i].id_no); Printf(“ Enter the salary of
employee:“); scanf(“%d”,Cemp[i].salary);
}
getch(); for(i=0;i<n;i++)
{
Printf(“Detailsof%dEmployee n”,i+1);
Printf(“ NAME = %s n”,emp[i].name);
Printf(“ ID_NO= %d n”,emp[i].id_no);
Printf(“SALARY=%dn”,emp[i].salary);
}
getch();
return0;
}
14.(b).(ii) Whatisaself-referentialstructure?Discussitstypeswithexampleprograms. Also list
down its applications.
Ans:
Self Referential Structure
Aselfreferentialstructureisdefined asastructureinwhichthereexistsaself reference
(i.e., a reference to the data of similar type) apart from the reference to other data. This
structure acts as the basefor various data structures including thelinkedlists,treesand
graphs. It hasthefollowingsyntax,
Syntax
Struct tag
{
typeldata1;type2 data
2;
•
•
•
typendata n;
Structtag*ptr;
};
Intheabovesyntax,‘ptr’referstothenameofthepointervariable.Here,a structureoftype
‘tag’willincludea memberwhichpointstosomeother structure having its type as tag.
Thefollowing examplerepresents a selfreferential structure,
Example
Struct node
{ Char item [15]; Struct
node*ptrnode;};
Theaboveexampleconsistsofastructurenamedstudent,whichconsists of three
members. Thefirst memberis a 50-element arrayofcharacters called ‘name’,second
memberis‘rollno’oftypeint,andthelast memberisaself referentialstructurenamed
‘Ptr’
In general,theself-referentialstructuresaremainlyusedintheimplementation oflinked
data structureslikelists,treesetc.
Consideranimplementationoflinked-lists. Alinked list isadatastructuresthat contains a
set ofnodes, whereeachnodepoints totheimmediatenodeinthe list.
In a linked list, cach node consists oftwoitems, one containing a pointer tothe data and
theother containingtheaddressOfthenext element. Hence, theorder ofnodes canbe
alteredbychangingthepointer. Moreover, thedata canbe insertedordeletedbychanging
thepointer.Therefore,usingalinkedlistthedata structurecan easilybeexpanded or
consized dependingontheneeds.
In a linked list, nodes represent self-referential structure and the arrows represent pointers
that makes a linked list a self- referential structureConsider thefollowingexampleofa
linked list.
Theaboveexamplecontains a linkedlist having three objects, everyobject contain two itemsi.e.,a
characterstringandapointertonextobject ofthelist.Thestaringofalistis representedusingaseparate
pointer.Itisrepresentedusingthelabe“begin’.Theendofthe list is represented using a cross. Herethe
objects represent theself referentialstructure.
Ingeneral,aself-referentialstructurecanbeoftwotypes,thatis, 1.Self-
referentialstructurewithsinglelink
2.Self-referential structure with multiple links.
1. Self-ReferentialStructurewith SingleLink
Astructurethat containsa singleselfpointerasitsmemberisreferredasaself-referential structurewithasingle
linkThefollowingfigure illustratesthewayintheobjectsofaself referentialstructurewithsinglelinkare
connected.
Theabovefigureconsistsoftwoobjectswhichcontainsasinglelinkbetweenthem.The following
programillustratesa selfreferentialstructurewitha single link.
Program
#include<stdio.h>
#include<conio.h
Struct node
{
int d1; int
d2;
Struct node*LINK;
};
main()
{
Struct node ob1
Struct node ob2;
Clrscr();
ob1.LINK NULL;
ob1.d150; ob1.d2
= 60;
ob2.LINK-
NULL; ob2.d1 =
70:
ob2.d2 = 80;
ob1.LINK
=Cob2;
printf(“n%d”,
ob1.LINK->d1);
Printf(“n%d”,
ob1.LINK->d2);
getch(); return 0;
}
2. SelfReferentialStructurewith MultipleLinks
Asstructurethat containmultipleselfpointermultiplereferred as a selfreferential structurewith
multiplelinksasicallyusedtobuilt variouscomplexdatastructures. In general, thistypeofstructure
canconnect multiplenodesat astanceoftime. The followingfigurerepresentsaselfreferential
structurewithmultiplelinks.
Theabovefigureconsistsofthreeobjectswhichcontainsmultiple linksamongthem. The followingprogram
illself referentialstructurewithmultiplelinks.
Program
#include <stdio.h>
#include <conio.h>
Struct node
{
intd; structnode
*REV; struct
node*NEXT
;
}
Main()
Struct node object 1;
Struct node object2;
Struct node object3;
Clrscr(); object1.
PREV=NULL; object1.
NEXT = NULL:;
object1.d=70;
object1.PREV = NULL;
object2. NEXT=NULL;
object2.d=80;
object3.PREV= NULL;
object3. NEXT=NULL;
object3.d=90;
object1.NEXT=Cobject
2; object2.NEXT =
Cobject3;
object2.PREV=
Cobject1:
object3.PREV=Cobject 2;
Printf(“n%dt”, object1.d);
Printf(“%dt”, object1. NEXT>d); Printf(“%dn”,
object | NEXT>NEXT->d); printf(“%dt”,
object2.PREV->d); Printf(“%dt”, object2.d);
Printf(“%dn”,object2.NEXT->d);
Printf(“%dt”,object3.PREV->d);
Printf(“%d”,object3.d); getch();
return 0;
}
Intheaboveprogramobject1,object2,object3aretheobjectsofselfreferentialstructure “node”, they
are joined usingmultiple links so that accessing each other’s data becomes easy. Thisbecomesthe
advantageofselfreferentialstructures.
Applications of a Self Referential Structure
Thevariousapplicationsofaselfreferentialstructurearelistedbelow, 1.Stack
2.Linkedlists
3.Graphs
4.Queues
5 Trees.
15.(a)Explainaboutthevarioustypes offiles inC. Ans:
AStreamreferstoasourceordestinationofthedata. Itiseither attachedtoaterminal(i.e., anyphysical
device) or an auxiliarymemory file.
Cprogramminglanguagetypicallysupportstwotypes offilesi.e., a textfilesand a binary files.
TypesofFiles
1. Text Files
Atext filestores data onlyintheform ofcharacters. Thenon-characterdatatypes cannot bedirectly
storedinthetext filewithoutconvertingthemintoasequenceofcharacters.
Input/Output functions can be used to convert non-character datatypes to characters while writing into
the text files. If input has to be read from a text file, it is read in the form of character sequence. Converted
totheir appropriateinternal formats and arethen stored in memory.
Theconvertingfunctioncanbeoneofthefollowingthreetypes,
(i) Formatting I/O functions (ii)
Character I/O functions (iii)
String I/O functions.
(i)FormattingI/OFunctions
In case of reading an input, formatting I/O functions convert the series of input characters to standard
types. On the other hand, while displaying the output, standard datatypes are converted to sequence
of characters.
Example
Scanf(), printf().
(ii)Character I/O Functions
Thesefunctionscanreadorwrite onlyonecharacterat atime. Example
getchar(), putchar().
(iii).String I/O Functions
These functions can read or writestrings ofcharacters. Example
fgets(), fputs().
Someofthefeatures oftext filesareasfollows,
(i)Intext file,data isstoredin thehumanreadableform.
(ii) A new line character (n) is used to terminate every line of data in the text file.
(iii) Aspecialcharactermarkercalled“EOF”(End-Of-File)isusedtoindicatetheendof a file.
2.Binary Files
A binary file is a collection of bytes. This collection is a compiled version of a C program (E.g:
programl.exe),ormusicdata storedina wavefileora picturestored ina graphicfile.
In contrast to text files in a binary file, the data is stored in the internal format of computer, the format
similar to that of memory. Binary streams also called as block I/O functions are used for reading and
writingbinary files.
Someofthe features ofbinary files areas follows,
(i) Nonewlinecharacterisusedtoindicatetheendofaline.
(ii) Inbinaryfiles,dataisstored inthemanner similar tothatinmemory.
(iii) Liketext files,binaryfilesalsouses“EOF”markertoindicatetheendofa file.
(OR)
15.(b)Explaininbriefabout sequentialaccessfiles. Ans:
Sequential access fileenablestheuserstosequentially accessthewhole(or)part offile. It is different
from random access where in, the user can visit only the required file which they want to access. But, in
sequential access, theuser need to visit all thefiles i.e., n-1
filesinordertoaccess n’hfile. Therefore, it can besaid that,sequentialaccess file consume relatively
much (more) access time.
Sequentialaccessfilecanbeaccessedusingthefollowingfunctionsthat areavailablein I/Or
library.
1. fopen()
2. fclose()
3. fprintf()
4. fgetc()5. fputs().
6.
1. fopen()
Thisfunctionisusedto openthefile
Syntax
Handle=fopen(filename,mode); In
the above syntax,
handleisanpointerthat referstoafile.fopenisa open
function. filename andmodearethetwo string
arguments.
2. fclose()
Thisfunctionisusedtoclosethefile Syntax
fclose(handle); Intheabove syntax, fclose
is a function and, handle is an argument.
3. fprintf()
This function is used to print/write the text to the file.
Syntax
Fprintf(handle, “text”); In the above syntax,
handle is an argument and, text is (string) used
toprint thetext inanfile.
4. fgetc()
Thisfunctionisused to read thetext character atansingleinstanceoftime.
Syntax
Ch=Fgetc(handle);
In theabovesyntax,inchisancharacter datatypethat referstoa file. Fgetcis anget
character functionand,Handle is an argument ofthefile.
5.fputs()
Thisfunctionisusedtowritethetextsequentially alongwithanargumenttoafile.
Syntaxfputs(“next”,handle)Intheabovesyntax,
Text is a string used to write the text to a file and, handle is an argument.
Program
#include<stdio.h>//headerfilesection
Typedef struct {
Int id;
Char name[25];
Intmarks1,marks2,marks3;
}
STD;
STD s;
Void display(FILE *);
Intsearch(FILE*,int);
Void main()
{
Int i,n,id_key,opn;
FILE *fp;
Clrscr();
Printf(“Enterthenumber ofrecords“);
Scanf(“%d”,Cn); fp-fopen(“stud.dat”,”w”);
for (i=0;i<n;i++)
{
Printf(“ReadtheInfo ofStudent: %d(id,name,marks1,marks2,marks3) n”,i+1);
scanf(“%d%s%d%d%d”,Cs.id,s.name,Cs.marks1,Cs.marks2,Cs.marks3);
fwrite(Cs,sizeof(s),1,fp);
}
fclose(fp);
fp=fopen(“stud.dat”,”r”); do
{
Printf(“Press1-Displayt 2-Searcht 3-ExittEnterYourOption”); scanf(“%d”,Copn); Switch(opn)
{
Case1:printf(“nStudent Recordsinthe File n”); display(fp); Break;
Case2: printf(“Readtheidofthestudent tobesearched”); scanf(“%d”,Cid_key); If(search(fp,id_key)){
Printf(“ Record found in the filen”);
Printf(“%dt%st%dt%dt%dn”,s.id,s.name,s.marks1,s.marks2,s.marks3); else
Printf(“RecordwithUSN%disnotfoundn”,id_key);break; Case3:
printf(“Exit!!Pressanykey”);
getch(); break;
default: printf(“ Invalid Option!!! Try again! n”); break;
}
}
while(opn != 3); fclose(fp);
}
void display(FILE *fp) //display function section
{
rewind(fp); while(fread(Cs,sizeof(s),1,fp))
printf(“%dt%st%dt%dt%dn”,s.id,s.name,s.marks1,s.marks2,s.marks3);
}
int search(FILE *fp, int id_key) //search function section
{
rewind(fp);
while(fread(Cs,sizeof(s),1,fp))
if(s.id=id_key) return 1; return 0;
}
PART–C
16. (i) WriteaC codingfortransactionprocessingusingrandom accessfiles. Ans:
Program
#include<stdio.h>struct clientData
{
Unsignedint acctNum;
Char lastName 15];
Char firstName[ 10 ];
double balance;};
Voidmain()
FILE *cfPtr;
Struct clientData client {0,“”,“”, 0.0 };
Clrscr();
If ((cfPtr fopen(“C:Turboc3BinProjectcredit2.dat”, “w”))=NULL)
{
Puts(“Filecouldnot beopened.”);
}
else
{
Printf(“Enteraccountnumber”“(1to100,0toendinput)n”); scanf(“%d”, Cclient.acctNum);
While (client.acctNum != 0)
{
Printf(“Enter lastname, firstname, balancen”),
Fscanf( stdin,“%14s%9s%If”, client.lastName, client.firstName, Cclient.balance);
fseek(cfPtr,(client.acctNum-1)*sizeof(structclientData), SEEK_SET); fwrite(Cclient,
sizeof( struct clientData), 1, cfPtr); Printf(“Enter account number’n”); scanf(“%d”,
Cclient.acctNum);
}
fclose(cfPtr);
}
getch();
return;}
16.(ii).WriteaCprogramtocomputemodeforanarrayofelement. Ans:
Mode
Mode is defined as anobservation that occurs most frequency inthe data. This measureof central
tendencyisusedincaseof nominalor higherorderscales. However, it isnot appropriatetousemode
forordinal orintervaldata unlessthedata is grouped.
Example
Considerthenumbers,10, 10,11,12,12,12,14,15,15.Themodeofgivennumbersis{12}.
Program
#include<stdio.h>
#include<conio.h>
Void main()
{
Int I,j,A[50], B[20],k,num,mode_value; int
c=1,max=0;
Clrscr();
Printf(“Enter the total number of elements: “); Scanf(“%d”,Cnum);
Printf(“Enter the numbers: n”); for(i=0;i<num;i++)
{
Scanf(“%d”,CA[i]);
}
for(i=0;i<num-1;i++) //Loop to calculate mode
{
mode_value=0; for(j=i+1;j<num;j++)
{
If(A[i]=A[j])
{
}
Mode_value++;
}
If((mode_value>max)CC(mode_value!=0))
{ k=0;
max=mode_value;
B[k]=A[i];
k++;
}
elseif(mode_value=max)
{
B[k]=A[i];
K++;
}
for(i=0;i<num;i++)
{
If(A[i]-B[i])
C++;
}
If(c=num) printf(“ No
mode”); else
{
Printf(“The Mode is: “);
for(i=0;i<k;i++)
Printf(“n%d”,B[i]);
getch(); return; } }
C programming for first year engineering students

C programming for first year engineering students

  • 1.
    B.E./B.Tech.DEGREEEXAΜΙΝΑΤΙΟΝ MODEL QUESTION PAPER-1Second Semester. CS 8251-PROGRAMMING IN C (Common to CSE and IT) PART–A 1. Whatisexternalstorageclass. Ans: ExternalStorageClass Theexternal storageclassvariables are declared outside allfunctionsusingkeyword “extern”. Syntax Externdata_typevariable; Example: Extern int j: 2. What is a datatype? Give an example. Ans: A data type is used to indicate the type of data value stored in a variable. The data type of a variable is specified at the time of its declaration and is attached till the end of execution of the program. Example Int a, b; Int c; Short int num; Doubledata; Char ch; Here, int, float, short int, double and char are the data types.
  • 2.
    3. What isstring?Writeshort notesonstringdeclaration. Ans: StringStringisdefinedasaseriesofcharacterswhichisconsidered asa singledataitem. They are enclosed in double quotes. Example“SIA GROUP” Declaration of Strings InC,thereis nospecificdata type forthe declaration ofstrings. Therearetwoapproaches for declaration of strings. In the first approach, strings are implemented as an array of characters. The generalformat ofdeclaringastringisasfollows, Char str_var[size]; Example CharS[10]; Thestring‘S’will holdupto10charactersincludingdelimiter(0) 4. What conditionsmust besatisfiedbytheentire elementsofanygivenarray? Ans: Elementsofanarraycanbeinitializedat thetimeand placeoftheirdeclaration. Consider an array with its elements. Int a[4] = {5, 6, 7, 8}; Intheaboveexample,fourelementsarestored inanarray‘a’.Thearrayelementsarestored incontiguous (adjacent) memorylocations. The arraybegins from‘0’i.e., a[0] is assigned thevalue'5'.Similarlya[1] isassignedthevalue6.Thenumber'4'Ina[4]representsthetotal S S I A G R O U P O
  • 3.
    number ofelements. Theconditionsthatmust besatisfied bytheentireelement ofthe givenarrayis that, thoseelementsmust beofthesamedatatypeofthedeclared 5. Definepointer.Givethesyntaxfordeclaringapointer. Ans: APointerisdefinedasavariablewhich holdsthe memoryaddressofanothervariable. Syntax for Pointer Declaration Thesyntaxforpointerdeclarationisshownbelow, Datatype *ptr_name; *** denotes that ptr_name isa pointervariablewhich Gives a value stored at a specific address 6. List the advantages of recursion. AdvantagesofRecursion (i) It solvestheprobleminthemost generalwayaspossible. (ii) It isusedtosolvethe morecomplex problemsthat haverepetitivestructure. (iii) It is more useful because sometimes a problem is naturally recursive. (iv) It helpsinunderstandingaproblemmoreeasily. 7. Define structure. Ans: A structure is identical to records which is used to store the data of an entity. It is a user defined data type which can store the data simultaneously. It is also defined as a set of variables of different datatypesthat arestoredundera singlename. Thestructureisdefinedwithakeywordnamed“struct”andthenfollowed bythenameof thestructure (structure_Name).
  • 4.
    Syntax: Struct tag_name { Datatypeml; Datatypem2; • • • • Datatype mn; }; Intheabovesyntax Structisakeyword, Tagnameisnameofstructureandm1,m2,m3 are the members of structure. 8. What do youmeanbynested structure? Anested structureis a structurewhich contains another structure. Consider a structure ‘Department’of a college. Each department will have name associated with it like Computer Science department, Mechanical department etc. Each department will be assigned‘Staff’. Staff inturn has attributes suchas name and designation as shownbelow. Here, both department and staff are structures.
  • 5.
    9. What isafile? Afileisa permanent named unit that holds largevolumes ofrelated data. It storesthedata in secondary or auxiliary memory such as CDs, tapes, DVDs and hard disks. Hence, it is a permanentlystored memory. It isused tosupport thevolatilenature ofmainmemory. That is, whenthesystem is shut down, mainmemorylooses thedata and relies onsecondary storage.Whenthesystemisswitchedon, mainmemorygetsloadedwiththedatafromthe files.Moreover,mainmemorycannotholdtheentire dataat anypoint.Rather,it accesses the data from files as and when needed. 10. Whatarethevariousmodesof openinga file? The various modes of opening a file are discussed below, 1. “r” (Read) Mode 2. “w”(Write) Mode 3. “a” (Append) Mode 4. “r+” (Read and Write) Mode 5. “w+” (Write and Read) Mode 6. “a+”(Append and Read) Mode 7. “wb” (Write Binary) Mode 8. “rb”(ReadBinary)Mode9. “ab”(AppendBinary)Mode.
  • 6.
    PART-B 11.(a)(i)ExplainthestructureofCprogramwithhelpofneatdiagram. Ans: GeneralStructureofa‘C’Program ‘C’isa structuralprogramminglanguage.A‘C’programisacollectionorset offunctions. Each function is a collectionofstatements, which performs a specifictaskintheprogram. A‘C’program ingeneral, consist ofvarious sections which can be elaborated as follows, Documentation Section Toenhancethereadabilityoftheprogram,programmerscanprovidecommentsaboutthe programin thissection.Thecommentsare includedbetweenthedelimiters‘/*’and‘*/’. These statements are not executable rather they are ignored by compiler. Comments can beused anywhereintheprogram but too manycomments should beavoided.
  • 7.
    Header Files Section A‘C’programdepends on theheader files toa great extent. A header filecontainsthe information requiredbythecompiler.The headerfilesareoftwotypes, onethat arewritten byprogrammersandother that originates fromthecompiler. AheaderfileinCprogram isincludedalongwithapreprocessingdirective#include. The most commonly used header files in C are stdio.h and conio.h. These header files appears along with the compiler that holds the information regarding the input functions (like scanf and the output functions (like printf). Global Declaration Section Thissection isused fordeclaringtheglobalvariables. That is,thissectionis used in‘C’ program for declaringa variablecommontoallotherfunctions existing intheprogram. Main ProgramSection Thissectionstartswithafunctionnamedasmain().Every‘C’program must containonly one main()function. Itisthestartingpoint forprogramexecution. Thefunctionmain()has no parameters or arguments. Theprogram executionstarts from theopening brace“{“andterminates at theclosing brace,“}” occurringafter themain(). Themain()function consists ofdeclaration and executablestatements. Thegroupofstatements inmain()areexecutedsequentially. User-defined FunctionSection ‘C’ language provides the facility for the user to define their own functions such functions are called as user defined function. These functions are defined after the main() function. This section is not mandatoryinallthe‘C’programs. Consider a sample program (printing a line of text on monitor) to get a clear concept of the basic structure of a ‘C’program
  • 8.
    11.(a).(ii)What is meantby operator precedence? What arethe relative precedence of arithmetic operators? Ans: Operator Precedence Thevarious arithmetic operators in“C”has a precedenceassociated withthem. This precedenceis usedtodetermine, how eachexpressioninvolvingmorethanone operator is evaluated. There are distinct levels of precedence and anoperator may belong to one of thelevels.Theoperatorat thehigher levelofprecedenceareevaluatedfirst andthe Operatorsofthesameprecedenceareevaluatedeitherfromlefttorrightorfromrightto left, dependinguponthelevel. Precedenceof ArithmeticOperators Anarithmeticexpressioninvolvingparenthesiswillbeevaluated from left toright usingthe rulesof precedence ofoperators. Therearetwodistinct prioritylevels ofarithmetic operatorsinC. 1Highpriorityarithmeticoperatorsare,%and 2 Low priority arithmetic operators are Thebasicevaluationprocedureincludestwoleft-to-right passesthroughtheexpression. Duringthe first pass,thehighpriority operators (if any) areapplied whentheyare
  • 9.
    encountered. During thesecondpass,the low priority (if any) operators are applied when they are encountered. Example Considerthebelowarithmeticexpression, X = a + (- b) / 3 + x + 2 – 1 When, a=9,b=12,c=3thenthestatement becomes, x = 9 – 12/3 + 3 * 2 – 1 The above operationis evaluated as follows, First Pass Step1:x-9-4-3-2-1 Step 2:x 9-4-6-1 Second Pass Step3/x=5+6–1 Step4/x=11–1 Step 5 / x = 10 Y =a+(-b)/(3+c)*(2 –1) y=9–12/(3+3)*(2 –1) When parenthesis are used, the expressions within the parenthesis assume highest Priority. Iftwoormoresetsofparenthesisappearoneaftertheanother,theexpression containedinthe left most set is evaluatedfirstandtheright most isthelast. First Pass Step1:y=9-12/6*(2–1) Step 2: y = 9 – 12/6 *1
  • 10.
    Second Pass Step3: y=9-2^*1 Step4 : y= 9 –2 Third Pass Step 5 / y = 7 Now, parenthesiscanbenested, insuchcases evaluationofthe expressionwillproceed outward from the innermost set of the parenthesis. So,z=a-(b/(3+c)^*2)-1 The result is, Step 1:z =9-(12/6^ *2)-1 Step2: z =9-(2^ *2)-1 Step 3: z =9 – 4– 1 Step 4: z =5 –1 Step5:z =4 Program #include<stdio.h> #include<conio.h> //Header file section main() Main() //Main function { Float a,b,c,x,y,z; a =9; b=12; c=3;printf(“ Evaluationsofexpressions n”); //Evaluationsofexpressionsx=a+(-b)/3+c^ *2-1; y=a-b/(3+c)^ * (2-1); z=a-(b/(3+c)^*2)-1;printf(“x=%fn”,x);printf(“y=%fn”,y); printf(“z =%fn”,z); getch(); return0;
  • 11.
    } Output (OR) 11.(b) Explain thefollowing, a. C Tokens b. Keywords c. Identifiers. Ans: 1.CTokens Thesmallest unit ina program is knownas C token. It consists ofa set ofoneor more characters sequentially. Therearesix types oftokens inC language. Theyare as follows, 1. Keywords 2. Identifiers 3. Strings 4. Constants 5. Operators 6. Special symbols
  • 12.
    (ii).Keywords KeywordshavethespecialmeaningsinClanguage. Theyarealwayswritteninlowercase lettersand havethespecificpurpose. Thesekeywords are alsocalled reserved words. Thereare32keywords inC.Theyareasfollows in alphabeticalorder.
  • 16.
    (iii) Identifiers Identifiersdesignatethenamesofvariables, functionsandarrays. Theyareuser-defined names containingsequenceoflettersanddigits. Identifiers maybewritteneitherusing uppercaseor lowercaseletter. Moreover, special character“underscore”canalsobeused inidentifiers. (It is generallyusedinlongidentifiersforconnectingtwowords). Example Max, a14, nRules for Identifiers Rules foridentifiers The following are the rules for identifiers, 1. Identifiermust beginwithanalphabet oranunderscore. 2. Identifier namemust not beakeyword. 3. Theymust contain onlyletters, digits or underscore. 4. Thelengthofidentifiermust not exceed 31 characters. 5. Theymust notincludeanywhitespace. 12.(a)Explainthevariousoperationsperformed onone-dimensionalarrays. Ans: Thevarious operations that areperformed on arrays areas follows, 1. Insertion 2.Deletion 3. Traversal 4.Merge.
  • 17.
    1. Insertion Insertoperationisusedfor insertinganewdataelement at a specificindexin an array. New value can be inserted at either, of the following position, (i) At themiddleorat aparticularpositionofanarray. (ii) Attheendofanarray. (1) Algorithmtoinsert atthemiddleorataparticularpositionofanarray. Toinsertavalueintothearray,thealgorithmgivenbelowusesthefollowingdeclaration, INSERT (array_name, n, insert_POS, new_value) Intheabovedecleration, InsertPOS: indexpositionofarraytoinsert thenewvalue. new_value:new_valuetoinsertinthearray array_name: namegiventothearrayn:totalnumberofelementsthat can be inserted in array. The algorithm is as follows, Step 1: Initialize index [i] to the total number of elements Step2:whileindex[i]>=insert_POS, repeat step3to4untilXgetsprocessed Step 3: SET X[i + 1] = X[i] Step 4: SETi=i-1 [END OF LOOP] Step5: Increasenumber ofelementsn= n+1 Step-6: SET X[linsert_POS] = new_value Step-7: Exit Intheabovealgorithm,step!Declaresthesizeofanarray(n)byassigningittotheindex[i].
  • 18.
    Step 2 executes‘while’conditiontoshiftalltheelementsofarraytotheir next index positions, whoseindex values are greater thanor equal totheinsert position of index to allocate memorytoinsert new element inthearraybyincrementingnby1.Step 6 inserts thenew element valueinthevalueallocatedindexposition. Considerthebelowexampletoinsert avalueintoanarrayInsert (X,6,2,30) (ii).Algorithm to insert value to an existing array Thealgorithmtoinsert valuetoanexistingarrayisasfollows, Algorithm Step1:Performthefollowingactions; Upper_bound =Upper_bound+ 1 Step2:SETarrayX[Upper_bound]=newvalue Step 3: Exit In the above algorithm, step1 is used to increase the size of index by adding 1 to the upper_bound value. This creates and allocates a new empty space at the end of the array. Step 2 is used to assign the new element at the newly allocated empty position of array at index [i]. Consider an example arraywhich is declared as follows, int X[10] ={2,3,4,5, 6, 7} Theupper_boundofthisarrayis5. Thefollowingactions areperformed to insert a new value‘8’atthe endofthearray, (a) Increment the upper bound by1
  • 19.
    (b) Insert thenewvalue‘8’atthenewupperboundi.e.,newlyallocatedemptyspace. 2. Deletion Deleteoperationisusedto removeanalreadyexistingelement fromanarray. The existing elements canbe delete from the array inthe following ways, (i) Deletinganelementfromtheendofarray, Thealgorithmtodeleteanelement fromtheendofanarrayisasfollows, Algorithm Step 1: SET Upper_bound = Upper_bound-1 Step 2: Exit InStep1,Upper_bound valuei.e.,indexvaluethat holdsthelast element in arrayis subtractedby1.Subtractinganupper_boundvalueofthearray automaticallydeletesthe arrayelements holdingbyit. (ii) Deletinganelement from a particularpositionor middleofanarray. Todeleteanelementfromanyparticularpositionfromanarray, eachelement(after the position of deleting element) must be shifted to their preceding index value position.Thesyntax todeletean element from a particularpositionofanarrayis given below, Syntax DELETE(array_name,N,delete_position) Intheabovedecleration, array_nameisthenameofthearrayfromwhichthe element must be deleted.Nisthetotalnumber of elementsinan array. delete_position is the position from which deletion must be done.
  • 20.
    Thealgorithmfordeletionis asfollows, Step1:SETi=delete_position Step2: Whilek=N-1 repeat steps3to4 Step 3: SETX[i] = x[i + 1] Step 4: SET i = i + 1 Step5: SETN= N -1 Step 6: EXIT. Intheabovealgorithm,step1initializetheindex[i]withthepositionat whichthe element hasto bedeleted. Step2 executesa 'while'looptoshift allelementswhich are stored in index position greater than 'delete_position' to their preceding index positionin ordertoocupytheindexpositionofdeleteelement instep 3 and 4. After theelements wereshifted, step 5 decreasesthetotalnumber ofelementsby1. Example 2 DELETE(X,5,2) 3.Traversal Traversal operation is performed on anarray to access each element exactly once. This operation helps in (a) Printingelementsofthearray (b) Determiningthetotalnumberofelementspresent inanarray (c) Calculatingthe sizeofan array, etc.
  • 21.
    Since array isa homogeneous data structure that stores only single type of elements in a linear or sequential manner,Traversal operation can be done easily and quickly. Algorithmfor Traversing an Array Step 1: Initialize index [i] to lower_bound of an array Step2: Whileindex [i]<= Upper_bound, repeat steps 3 to4 until each element of array (X) gets processed Step 3: Process the array X[i] Step4: Increment thevalueofIi.e., I=i+1[ENDofLOOP] Step 5: Exit Here,Upper_boundisthehighest/endvalueofindex[i] Lower_boundisthelowest/beginningvalueofindex[i]. Intheabovealgorithm,step1initializesthearrayindex(i)byassigningit witha lower_bound value. Step2 contains a“while”conditiontoevaluatetheindex value [i]ofarray, andonlyallowstoprocessfurther(step3and4),ifindex[i]islessthanor equal to the upper_bound. Arraytraversingisdoneinstep3,untileacharrayelement canbeaccessedto perform aspecifictask.Step4incrementsorincreasesthevaluetoanarrayindex toaccessthe nextelementofarrayduringnextiteration,untilendofthearrayor upper_bound is reached. 4. Merge Mergeoperationisusedtocombinetheelements oftwoarraysintoasinglearray. In C,merge operationhelpsincopyingtheelements oftwoarraysintoathirdarraysin asequentialmanner i.e.,copyingallthearrayelements ofonearrayaftertheother array. Merging can bedoneon both sorted and unsorted array. Mergingtwounsorted arrays requires nosortingofthethird arrayaftermerging(as theyare notsortedbeforemerging).Butmergingtwosortedarrayrequirestosort thethirdarrayafter merging. Consideredthebelow twoillustration regardingmerging,
  • 22.
    (OR) 12.b)(i)What issearching? Explainindetailaboutlinearsearch.Ans: Searching Searchingis aprocess offindingthecorrect location ofanelement from alist orarrayof elements. In an array, elements arestored inconsecutivememory locations. Searching is done by comparing a particular element withthe remaining elements until the exact match is found. Iftheelement is found, thesearch process is said to besuccessful or elsethe search process is terminated unsuccessfully. The time complexity of searching technique depends on the number of comparisons made to find the exact match.
  • 23.
    Searching Techniques The searchingtechniques can be categorized into two Types, 1. Sequential/Linear search 2. Binary search. Sequential/Linear Search Thesequential/linearsearchmethodismainlyapplicableforsearchinganelement within an unordered list. Theprinciplebehind sequential/linear search is that each element ofthe list iscompared ormatchedwiththekey(i.e., searchargument)inasequentialorder. The search (i.e., comparison) begins from thestarting element andproceeds untila matchis foundortheendoflist isencountered. Ifamatch isfound(i.e.,successfulsearch),the position(i.e.,index)ofthematchedelementisre-turned. Ifamatchisnotfoundbutthe end of list is encountered then1 is returned (i.e., unsuccessfulsearch). AlgorithmofLinearSearch Input n: [i.e.,thenumberofelementsinalist] Index:[i.e, thepositionofelementsinalist] Key[i.e,the element tobesearched] Step1: Initializeindex(i.e.,position) I=0andnumberofelementsinlist=n Step 2: Check, if (I< n) then Gotostep3 else Gotostep5 Step3:Compare,if(keymatcheswithlistelement ati)then printf(“Element found!Successfulsearch”)
  • 24.
    Returntheindex(i)ofthefoundelement Goto step 6else Step4: Increment Iby1 Gotostep2 Step5:printf(“Endoflist; Elementnotfound!Unsuccessfulsearch”) Step 6: Stop. Example Let theelementtobesearchedis‘15’.Thelinear/sequentialsearchalgorithmstartsfrom thefirst element i.e.,4andcomparesit withthekeyelement i.e., 15. Theindexelement isset to‘0’. Since 4≠15,‘i’is moved to the next element i.e., 10. Nowtheelement ati=1iscomparedwiththekeyelement 15. Since 10 ≠15, ‘i’ is moved to the next element i.e., 5. Now,theelement at i= 2iscomparedwiththekeyelement 15.
  • 25.
    Since, 5≠15,‘i’ ismoved to the next element ie., 15. Now,theelementi=3iscomparedwiththekeyelement‘15’. Since,thecurrentelement matcheswiththekeyelement(i.e.,15=15)atlocationi=3,the search is successful andthelocation ofelement‘i’i.e., 3is returned uponsuccess Program #include<stdio.h> #include<conio.h> int linearsearch(int[],int,int); int main() { Int n,A[20], i, key, index; Clrscr(): Printf(“Enter the number of elements in the list:n”); Scanf(“%d”,Cn); Printf(“Enter the elements of the list:n”); for(i=0; i<n; i++) Scanf(“%d”, CA[i]); Printf(“Enterthekeyelementtobesearchedinthelist:n”); Scanf(“%d”, Ckey); index linear_search(A, n, key); if(index==-1) Printf(“Search completed, element not foundn”); else
  • 26.
    Printf(“Search completed, element%dfoundinthelist at position%d”, key, index); getch(); return 0; } Int linear_search(int I[ ], int n, int e) { int i; for(i=0; i<n; i++) if(1[i]==e) return 1; return -1; } Time Complexity : TimecomplexityoflinearsearchisO(n). It requiresatmost‘n’comparisonstosearchan element in a list containing‘ elements 12.(b).(ii)WriteaCprogramtoperformscalarmatrix multiplication. Ans Program
  • 27.
    #include<stdio.h> #include<conio.h>int main() { int i, j,row, col, A[10][10], num; Clrscr(); Printf(“ Enter Number of rows: “); Scanf(“%d”, Ci); Printf(“EnterNumberofcolumns:“). Scanf(“%d”, C j); Printf(“ Enter the elements of the matrix: n”); // Input elements in matrix for(row 0; row <I; row++) { for(col=0;col<j;col++) { scanf(“%d”,C A[row][col]); } } Printf(“ Enter the Multiplication Value:“); Scanf(“%d”, Cnum); for(row=0; row<I; row++)//Performscalarmultiplicationof matrix { for(col=0; col j; col++) { A[row][col] = num*A[row][col]; }
  • 28.
    } Printf(“ The ResultantScalar Matrix is: n”); for(row = 0; row <I; row++) { for(col = 0; col <j; col++) { printf(“%d t”, A[row][col]); } Printf(“n”); } getch(); return 0; } 13.(a) (i)What isa pointer? Explaintheprocessofdeclaringandinitializingapointer. Explain about thereason forusingpointer. Ans: Pointer Apointerisdefinedasa variablewhichholdsthememoryaddressofanothervariable. Example
  • 29.
    int x= 2 Thisstatement will allow the system to locate integer variable ‘x’ and store ‘2’ in that location. If ‘x’ is stored at location ‘ 1210’ by the system, then address of the variable ‘x’ will be‘1210’. Declaration of Pointers Pointers are declared in the same way the variables are declared. But a symbol called precedesthe nameofthevariable. Thisindicates that apointervariablehasbeencreated. Syntax Thesyntaxforpointerdeclarationis asshownbelow, datatype *ptr_name; ‘*’denotesthat ptr_nameisapointervariablewhichgivesavaluestoredat aspecific address. Example int *p Initialization of Pointers Theprocessofallocatingaddressofvariabletopointervariableiscalled as“pointer initialization”. Syntax Thesyntaxforpointerinitializationisasshownbelow, int *P; *P = 6 ; Whentheabovestatements arecompiled, thevariable valueis stored at theaddress pointedbyP. Let‘P’points toanaddress1028. Thus,thevalue6 isstored at thelocation 1028.
  • 30.
    Hence, thevalueofP is‘1028’and*Pis‘6’. Assigning Address ofVariable to PointerVariable Apointervariablepointsto thememory address ofother variables. Example int *P: int a = 6; P =Ca; Here, *P pointsthevaluepresent at location1005i.e., *P =6whichissameasthevalueof‘ ‘a’. Reasons for Using Pointers Thefollowingarethe reasons for usingpointers, 1. Pointersareusedinindirect addressingwhichismost oftenlyused inassembly languages. 2. Pointersareusedindynamicmemorymanagement (i.e.. dynamicmemory allocation and deallocation). 3. Apointer is used to access a dynamically memoryal- located storage. This dynamically allocated storageis called a heap. 4. Thevariablesthat aredynamicallyallocated from theheap areknown asheap dynamic variables.Thesevariablesdonot havetheassociatedidentifiers. Hence, theycanbe referencedonlybypointersandreferencetypevariables.
  • 31.
    5. Useof pointersmakes the codingprocess simple and easy. 6. Pointersareusedtocreaterecursivetypesthat areimportant indatastructuresand algorithms. 7. Pointersareusedtoenhancethelanguage’swritability. 13.(a). (ii) Write a C program for scientific calculator using built-in-functions. Ans: Scientific Calculator Scientificcalculator is defined as a graphing calculatorthat contains mathematical and trigonometricsymbols. It iscapableofperformingmanyarithmetic(i.e..add,subtract, multiplication)andtrigonometriccalculations(modules,sin,tan,d/dxetc)Generally, itis used in many scientifical, engineering and mathematical applications. Program #include<stdio.h> #include <math.h> VoidprintMenu(){ Printf(“ScientificCalculatorn”); Printf(“1.Addition (+)n”); Printf(“2.Subtraction (-)n”); Printf(“3. Multiplication (*)n”); Printf(“4. Division (/)n”); Printf(“5.SquareRoot(sqrt)n”); Printf(“6.Power(^)n”); Printf(“7. Sine (sin)n”); Printf(“8. Cosine (cos)n”); Printf(“G. Tangent (tan)n”); Printf(“0.Exitn”); Printf(“Enter your choice: “);
  • 32.
    } Int main() { Intchoice; Doublenum1, num2, result; Do { printMenu(); scanf(“%d”, schoice); switch(choice){ case 1: printf(“Enter two numbers: “); scanf(“%lf %lf”, snum1, snum2); result = num1 + num2; printf(“Result:%.2lfn”,result); break; case 2: printf(“Entertwonumbers:“); scanf(“%lf %lf”, snum1, snum2); result = num1 – num2; printf(“Result:%.2lfn”,result); break; case 3:
  • 33.
    printf(“Entertwonumbers:“); scanf(“%lf %lf”, snum1,snum2); result = num1 * num2; printf(“Result:%.2lfn”,result); break; case 4: printf(“Entertwonumbers:“); scanf(“%lf %lf”, snum1, snum2); if (num2 != 0) { result= num1/ num2; printf(“Result: %.2lfn”, result); }else{ Printf(“Error: Division by zero!n”); } Break; Case 5: Printf(“Enter a number: “); Scanf(“%lf”, snum1); If (num1 >= 0) { Result = sqrt(num1); Printf(“Result:%.2lfn”,result); }else{ Printf(“Error:Cannot computesquare root ofanegative number!n”); }
  • 34.
    Break; Case 6: Printf(“Enterthebaseandtheexponent:“); Scanf(“%lf %lf”,snum1, snum2); Result = pow(num1, num2); Printf(“Result:%.2lfn”,result); Break; Case 7: Printf(“Enteranangleindegrees:“); Scanf(“%lf”, snum1); Result=sin(num1 *M_PI/180.0); //Converttoradians Printf(“Result: %.2lfn”, result); Break; Case 8: Printf(“Enteranangleindegrees:“); Scanf(“%lf”, snum1); Result=cos(num1*M_PI/180.0); //Convertto radians Printf(“Result: %.2lfn”, result); Break; Case G: Printf(“Enteranangleindegrees:“); Scanf(“%lf”, snum1);
  • 35.
    Result=tan(num1*M_PI/180.0); // Converttoradians Printf(“Result: %.2lfn”, result); Break; Case 0: Printf(“Exiting…n”); Break; Default: Printf(“Invalid choice! Please try again.n”); } } while (choice != 0); Return0; } -------------------------------------------------------------------------------------------------------------- (OR) 13.(b) Explainthepurposeofa functionprototype. Andspecifythedifference between user defined function and built in function. Ans :
  • 36.
    Function Prototype User-defined Function User-definedfunctionallowsusertodefinetheirownfunctionsaccordingtotherequirement of programs. Elements of User-defined Functions Theelementsofuserdefinedfunctionsareas follows, 1. Function Declaration 2. Function Definition 3. Function Prototype 4. FunctionCall. 1. Function Declaration Afunctiondeclarationdeclaresafunctionthat consistsofafunctiontype(or returntype), functionnameparameter(or argument)list andaterminating semicolon. Function declaration is also called function prototype. In C, a function must be declared before it is invoked. Syntax Function-type function-name(parameter-list); Where,parameter-list is a list ofargumentswithdata typesseparatedbya comma. However,it isnot necessaryfortheparameternamestobesameinthe prototype declaration and the functiondefinition, but their types must match. Example Float sum(float x, float y); Thisexampleisafunctionprototypeforthefunctionsum()that takestwofloat arguments and returns a float valueas result. Moreover, functions canevenbe a declared without anyparameter list and the return value. Insuch cases,thefunctionprototypeis written as, Voiddisplay(void); Inadditiontothese,thefunctiondeclarationisreferred asglobalprototypeifitis declared beforeall thefunctions, and localprototypeifdeclared inthefunction definition. Globalprototypecanbe usedbyallthefunctionspresent inthe
  • 37.
    program.Whereas,localprototypeisonlyusedbytherespectivefunctions which contain it. 2.Function Definition Afunctiondefinition isthecompletedescription ofafunction. It specifieswhat a function does and how it performs. It contains a function body (a block of statements) in addition to function name, arguments list and return type. It has thefollowing generalsyntax. Syntax return_type function_name(parameter_list) { local variable declarations; Statements; (expression); } return Example float sum(float x, float y) float z; z= x + y; return(z); } 3. Function Prototype Afunction prototype is a declaration ofa subroutine(or a function) that specifies the function name, an argument list withdatatypes and thereturntype ofa function without the function body. It specifies the function name, the argument list and returntype that a function expects, but it does not specifywhat the function does. Afunctionprototypeisusedtoenforcestrongtypechecking.That isithelpsthe compiler to check whether the data types of arguments passed to a function matchwithwhat the functionexpects.Therefore, everyfunctionshouldhavea functionprototypewhich is declaredinthedeclarationpart ofa program.
  • 38.
    Syntax return-type function-name(parameter-list); Where, parameter-listisa list ofargumentswithdatatypesseparated bya comma. Afunction prototypes ends witha semicolon. It should be given beforemain(). Example Float sum(float x, float y); Thisexampleisafunctionprototypeforthefunctionsum()that takestwofloat arguments and returns a float value. 4. Function Call Afunction can be called withfunction name and a list ofactual parameters. When a function callis encountered, the control is transferred tothe respective function. Then, it is executed and theresultingvalueis returned tothemain function. Afunctioncall Is a postfix expression. Theoperator (..)has highest precedence. Therefore, whenevera functioncalappearsinanexpression, it isevaluatedfirst. Syntax F(…) Here,‘F’representstheoperandorthefunctionname,and(….)indicatesthe operator or theparenthesis set whichconsists of actualparameters.Multiple actual parameters areseparated bycommas. A function can be called in various ways. For example,considera function'mul()'it canbecalledinsixdifferent Ways, (i) Mul(8,6) (ii) Mul(z, 6) (iii) Mul(8, z) (iv) Mul(z+8, 6) (v) Mul(6, mul(z, i)) (vi) Mul(Expressiont, Expression2).
  • 39.
    Here, thefirstthreeexamplesindicatethat mul()iscalled withprimary expressions. Inthe fourthexample,mul()iscalledwithbinaryexpressionz+8as thefirst argument value. The fifthexampleshows that mul()is called withmul(z, i)asitsownfirst argument.Thesixth exampleisthesummationoftheabovefive examples. Example #include<stdio.h> #include<conio.h> #include<math.h> Void Add(); Int main() { Int a, b, c; Clrscr(); Add(); getch(); return0; } VoidAdd() { Int x= 3,y2, z; z= x + y; Printf(“Theadditionofx andyis%d”, z); }
  • 40.
    14.(a) What isa structure? Explain how a structure is defined. Ans: A structure is identical to records which is used to store the data of an entity. It is a user defined data type which can store the data simultaneously. It is also defined as a set of variables of different datatypesthat arestoredundera singlenameThestructureIs defined with a keyword nained ‘struct” and then followed by the name of the structure (structure_name)Thesyntax ofthestructureisshownbelow, Syntax Struct tag_name 1 { Datatypem1; Datatype m2;
  • 41.
    • • • • Datatype mn; }; Here, Struct isakeyword. Tag_nameisthenameofthestructure. m1,m2,…mnaremembersofstructureswhichbelongstoanydatatypelikeinteger, character etc. Definitionofa structureholdsthefollowingsyntax, 1. Specifythesemicolon (;) after closingbracket. 2. Declaretheindividualmembers withtheirtypeand name. 3. Usethenameofthestructurewhiledeclaringthevariableofitstype. Considerthefollowingexamplethat definesastructureofstudent detailscontainingthe data fields name, branch, ageand rollno. Struct stud_details { Char name[20]; Char branch[5]; Int age; Int rollno; }; Thisstructurespecifiesatemplatethat displaysthedataasfollows,
  • 42.
    Thedata fields name,branch,ageandrollno arecalledmembersorstructureelements. Themembers may belongtodifferent data types.Structurename i.e., stud_details is also known as structure tag that maydeclare structure type variables later. Since,thestructureisauserdefineddatatypethevariablewhichisdeclaredinastructure areknownas membersofthestructure. Theabovestructuredeclarationdoesn’t require any memory (or) storage space. It only specifies storage or structure with in memory. Besidesthis,typeofdeclarationprovidedetails ofthemembernamesdefinedwithina structure. However,thememoryallocatedtostructuresisdoneondeclarationofits variables. Thefollowingprogramillustratesanexampleofstructureinc Program #include<stdio.h> #include<conio.h> Struct EmployeeDetails { Char*name; int id, age; }; int main()
  • 43.
    { StructEmployeeDetailse; Clrscr(); e.name=“John”; e.id=5678.; e.age=26;printf(“nEmployeeNameis %s”,e.name); printf(“nEmployee Idis: %d”,e.id);printf(“nEmployeeAgeis%d”, e.age); getch(); return0; } (OR) 14.(b). (i)Explainindetailabouttheconcept ofarrayofstructuresalongwithan example program. Ans: Theprocess ofgrouping a set ofdistinct structurevariables intoonearray is referred toasan arrayofstructures. Thisorganizationwhenthereisa need ofdeclaring distinctvariableintooneisreferredthatis,forexampleconsideranthathas different departmerits and eachdepartment hascertain numbermucturefor every
  • 44.
    employee, it iseasytodefinea singlestructureforalltheemployees ofan organization. of employees, insteadofdefiningaseparate Syntax struct struct_name { data_typemember_name1;data_type member_name 2; • • • Data_type member_name n: } struct struct_name struct_variable [index]; Intheabovesyntax, struct isakeyword struct_nameisthenameofthestructure and data_type member_name 1,................arethemembersofthestruture. struct_variable [index];isthenameofthevariablewhichisoftypestructand [index]representsthe total number ofelements present in an array. Example struct employee { charemp_name[20]; int emp_id; float emp_sal; }; struct employeearray_employee[4]; Intheaboveexample,array_employee[4] representsan arrayof4 elementswhichare oftype "struct"(i.e..struct employee array, employee[4]:) employeerepresents thestructurevariable [4] representsthe[index] The above example is diagrammatically represented as follows,
  • 45.
    Here, Array_employee[0]pointstothefirst element ofanarray.Array_employee[1] pointstothesecondelementofanarray. Similarly, Array_employee[3]pointstothethirdelementofanarrayAn arrayof structurewith15 employee is declared as. Struct employee emp [15]; Inordertoassignvaluestotheemployeewhichisstoredatposition10iswrittenas. Employee[10].Name=“John”; Employee [10]. Id = 666; Employee[10]. Salary= 15000; Here, the array subscript ([]) is used first followed by a dot (.) operator. Initializing Array of Structures Thearrayofstructureis initialized asfollows. Struct struct_namestruct_variable[N]= {{const01, const 02, …….const0n},{const 11, const 12, const……,const1n},…..{constN1,constN2,……, Const Nn}}; Here, struct is a keyword, struct_nameis nameofstructure.
  • 46.
    Struct_variableisthestructurevariableand const 01,const 02 canbeint, char, floatingpoint constants. Example Struct employeeemp[2]={{“John”,666,20000},{“Dennis”, 777,250001}}; Here, Employeeisstruct_name emp is struct_variable [2] representstheindex[N]. Program #include<stdio.h> #include<conio.h>int main() { Struct employee { Char name[50]: int id_no: int salary:}; struct employee emp[25]; int n,I; clrscr(); printf(“n Enter the number of employees: “); scanf(“%d”,Cn); for(i=0;i<n;i++) { Printf(“Enterthenameofemployee:“);scanf(“%s”,Cemp[i].name); Printf(“ Enter the id_no of employee: “); scanf(“%d”,Cemp[i].id_no); Printf(“ Enter the salary of employee:“); scanf(“%d”,Cemp[i].salary);
  • 47.
    } getch(); for(i=0;i<n;i++) { Printf(“Detailsof%dEmployee n”,i+1); Printf(“NAME = %s n”,emp[i].name); Printf(“ ID_NO= %d n”,emp[i].id_no); Printf(“SALARY=%dn”,emp[i].salary); } getch(); return0; }
  • 48.
    14.(b).(ii) Whatisaself-referentialstructure?Discussitstypeswithexampleprograms. Alsolist down its applications. Ans: Self Referential Structure Aselfreferentialstructureisdefined asastructureinwhichthereexistsaself reference (i.e., a reference to the data of similar type) apart from the reference to other data. This structure acts as the basefor various data structures including thelinkedlists,treesand graphs. It hasthefollowingsyntax, Syntax Struct tag {
  • 49.
    typeldata1;type2 data 2; • • • typendata n; Structtag*ptr; }; Intheabovesyntax,‘ptr’referstothenameofthepointervariable.Here,astructureoftype ‘tag’willincludea memberwhichpointstosomeother structure having its type as tag. Thefollowing examplerepresents a selfreferential structure, Example Struct node { Char item [15]; Struct node*ptrnode;}; Theaboveexampleconsistsofastructurenamedstudent,whichconsists of three members. Thefirst memberis a 50-element arrayofcharacters called ‘name’,second memberis‘rollno’oftypeint,andthelast memberisaself referentialstructurenamed ‘Ptr’ In general,theself-referentialstructuresaremainlyusedintheimplementation oflinked data structureslikelists,treesetc. Consideranimplementationoflinked-lists. Alinked list isadatastructuresthat contains a set ofnodes, whereeachnodepoints totheimmediatenodeinthe list.
  • 50.
    In a linkedlist, cach node consists oftwoitems, one containing a pointer tothe data and theother containingtheaddressOfthenext element. Hence, theorder ofnodes canbe alteredbychangingthepointer. Moreover, thedata canbe insertedordeletedbychanging thepointer.Therefore,usingalinkedlistthedata structurecan easilybeexpanded or consized dependingontheneeds. In a linked list, nodes represent self-referential structure and the arrows represent pointers that makes a linked list a self- referential structureConsider thefollowingexampleofa linked list. Theaboveexamplecontains a linkedlist having three objects, everyobject contain two itemsi.e.,a characterstringandapointertonextobject ofthelist.Thestaringofalistis representedusingaseparate pointer.Itisrepresentedusingthelabe“begin’.Theendofthe list is represented using a cross. Herethe objects represent theself referentialstructure. Ingeneral,aself-referentialstructurecanbeoftwotypes,thatis, 1.Self- referentialstructurewithsinglelink 2.Self-referential structure with multiple links. 1. Self-ReferentialStructurewith SingleLink Astructurethat containsa singleselfpointerasitsmemberisreferredasaself-referential structurewithasingle linkThefollowingfigure illustratesthewayintheobjectsofaself referentialstructurewithsinglelinkare connected. Theabovefigureconsistsoftwoobjectswhichcontainsasinglelinkbetweenthem.The following programillustratesa selfreferentialstructurewitha single link.
  • 51.
    Program #include<stdio.h> #include<conio.h Struct node { int d1;int d2; Struct node*LINK; }; main() { Struct node ob1 Struct node ob2; Clrscr(); ob1.LINK NULL; ob1.d150; ob1.d2 = 60; ob2.LINK- NULL; ob2.d1 = 70: ob2.d2 = 80; ob1.LINK =Cob2; printf(“n%d”, ob1.LINK->d1); Printf(“n%d”,
  • 52.
    ob1.LINK->d2); getch(); return 0; } 2.SelfReferentialStructurewith MultipleLinks Asstructurethat containmultipleselfpointermultiplereferred as a selfreferential structurewith multiplelinksasicallyusedtobuilt variouscomplexdatastructures. In general, thistypeofstructure canconnect multiplenodesat astanceoftime. The followingfigurerepresentsaselfreferential structurewithmultiplelinks. Theabovefigureconsistsofthreeobjectswhichcontainsmultiple linksamongthem. The followingprogram illself referentialstructurewithmultiplelinks. Program #include <stdio.h> #include <conio.h> Struct node { intd; structnode *REV; struct node*NEXT
  • 53.
  • 54.
    } Main() Struct node object1; Struct node object2; Struct node object3; Clrscr(); object1. PREV=NULL; object1. NEXT = NULL:; object1.d=70; object1.PREV = NULL; object2. NEXT=NULL; object2.d=80; object3.PREV= NULL; object3. NEXT=NULL; object3.d=90; object1.NEXT=Cobject 2; object2.NEXT = Cobject3; object2.PREV= Cobject1: object3.PREV=Cobject 2; Printf(“n%dt”, object1.d); Printf(“%dt”, object1. NEXT>d); Printf(“%dn”, object | NEXT>NEXT->d); printf(“%dt”, object2.PREV->d); Printf(“%dt”, object2.d);
  • 55.
    Printf(“%dn”,object2.NEXT->d); Printf(“%dt”,object3.PREV->d); Printf(“%d”,object3.d); getch(); return 0; } Intheaboveprogramobject1,object2,object3aretheobjectsofselfreferentialstructure“node”, they are joined usingmultiple links so that accessing each other’s data becomes easy. Thisbecomesthe advantageofselfreferentialstructures. Applications of a Self Referential Structure Thevariousapplicationsofaselfreferentialstructurearelistedbelow, 1.Stack 2.Linkedlists 3.Graphs 4.Queues 5 Trees.
  • 56.
    15.(a)Explainaboutthevarioustypes offiles inC.Ans: AStreamreferstoasourceordestinationofthedata. Itiseither attachedtoaterminal(i.e., anyphysical device) or an auxiliarymemory file. Cprogramminglanguagetypicallysupportstwotypes offilesi.e., a textfilesand a binary files. TypesofFiles 1. Text Files Atext filestores data onlyintheform ofcharacters. Thenon-characterdatatypes cannot bedirectly storedinthetext filewithoutconvertingthemintoasequenceofcharacters. Input/Output functions can be used to convert non-character datatypes to characters while writing into the text files. If input has to be read from a text file, it is read in the form of character sequence. Converted totheir appropriateinternal formats and arethen stored in memory. Theconvertingfunctioncanbeoneofthefollowingthreetypes,
  • 57.
    (i) Formatting I/Ofunctions (ii) Character I/O functions (iii) String I/O functions. (i)FormattingI/OFunctions In case of reading an input, formatting I/O functions convert the series of input characters to standard types. On the other hand, while displaying the output, standard datatypes are converted to sequence of characters. Example Scanf(), printf(). (ii)Character I/O Functions Thesefunctionscanreadorwrite onlyonecharacterat atime. Example getchar(), putchar(). (iii).String I/O Functions These functions can read or writestrings ofcharacters. Example fgets(), fputs(). Someofthefeatures oftext filesareasfollows, (i)Intext file,data isstoredin thehumanreadableform. (ii) A new line character (n) is used to terminate every line of data in the text file. (iii) Aspecialcharactermarkercalled“EOF”(End-Of-File)isusedtoindicatetheendof a file. 2.Binary Files
  • 58.
    A binary fileis a collection of bytes. This collection is a compiled version of a C program (E.g: programl.exe),ormusicdata storedina wavefileora picturestored ina graphicfile. In contrast to text files in a binary file, the data is stored in the internal format of computer, the format similar to that of memory. Binary streams also called as block I/O functions are used for reading and writingbinary files. Someofthe features ofbinary files areas follows, (i) Nonewlinecharacterisusedtoindicatetheendofaline. (ii) Inbinaryfiles,dataisstored inthemanner similar tothatinmemory. (iii) Liketext files,binaryfilesalsouses“EOF”markertoindicatetheendofa file. (OR) 15.(b)Explaininbriefabout sequentialaccessfiles. Ans: Sequential access fileenablestheuserstosequentially accessthewhole(or)part offile. It is different from random access where in, the user can visit only the required file which they want to access. But, in sequential access, theuser need to visit all thefiles i.e., n-1
  • 59.
    filesinordertoaccess n’hfile. Therefore,it can besaid that,sequentialaccess file consume relatively much (more) access time. Sequentialaccessfilecanbeaccessedusingthefollowingfunctionsthat areavailablein I/Or library. 1. fopen() 2. fclose() 3. fprintf() 4. fgetc()5. fputs(). 6. 1. fopen() Thisfunctionisusedto openthefile Syntax Handle=fopen(filename,mode); In the above syntax, handleisanpointerthat referstoafile.fopenisa open function. filename andmodearethetwo string arguments. 2. fclose() Thisfunctionisusedtoclosethefile Syntax fclose(handle); Intheabove syntax, fclose is a function and, handle is an argument. 3. fprintf() This function is used to print/write the text to the file.
  • 60.
    Syntax Fprintf(handle, “text”); Inthe above syntax, handle is an argument and, text is (string) used toprint thetext inanfile. 4. fgetc() Thisfunctionisused to read thetext character atansingleinstanceoftime. Syntax Ch=Fgetc(handle); In theabovesyntax,inchisancharacter datatypethat referstoa file. Fgetcis anget character functionand,Handle is an argument ofthefile. 5.fputs() Thisfunctionisusedtowritethetextsequentially alongwithanargumenttoafile. Syntaxfputs(“next”,handle)Intheabovesyntax, Text is a string used to write the text to a file and, handle is an argument. Program #include<stdio.h>//headerfilesection Typedef struct { Int id; Char name[25]; Intmarks1,marks2,marks3; } STD; STD s; Void display(FILE *);
  • 61.
    Intsearch(FILE*,int); Void main() { Int i,n,id_key,opn; FILE*fp; Clrscr(); Printf(“Enterthenumber ofrecords“); Scanf(“%d”,Cn); fp-fopen(“stud.dat”,”w”); for (i=0;i<n;i++) { Printf(“ReadtheInfo ofStudent: %d(id,name,marks1,marks2,marks3) n”,i+1); scanf(“%d%s%d%d%d”,Cs.id,s.name,Cs.marks1,Cs.marks2,Cs.marks3); fwrite(Cs,sizeof(s),1,fp); } fclose(fp); fp=fopen(“stud.dat”,”r”); do { Printf(“Press1-Displayt 2-Searcht 3-ExittEnterYourOption”); scanf(“%d”,Copn); Switch(opn) { Case1:printf(“nStudent Recordsinthe File n”); display(fp); Break; Case2: printf(“Readtheidofthestudent tobesearched”); scanf(“%d”,Cid_key); If(search(fp,id_key)){ Printf(“ Record found in the filen”); Printf(“%dt%st%dt%dt%dn”,s.id,s.name,s.marks1,s.marks2,s.marks3); else
  • 62.
    Printf(“RecordwithUSN%disnotfoundn”,id_key);break; Case3: printf(“Exit!!Pressanykey”); getch(); break; default:printf(“ Invalid Option!!! Try again! n”); break; } } while(opn != 3); fclose(fp); } void display(FILE *fp) //display function section { rewind(fp); while(fread(Cs,sizeof(s),1,fp)) printf(“%dt%st%dt%dt%dn”,s.id,s.name,s.marks1,s.marks2,s.marks3); } int search(FILE *fp, int id_key) //search function section { rewind(fp); while(fread(Cs,sizeof(s),1,fp)) if(s.id=id_key) return 1; return 0; }
  • 63.
    PART–C 16. (i) WriteaCcodingfortransactionprocessingusingrandom accessfiles. Ans: Program #include<stdio.h>struct clientData { Unsignedint acctNum; Char lastName 15]; Char firstName[ 10 ]; double balance;};
  • 64.
    Voidmain() FILE *cfPtr; Struct clientDataclient {0,“”,“”, 0.0 }; Clrscr(); If ((cfPtr fopen(“C:Turboc3BinProjectcredit2.dat”, “w”))=NULL) { Puts(“Filecouldnot beopened.”); } else { Printf(“Enteraccountnumber”“(1to100,0toendinput)n”); scanf(“%d”, Cclient.acctNum); While (client.acctNum != 0) { Printf(“Enter lastname, firstname, balancen”), Fscanf( stdin,“%14s%9s%If”, client.lastName, client.firstName, Cclient.balance); fseek(cfPtr,(client.acctNum-1)*sizeof(structclientData), SEEK_SET); fwrite(Cclient, sizeof( struct clientData), 1, cfPtr); Printf(“Enter account number’n”); scanf(“%d”, Cclient.acctNum); } fclose(cfPtr); } getch(); return;}
  • 65.
    16.(ii).WriteaCprogramtocomputemodeforanarrayofelement. Ans: Mode Mode isdefined as anobservation that occurs most frequency inthe data. This measureof central tendencyisusedincaseof nominalor higherorderscales. However, it isnot appropriatetousemode forordinal orintervaldata unlessthedata is grouped. Example Considerthenumbers,10, 10,11,12,12,12,14,15,15.Themodeofgivennumbersis{12}. Program #include<stdio.h> #include<conio.h> Void main() { Int I,j,A[50], B[20],k,num,mode_value; int c=1,max=0; Clrscr();
  • 66.
    Printf(“Enter the totalnumber of elements: “); Scanf(“%d”,Cnum); Printf(“Enter the numbers: n”); for(i=0;i<num;i++) { Scanf(“%d”,CA[i]); } for(i=0;i<num-1;i++) //Loop to calculate mode { mode_value=0; for(j=i+1;j<num;j++) { If(A[i]=A[j]) { } Mode_value++; } If((mode_value>max)CC(mode_value!=0)) { k=0; max=mode_value; B[k]=A[i]; k++; }
  • 67.
    elseif(mode_value=max) { B[k]=A[i]; K++; } for(i=0;i<num;i++) { If(A[i]-B[i]) C++; } If(c=num) printf(“ No mode”);else { Printf(“The Mode is: “); for(i=0;i<k;i++) Printf(“n%d”,B[i]); getch(); return; } }