You are on page 1of 39
Shrichakradthar.com a MCS 201: Programming In C and Python Guess Paper-1 Q. Explain the basies of algorithms? Ans. The word Algorithm means “a process or set of rules to be followedsig ealulations or other problem-solving operations”. Therefore Algorithm refers to a set of rules) ifstrudons that step-by-step define how a work is to be executed upon in order to get the expected results. Zatch ed ‘pobianine expects ut tom never ot It can be understood by taking an example Of dokihg a new recipe Tp cook a new recipe, one reads the instructions and steps and executes them/ene by one, in the given sequence. The result thus obtained is the new dish cooked perfectly. Similarly, algorithms help to do tak in programming to get the expected output. The Algorithm designed is language“independéntpi® they are just plain instructions that can be implemented in any language) and yet the output will be the same, as expected Characteristics of an Algorithm: ASOne, would not follow any written instructions to cook the recipe, but only the standard one. Similarly, not all written instructions for programming is an algorithm, In order for some instructions to be an algorithm, it must have the following characteristics © Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its steps should be clear in all aspects and must lead to only one meaning. ‘+ Well-Defined Inputs: Ifan algorithm says to take Inputs, it should be well-defined inputs. 2 Guess Paper + Well-Defined Outputs: The algorithan must clearly define what oulpat will be yielder and a should be well-cefined as well + Finite-ness: The algorithm rrust be ficite, ie itshould notend np in an infinitednops or sirrilar # Feasible: The algorithen must be simple, generic andi practical, such that st can bassecated upon ‘nth the available resources. It reust not contain some future technology, o#anithing. + Language Independent: The Algorithm designed must be language-indepandent, ie it must be just plain instructions that can be ireplemented in any language, ard yébthe output vill be sarre, asexpected Advantages of Algorithms: + Triseasy to understand # Algorithn isa step-wise representation af a solution to a given prébalen: + In Algorithen the problem is becken down into smaller pigozs of steps hence, itis easicr for the programmer to convert itinto an actual program. Disadvantages of Algorithis:- © Writing an algorithm takes a long time so itis timasdoasianing, + Branching and looping statements are dificult to Shaky in Al goritars Q Describe the symbols used in designing of tlowehiant? ‘Ans. Flowcharts use special shapes to represent dliflesent tfpes of actiGhWlor steps in a process, Lines and arrows show the sequence of the steps, and the calahtoeBhips arrong them These are knawn.as flowchart symbols Coreenon Flowchart Syenbols: Rectangle Shape - Represents a process Ovallor Pill Shape - Represents the start or end Diamond Shape Represents a decision Parallel ogram ~ Repesentsiinputiout pues sin ing etn £ Stara D 4 or eed pein —- | eiiaEaaane — Rowe oot i eee cee PO _ Pel Prenrons | ap tet ae te Fn | hg =e baa || emg Let's glen each flowchart symbol individually Shrichokrodbor.com a Start/End Symbol: The terminator symbol marks the starting or ending point of the system, It usually containsthe wor "Start"or "End." me UCUs Action or Process Symbol: & box can represent asingle step ("add two ct 1"), of and entire sab- process ["inake bread") within a larger process, ms Document Symb ol: A printed document or sepo: Multiple Docaments Symbol: R int: Lines representing different decisions emerge from tt Symbol: Represents material or information entering or leaving the system, such as der (input) or a product output), Guess Paper . Mansa ipo! Symbl: Representa step uber users prompts “ie presents. set-up to-anothes step in the &, S © S Connector Symbol: indicates that the fo ing symbol (containing the same letter) has been placed. @: (Or Symbol: Inciicates that theypracess flow esntinies in mare than two branches oo jon Symbol: Indicates a point in the flowchart where multiple branches converge back process, Siricrokradtrarcom 5 Merge Symbol: Indicates a step where two ov more sub-lisisor sub- processes become one. Collate Symbol: Indicates a step that orders information into a standard: se) + Sort Symbol: [ndivates a step that organizes a list of wh Pan ®. fon some pre- determined criteria, af Subroutine Symbol; Indicates a sequence rota specific task embedded within a sagen prose. Tha saquanes of actions “i son sopra fecha, Manual Loop Symbol: hs GQ... that veill continue ta repeat until stopped 4 Loop Limit Symbol: Indicates 6 Guess Paper ‘Data Storage or Stored Data Symbol: Indicates a step where data gets stored. Database Symbol: Indicates a list of information with a standard structure sorting: Internal Storage Symbol: Indicates that information w. in program, used in. e © Display Symbol: indicates a step that lion guage. It was initially developed by Dennis Ritchie in the year programming language to write an operating system. The level access to memory, a simple set of keywords, and a clean Modularity General-Purpose Language + Statically Type + Richset of built-in Operators Shrichakradhar.com 7 Libraries with rich Functions Middle-Level Language Portability Easy to Extend Let us see the features one by one: Procedural Language: In a procedural language like C step by step prédefined instructions are earried out. C program may contain more than ene function to perfofiie parlicular task. New people to programming will think that this is the only way a partiailar programming language ‘works, There are other programming paradigms as well in the programing world. Mast of the commonly used paradigm is an object-oriented programming language. Fast and Efficient: Newer languages like java, python offer moresfeatures than ¢ programming language but due to additional processing in these languages, their performance rate gets down effectively. C programming language as the been middle-level language provides programmers access to direct manipulation with the computer hardwar@but higheflevel languages do not allow this. That's one of the reasons C language isi¢0fsidered the first, choike to start learning, programming languages. It’s fast because statically typed languages-are faster than dynamically typed languages. Modularity: The concept of storing C progtdmming! language code in the form of libraries for further future uses is known as modularifgisThis programmingélangtrage van does'very little on its own most of its power is held by its librarie’oC language has its awn library to solve common problems like in this we can use a particulanfunction by sising a Reader file stored in ils library Statically Type: C programming langilage I a statically typed language. Meaning the type of variable is checked at the time of compilation but not at fun time. This means each time a programmer type a program they lave ta mention thétype of variables used. General Purpose Language: Fram) system programming to photo editing software, the C programming language is usefl in Various applications: Some of the common applications where it's used are as follows Operating systems: Windows, Linux, 05, Andibid, OXS, Databases: PostgteSQUy Ofatle, MySQU) MS'SQL Server ete. Rich set of built-in Operators: It isa diversified language with a rich set of built in operators whiclyaf@used! in writifff compl&x or simplified C programs. Libraries with rich Functions: Robust libraries and functions in C help even a beginner coder to code with ease, Middle-Level Language: Asiit is dlmiddle-level language so it has the combined form of both capabilifies of assembly langualgeand features of the high-level language Portability2G. language islavishly portable as programs that are written in C language can run and compile on any system witheither none or small changes, Easy to Extend: Programs vwrilten in C language can be extended means when a program is alfeadyiwritien in it then some more features and operations can be added ta it: correctly or makes typos. In other words, syntax errors occur when a programmer does not follow the set of rules defined for the syntax of C language. SymiaX ertbrs are sometimes also called compilation errors because they are always detected by the compilér, Generally, these errors can be easily identified and rectified by programmers. ‘The most commonly occurring syntax errors in C language are: Missing semi-colon () Missing parenthesis (0) Assigning value toa variable without declaring it 8 Guess Paper Letustake wn oample to understand qmtecenae gineudecetdis > void maint) { var = 5; ff we didnot declaze the date type oF variable Print ("The variable is: Wa", var); i Outputiexeex: ‘var! undeclaxed [fiter use in this function} H the user afsigne any value to a variable without defining the data type pf thiratiable, the compile heowsa nyntec ear. Semantic Exsor: Exvoes that occur becanse the connpslay is unable to understand the written code ate called Semantic Emons. A semantic enor wall begenaaled if the cade indkas no sanseto the compile, even though it is apntactically comedt It islikeusing the wong woxd inthe mong place in the English language For example, adding 2 string to an integer wall generate asemantic sre Semantic ears are different from syntax errars, as syntax axorsisignify thatthe structure of a program is incomect without consideing itr meaning, On the other hand, senanlis erivrs Signify the incon: saaplementation of a program by considaing the meaning ofthe paige. Themost commonly scouring semanlic mrors-are use of urinililized wariubles, type comp athilly, ama axsy index out of bounds Buample 1 tindudecetaio -h> void maint) { int 2, bo! ath acy ff This ofl genexate a semantir Setee + Output exror: value reqiredias Left operand of assignment When we have an expression on the Idt hand aide of atvassigtiment operator i the program generaies = semanlit «nan Evan thoughthe codeis ayntacticdly. oat, the ccmplledtow not understand the code, Q. Desaibethe process of compiling and sunning the € program? Ans. Cis amid-lerel language ad needs 2 sempiluzto convert if into am exerutable code sa that the progvam canbe ran on our arachine How do compile and sims C paiierames “Balu wethe steps we useion an Ubuntu machine wl thigce compile: ees tnt rte Whetistmeates C program using aneditor and.cwrethebles: flonase Sviillenime-e The disgtacs on tight choos a ssnple progeanits ald te numbers Shrichokradhar.com El me 2 Ones Q Booster Doses Then compile it using below command. $ gee -Wall filename.¢ ~0 filename: ‘The option -Wall enables all compilers’ warning messages. This option isq€omhended to generate better code. The option -o is used to specify the output file name. If we do not use this option, then an output file with name aout is generated Meee rue ad ‘After compilation executable is generated and wesfumn thBigenerated executable using below command 8. /filename What goes inside the compilation process? Compiler converts a C program into an exegitdble ‘There are four phases for a C program to become an executable Pro-processing, Compilation Assembly Linking By executing below command/ we ger the all iftterm@tiiate files in the current directory along with the executable Sgec -Walll -save-temps filename.c -0 filename, ‘The following screenshot shows all generated intermrediate files. Onwer Boe » & Donel 3 2 OB tienes Lefts one by one see what these intermediate files contain. Presprocessing: This is the first phase through which source code is passed. This phase includes: © (Removal of Comments ‘© Expansion of Macros © Expansion of the included files, © Conditional compilation ye 2 2 0 Guess Poper ‘The preproceised output is stored in thefilename Lets see whats inside flmane wings filename In the above output, source file i filled with lots and Lots of info, but at the end our code is preserved Analysist print contains nowa +b rather than add a,b) that’s becmse macros have expanded. Comments are stnpped off. #indude is missing instead we seelots of code. So header files has beenleipandéd and incuded in our somree file Compiling: The net step is to compile filename and produce an; intetinédiate compiled output filefllenamess. This file isin assembly level instructions, Let's seethrough thisfile using $i fllenamess ‘The snap shot shows that itis in assem bly language, which assembler can understand Assembly: In this phase the filename sixtakenas input and/tumed intofilenamew by assembler, This file contains machine level instructions. At this phase, only etisting code is converted into machine language, the function calls lke printifj are natresolved. Let's ew thie fle using $l fllename. Linking This is the final phase imvtohich all the linking of function calls with their definitions are done Linker knows sahiere all these finctionsare implemented, Linker does some extra work also, itadds some extra code to our'program which ie tegitired when the program starts and ends, For example, there is a code which required for setting up the environment like passing command line arguments. This tak can be eadily vetified by using $size filename and $size filename. Through these commands, we know thatyhew oniput file increases from an cbject file to an executable file. This is because of the extra code that linkerd ds with our program Shrichokradhar.com Step 4: Click on Run or press Ctel + F9 to run the code, Yes, C programs are firstl@ompiled to generate the object coce and then that abject code is run. Run C Program Without using any IDE: If you do not wish to set up an IDE and prefer the old school way, then dowload the C compiler which is called gec from the GCC website htips//gce gnu H Once you have downloacled arte installéd the gc compiler, all you have to do is, open any text editor, copy and paste the C program code forC Hello World Program, and save it with the name the helloworld.elike any other file you save with a name. Now, OpenCommand prompt or Terminal (if you use Ubuntu or Mac OS), and go to the ditectory where you have saved the helloworld.e program fle ‘Type the command gce hel1o.c to compile the code. This will compile the code, and if there are no errorstthen it will produce an output file with name a, out (default name) Now, fo run the program, type in./=. out and you will see Hello, World displayed on your screen. $ gcc helloc $ Ja. out Copy Hello, World n Guess Paper Q. Differentiate between keyword and identifiers? Ans. | Keyword isa pre-defined word, ‘The identifier isa user-defin Itmust be written in a lowercase letter, It can be written in bo} and uppercase letters. lis meaning is predefined in the c_ Itsmeaning isnot defined in the ecompilee compiler. a a “It is a combination of alphabetical tis a com iphan acters. | characters, Tt does not contain the underscore | tt =e character | ae gS intmaing) A int A-20; fy print f("Value of ais :%d".a); print f("\nValue of A is :%dA);, retum 0; 1 Output Value of ais: 10 Value of A is: 20 ‘The above output shor conclude that the id 1 variables, ‘a’ and ‘A’ are different. Therefore, we program may not alter during its execution. These fixed values are a Constants: any of the basiciata types like an integer constant, a floating constant, a character © g literal. There are enumeration constants as well. ated just like regular variables except that their values cannot be modified after their als: An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the ‘base of fadix: Ox or OX for hexadecimal, 0 for octal, and nothing for decimal. ‘An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order Here are some examples of integer literals ~ 22 Legal Shtichakradhar.com 8 2i5u Legal */ OxFeeL —/* Legal */ 078 "illegal: Bis not an octal digit 032UU__/* Illegal: cannot repeata suiix™®) Following are other examples of various types of integet literals ~ 85 decimal */ 0213 octal) Oxtb hexadecimal * 20 print */ Ou /* unsigned int */ 301 /#long*/ Boul unsigned long") Floating; point Literals: 4 ‘loaling;point literal has an integer pas & détimual point, a fractional part, and an exponent part. You can represent floating point literals either imdecimal farm or exponential form. While representing decimal form, you must include the decimabpoint, the exponentor both; and while representing exponential form, you must include the integer part, the fractional past, OF both. The signed exponent is introduced by ¢ or E. Here are some examples of floating-point literals — 3.14159 /* Legal *? BIAISOESL Legal */ SIE illegal: incomplete exponent* 210f Illegal: no decimal or exponent */ 655 _/*Illegal: missing integer or fraction af Character Constants: Character literals are enclosed in single quolespeg, x’ can be stored in a simple variable of char type ‘A character literal can be a plain characté (eg. 'x), an escape sequence (e.g, '\E), or a universal character (eg, "w02coy There are certain characters in Glthableepresent special Hieaning when preceded by a backslash for example, newline (\n) ot tab (\ Following is the example to shaw a feW escape sequetigeecharacters #include-stdioh> int mainOl . . printf ("Hello \tWorld \niin’): : return0; | ‘When the abowecode fs compiled and exeputet, it produces the following result ~ Hello World String Literals: String literals of constants are enclosed in double quotes "A string contains characters that are similar fo character literalsiplain characters, escape sequences, and universal characters. You can break a longline into multiple lines using string literals and separating them using white spaces. Here are some &xaimplcs of string literals. All the three forms are identical strings. “hellgpdear™ “ello Q. Describe the operator precedence/priority? Ans. Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. CS Guess Paper For example, x=7 + 3*2; here, xis assigned 13, not 20 because operator * has a higher precedence than +, soit first gets multiplied with 3"2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those withthe lowest appear at the bottom, Within an expression, higher precedence operators will be evaluated fi | Category Operator Associati | Postin lon>.+- “< | Unary +-1-++ ~~ type)" & sizeof | Mulipictive |" Gs. “Biwi AND | & “bitwise xoR* “piwwiseoR | & | Logical al Logical ©! Condi * Shichakradbor-com 15 (Q. Explain the various decision making statements in C? Ans. Decision making siructures require that the programmer specifies one o mere conditions to be evaluated or tested by the program, along with aslalement or statements to be executid if the eordition is determined to be true, and optionally, other statements to be executed if the condition tedeiernined to be false Show belowis the general forsn of a typical decision making structure found in sfeatol the programming languages tf condition W condition tetra is falaa © C programming Tanguage assumes angnin-zeroand n@n-nil values astrug, and if it as either 2ero ornull, then stisassumed as fale: value rogramming language provides the followingitypes of desision making statements, Se.No. Statement & Description 1 sf stateraent Anifstatemert consiat#iifa Boolean exitesiorifellowed by one or more statements 2 if. else statement Arif staterngnt can Be followed! by:anoptional else statement, which executes when the Boolean expressiginis false 3 nested if statements Yow eatase out for elge if sitemgent mside another if or else af statement). 4 switetistaternent Avgwiteh statement allowed variable to be tested for equality against « list of values 5 Asted switch statements ‘You can use one switch staternentinside another switch statement(s) It Statement: The if statement is used to check some given conditicn and perfor some operations depending upon the comectness of that condition. It 38 mostly used sn the scenario wher we need te perfosm the different operations fer the different conditions, The syntax of the if statement is given below if(expression)| ifeode to be execvted 16 Guess Paper t Flowchart of if statement in C: False Tre Let's see simple exemple of C language if statement finclude catdio ho int maind)| int number=; printff"Enter a number), sand" aernamber), if(eurnber£2-=0)} printf{ "ed is even number"smumbie 1 retum 0; ' Output: Enter @ number 41s ever number enter a number'S IGelse Statement: Thesf-els> statement is used to perform two operations for @ single condition, The if- clse statement is ahtjaxiension to theif statment using which, wre can perform two differant operations, i.e, one is for the coeBcness of thakesindition, and the other is for the incorreciness of the condition. Here, 2 must otice that if and elie block cannot be executed simultaneously. Using if-else statement is always prefefible since it always invokes on otherwise case with every if condition, The syntax of the if- else statement is given below. i (eXpression)} ‘iigode to be executed if condition is true Jelsel, Heode to be executed if condition is false t Flowchart of the if-else statement in C: Shrichakredbar.com 27 Let's see the simple example to check whether » fuimber is)even or odd/using if-else statement in C language. : finclucie int main()| int sumber-0; peinti'enter a umber"): seans{"%d,Snumber); if(rumber%2=-0)) prntf"So is even number" number); } ; else| printif'Sed ig odd number" muna ' return G; ! Output: enter a number: Ais even number enter a numbers Sis odd number If else-if ladder Statement: The ifelseif ladder statement is an extension to the if-else statement. It is used inthe seeharic where there are multiple cases to be performed for different conditions, In if-else-if ladder stalemest, if « condition is true then the statements defined in the if block will be executed, ott@ririse if some other condition is true than the stetaments definaddin the elseeif block will be executed, at the last if none of the condition is true then the statements defined in the else block will be exscuted, ‘There ae multiple else-if Blocks possible. itis similar to the switch case statement where the defeult is executed instead of elge block if none of the casesis matched. if(condition!}| foodie to be executed if condition is true Jelse if(condition2){ foode to be executed if condition? is true 18 Guess Paper 1 else if[sondition?}{ Jicade to be executed if condition’ is true I else] jieode to be executed if all tha conditions are false 1 Flowchart of else-if ladder statement in C: False Tee ocr of elgg tn CUP agen elo Aachudectiio b> int main()i 2 - int sum ber=0; f printi("entera skim bee sean ("dom bet 4 it{oumber--LOVE printi(‘number is Baualste LO, pulntf(inuim ber is equal to 50"); 1 else ifitum ber==100)[ pninti("numberis equal to 100 } else} pointi(’number is not equal to 10, 500r 100"); Shrichakrahar.com 19 ’ return 0; } Output: enter numberst numberis not equal to 10, 50 oF 100 enter a number:50 ‘number is equal to 50 C Switch Statement: The switch statement in C is an alternate to if-else: stement which allows us to execute multiple operations for the different possible values variable called switch variable, Here, we can define various statements in the multiple cases, different values of a single variable, ‘The syntax of switch statement in c language is given below: ¢ Switch (expression)| Case valuel: {jcode to be executed; Break; //optional case value?: joode to be executed; © Break; //optional Default: Code to be executed if all cases are not mat 1 Rules for switch statement in € 1 ‘© Theswitch expression must ‘The case value must be teger type. . char c © Thecase value can be us idle th ent. + Thebreak statement ey optional. If there is no break statement found int after the matched case. It is known as fall through the st Let's try to understan pl suming that there are following variables. int xyz: char ab; float f; a “sven | case 3; owas, | uo | soho) asa fee switch(arb2) | | ease 12 | ease x2; switch(fune(xy)) | “case's'y | case 12.3; 20 Guess Poper Flowchart of switch statement in C Fig: Switch Statement Matched ‘Unmatched Matched Matched, a Functioning of switch case statements Fist, the inleges expression specified in the switch statement is evaluated This valueis then matted one by ong-With thelgonstant values given in the different cases. Ifa rmateh is found, then all the statements specified mthat case are executed alang with the all the cases present after that case including the default ststement. No two cases can have similar values. If the matched case contains & break statement, then"all the cases present after that will be skipped, and the control comes out of the switch, Otherwise all the gases following the matched case will be executed, Lats see asimple exeBle oF language chal em ent Ancludlecstdio h> intrmain(){ intnumborst, printi(enter animber » scanf "Ee 'ydanusn ber), switellltaa PAP cased pfintf('Alim ber is equals to 10"), ‘break, ease 50 printi('ruaber is equal to 50"), break; case 110 printf(’nursber is equal to 100"), Shtichakradhar.com a ‘break; default: printf("number is not equal to 10, 50.0r 100"); 1 return 0; 1 Output: Enter a number Number is not equal to 10,50 oF 100 Enter a number50 Number is equal to 50 Nested switch case statement: We can tise as many switch ea Wwe want inside a switch st statement. Such type of statements is called nested switch nts. Consider the following example. #include int main (){ inti~ 10; © int 0; switch(i) { re Shasketdtrenietel oe =e a BANS cae oo if. 1 Printf("Exact value of iis : %d \n'pi); ed Printf("Exact value of jis : return 6; 1 Output: The value of i evalua switey The value of jevalu ted s Exact value of is 1 Exact value of © oy 2 Guess Poper MCS 201: Programming In C and Python Guess Paper-2 Q. Explain go to, break and conti Ans. The go to statement is known as jump statement in C. As the name suggests, goW is used to transfer the program control to a predefined label. The goto statement can be used to:tepeatisome part of the code for a particular condition. It can also be used to break the multiple loops whighyean't be done by using a single break statement. However, using goto is avoided these days sife it makes the program less readable and complicated, Syntax label: s/some part of the code; goto label; ‘goto example Let's see a simple example to use goto statement in C languages include int main) ( int num i-1; printf(’Enter the number whose table you wantito priat?”); scanf("%di" enum); table: printi("%od x %d = %d \n"snumi mum"); if(i19) goto table: } Output: Enter the number whose tableyou Want to ptint?10 10x1=10 10x2=20 10x3=20 10x4-40 we statements? 10x6=60 10x7=70 10x8 80, 10x9590) 10,30 - 100) C break statement: The break is a keyword in C which is used to bring the program control out of the lop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, ic, in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. ‘The break statement in C can be used in the following two scenarios: With switch case With loop Syntax: Shtichakradhar.com 2B ‘TMloop or Switch case break; Example finclude findlude void main () { int i; for(i =0;1<10;1++) { Print" "i iti =5) Break; t printf(’came outside of loop i = %d") } Output: 0123.45 came outside of loop C continue statement: The continue statement in(@ Janguaige is used f8baing the program control to the beginning of the loop. The continue statement skips Sori lines of code inside the loop and continues with the next iteration. It is mainly used for a condition, 6 that wBican Skip some code for a particular condition, Syntax: i/loop statements continue; {ysome lines of the code which is to beskipped Continue statement example 1 Finclude void main () . { int i=0: while(!-10) t printf("%6d" 4); Continue; } 1 Outputinfini®loop Qu Deseribe the concept of arrays with example? xy is defined as the collection of similar type of data items stored at contiguous memory locatioliS Arrays are the derived data type in C programming language which can store the primitive type of data stich as int, char, double, float, ete It also has the capability to store the collection of derived data types, such as pointers, structure, etc The array is the simplest data structure where each data element can be randomly accessed by using its index number. C array is beneficial if you have to store similar elements, For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different 24 Guess Poner subject, Instead of that, we can define an aay which cam store the marks in each subject at the sotigunus rnernary locations By nang the arvay, we can accass the clementseasily. Only a few lines of code are required to access the elements of the array. Pperties of Array. The array contains the following properties, Bach element of an arayis of same data type and carries the same size, ie, ink=4 bytes. Blements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location, Elements of the array can be randomly accessed since we can celeulate tite addvess of each element of the array with the given base address and the size of thedata element Declarstion of C Arvay: We con declare an array in the ¢ languagein the following vay. data_type erray namelarray size], Now, letussee the example to declare the array. intmarks[6]; Here, intisthe data type, marks ame the array name, and Bis the amay size Initialization of C Array The simplest way to initialize an array is by using the index of each element, We cari initialize each slementof the amay by using the index Consider the following exaraple Marles[l]=20 initialization of array: Markel Marks[2]-70, Markel Marksl | a0 marksfo] marks[1}markgl2] tnarksi3]__marks[a] Initialization of Array amy example Anclude-stdio h> intmaindt inti=t; Int marks(5],/Mleclaration of array initianzation oF array Merle 2]°70) Marks(3)=05, Markit i(taversal of Srray Site Ac \n' marks); fend of for loop return O; Shrichakradhor.com 2 1 Output 80 60 70 85 75 Q. Explain the purpose of sirings? Ans, Sitings are actually one-dimensional array of chatactets terminatgd bye null chatactar '\0', Thus a nullterminated string contains the characters that comprise the string allowed by a null. The following declaration and initialization create a string consisting of the word, "Hallo" To hold the null character at the end of the array, the size of the chatacter array containing the Strings one more than the number of charactersin the word "Hello." char groeting(6] ={'H!, eI, t,'o', N's Ifyou fellow the rule of array initialization then you can vrlfe the Bbove statementaafollows— char greeting[] ="Hello's Following is the memory presentation of the above defined string in CCH = ipa ° 3 2 3 * s address [Toaws [oom Toons [ame | ons | eau -Actuélly, you do not place the aull chafacter @t the endlof.a siting constant ‘The C compiler aulomatically places the string ~ Hinclude Int sain Ql Char greeting[6]-['H)e)'"IB4p\ 0}, Printi('Groeting massdye! s\n", grestingy), Returnd; 1 ‘When the sbovaienda fecompiled and Beeeulet, it produces the following result — resting message: Alello Csupportsa wide range of functionsthak manipulate null-terminated strings ~ 0 at the end of the sfringeqyhen'lt initisliges thearray. Let us try ta print the abowe menticned St.No. Rinction & Purpose 1 strepy(o1, 52); Copies string 52 into string 21. 2 streat(st, 32): Concatenates string 52 onto the end of string si 3 stilenist); Retamsthe length of strings 26 Guess Paper 4 stremp(st, 52); Refums 01 and s2 are the same; less than Oi s1<<2; greater than 0 if s>s2 5 strehr(s1, ch); Returns pointer to the first occurrence of character ch in string sl. 6 strstr(s1, 52); Retuns.a pointer to the first occurrence of string s2 in string sl. ‘The following example uses some of the above-mentioned functions — #include #include-stringh> Int main (| Char stri[12]-"Hello"; Char str2[12]-"World”; Char str3{12}; Int len; P*copy str] into str3*/ Strepy(str3, str); Printi(’strepy( str3, str)» %s\n", str3 ); P*concatenates str] and st2*) Streat{ str, str2) Printi('streat(str1, st2): %s\n", str ); /* total lenghth of ste] after concatenation Len = strlen(stt]); Printf'strlen(sir1) : %d\n’ len); Returnd; 4 When the above code is compilél ahahexecuted it products the following result — strepy(str3, strl) : Hello strcat( str1, str2):, HelloWotleh strlen(strl) : 10 Q. What are functions in ©? Ans. A functions a gtoup of statements’ thal together perform a task. Every C program has at least one function, which jini), and allgifimostéH vial programs can define additional functions. ‘A function dedlaration tells the compiler about a function's name, return type, and parameters. A function definitioneprovides the actual body of the function. ‘The Qpstandatd library provides numerous built-in functions that your program can call. For example straat®) to concatenate two strings, memepy() to copy one memory location to another location, and many more functions A fficfion can also be referred asa method or a sub-routine ora procedure, etc Defining a Function: The general form of a function definition in C programming language is as follows: retum typefunction name( parameter list )f body of the function r ‘A function definition in C programming consists of a function header and a function body, Here are all the paris of a function ~ Shtichakradhar.com a Return Type: A function may retum a value, The retum type is the data type of the value the function rettums. Some functions perform the desired operations without retuming a value, In this case, the return type is the keyword void, Function Name: This is the actual name of the function. ‘The function name and fhellparameter list together constitute the function signature. Parameters: A parameter is like a placeholder. When a function is invoked, feubpass a value to the parameter. This value is referred fo as actual parameter or argument. The param list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body: The function body contains. collection of statements thal defifte what the function does. Example Given below is the source code for a function called max0, This function takes two parameters num! and ‘num? and retums the maximum value between the two — /* function returning the max between two numbers" int max(int nmi int nuam2)| (local variable declaration */ int result; if(ournt > num?) result=numnt; else resull-= nur; return result; 1 Q. Illustrate the process of defining a uhion? Ans, A. union is a special data type a¥ailable’in C thatyalloWs storing different data types in the same ‘memory location, You can define lanion With many members, but only one member can contain a value at any given time, Unions provide am efficient way of using the same memory location for multiple- purpose, . Defining a Union: To define'a dhion, you mustiuse the union statement in the same way as you did while defining a structure. The union statemieht defii®s a new data type with more than one member for your program. The forma of the Union stateméntisjas follows ~ Uunion{union tag]t member definition; member definition, member definition; J[one or more unig variables}; ‘The wnfon(fagiSoptional and each member definition is a normal vatiable definition, such as int for float f; orany other Valid variable definition. At the end of the union's definition, before the final semicolon, yo! cansspecify one or more union variables but it is optional, Here is the way you would define a unin type named Data having three members i, f, and str ~ union Data inti; float f; char str{20); data; 28 Guess Paper ‘Now, a variable of Data type can slore an integer, a floaling-point number, or a siting of characters, It meansa single variable, ic, same memory location, can be used to store multiple types of data. Q. Briefly describe the significance of pointers in C? Ans. A pointeris a variable whose value is the address of another variable, i.e/ ditt ackdress of the ‘memory location, Like any variable or constant, you must declare a pointer heforelusing it to store any variable address, The general form of a pointer variable declaration is ~ type *var-name; Here, type is the pointer's base type; it must be a valid C dala type and var-name is the hame of the pointer variable, The asterisk * used to declare a pointensis thé-same astetisk used for multiplication, However, in this statement the asterisk is being used taldesighate a variable as a pointer, ‘Take a look at some of the valid pointer declarations - int “ip; /* pointer toan integer double *dp; /* pointer toa double */ float “fp; /* pointer toa float "7 char *ch /* pointer to a character 4 2 ‘The actual data type of the value of all pointers, whetherlingeger, float, cheradleiigor otherwise, is the same, a long hexadecimal number that represents, a sfémory address, THEGhly difference between pointers of different data types is the data type of thé Variable Br constant tha the pointer points to. ‘There are afew important operations, which we Wilh int main Ot intvar-20,/* actual variable declafattan int*ip,/* pointer variable declaration *? ip ~Revar,/* store acidress of vain paiiiter varialile™) printf" Address of var variable: ox" evar); /* address stored in pointer Waltable */ printf("Acidress stored in ip variable: %x \fpip J> access the value usingithe pointer *! printi(’Valuie of “ip variable: %ed \n’,*ip J; retum0; | When the aboye code is compiléchand executed, it produces the following result — ‘Address of yar vatiable: bffd8b3° Addresssforedlin ip variable: bffd862- Value of ipyarfable: 20 NULL Pointers: It is always a good practice to assign a NULL value to a pointer variable in case you do nobinve an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assfgnediNULL is called a null pointer, ‘The NULL pointer is a constant with a value of zero defined in several standard libraries, Consider the following program #include int main inf*ptr = NULL; Shtichakradhar.com 2 rinti(’The value of pir is: 9x\n", ptr); retum0; ) When the above code is compiled and executed, it produces the following result ~The Value of ptr is 0In ‘most of the operating systems, programs are not permitted to access memory at adtess 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location, Buby convention, if a pointer contains the null (zero) value, itis assumed to point to nothing. ‘To check for a null pointer, you can use an ‘if’ statement as follows ~ if (ptr) /* succeeds if p is not ull *) if(tptr) * succeeds if p is null Q. Describe the usage of array of pointers? Ans. There may be a situation when we want to maintain an arta, wHich can store pointers to an int or char or any other data type available. Following is the declaration an array6fipointers to an integer int *pte[MAXIt declares ptr as an array of MAX integer poiters. Thus, each element in ptr, holds a pointer to an int value. The following example uses thrde integers, which ar@jstored in an array of pointers, as follows ~ #include constint MAX=3; int main ()f intvarf]-{10,100,200), int i,"ptrf MAX]; for(i =0;1< MAX; i+)l ptr[i]=&var[i]* assign the address of integer. *f printi(’Value of var{%d] = 4d \n i pti 1 retum0; 1 When the above code is compiled and execyte, it prodtices the following result ~ Value of var{0=10 Value of var Value of var{2 You can also use.an array of pointers to charatter to store a list of strings as follows tinclude> After Willing the print statement, press the Enter key 32 Guess Poper {i Python 323 shel = 0 X File Edit Shell Debug Options Window Help Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925.32bit (In tel)] on win32 ‘Type "help", "copyright", "credits" or "License()" for more infOtmapion. >>> print ("Hello World") Hello World »| Here, we get the message "Hello World!” printed on the console Q. Briefly deseribe the various data types of python? Ans. A variable can hold different types of valuess{Kot example, a person’ name must be stored as a string whereas its id must be stored as an integer, Python providesivariougistandard data types that define the storage method on each of them. The data types defined it Pythanare given below © Numbers Sequence Type Boolean Set Dictionary = — Numbers:Nimbe? stores numeric ¥alues. The integer, float, and complex values belong to a Python Numiersidata-type. Python provides the type function to know the data-type of the variable. Similarly, thedsjinstance() function is used to check an object belongs to a particular class, Init lftieger value can be any length such as integers 10, 2, 29, -20, -150 ete, Python has no restriction on the length of an integer. Its value belongs to int Hat Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc Ibis accurate up to 15 decimal pois. Complex - A complex number contains an ordered pair, ie, x + iy where x and y denote the real and imaginary parts, respectively. The complex numbers like 2.14), 20+ 2.3), ete. Sequence Type: Shtichakradhar.com 33 String: The string can be defined as the sequence of characters represented in the quotation marks. In Python, we can use single, double, or triple quotes to define a string. String handling in Python is a straightforward task since Python provides built-in functions and operators to performoperations in the string. In the case of string handling, the operator + is used to concatenate, Ho Strings as the operation ‘hello"*" python” returns “hello python’: ‘The operator *is known as a repetition operator as the operation "Python" *2 retuhs!Python Python’ List: Python Lists are similar to arrays in C. However, the list can contain daitajof different types. The items stored in the list are separated with a comma (,) and enclosed within sduare brackets (J. We can use slice [:] operators to access the data of the list. The concatenation operator (+) ali repetition operator (") works with the list in the same way as they were working with the string ‘Tuple: A tuple is similar to the list in many ways. Like lists, tuples also eontain the collection of the items of different data types. The items of the tuple ate separated with a comma (, and enclosed in parentheses 0. A tuple isa read-only data structure as we can't modify the size and Value of theil@ms of a tuple Dictionary: Dictionary is an unordered set of a key-value paif of items. Itis likean asSociative array or a hash table where each key stores a specific value. Key can hold any primitive dataltype, whereas value is an arbitrary Python object ‘The items in the dictionary are separated with the cofima (,) at enclosed ithe ally braces {} Boolean: Boolean type provides two built-in valu@ipTrue and False fie valties are used to determine the given statement true or false. It denotes by the elas bool. Tru¢ gan bé fepresented by any non-zero value or 'T’ whereas false can be represented by the for’ Set: Python Set is the unordered collection ofithe data type/it ishinerrable, mutable(can modify after creation), and has unique elements. In set,{the order of the elements is undefined; it may return the changed sequence of the element. The seflis créaited by uSingjaibuilt-in function set, or a sequence of elements is passed in the curly braces and separated by the commapit can contain various types of values. Q. Explain the concept of functiongin python? Ans. A function is a block of organized reusable codaithat is used to perform a single, telated action, Functions provide better moduilarityfor your application and a high degree of code reusing: As you already know, Python gives youmany built-in finctions like print Q), etc. but you can also create your wn functions. These functi@iaré called useF-definéd functions Defining a Function: You can define functions 1 provide the required functionality. Here are simple rules to define a functiog in Python. Function blogks begin with thé KeyWord def, followed by the function name and parentheses (() d ‘+ Any inpitlparametets offfijgumehts should be placed within these parentheses. You can also defineyparameters inside these parentheses. ©The first statement of a function can be an optional statement - the documentation string of the fuitetiGin or docstring. “Thejcode block within every function starts with a colon (} and is indented. (he statement retum [expression] exits « function, optionally passing back an expression to the ‘aller. A return statement with no arguments is the same as return None. Syntax def function name( parameters ): “function_docstring" function suite retum [expression] 34 Guess Poper By defaull, parameters have a positional behavior and you need to inform them in the same order that they were defined. Example ‘The following function takes a string as input parameter and prints it on standard sen. def. printmne( str) "This prints a passed string into this function” print str retum Calling a Function: Defining a function only gives it a name, specifiessthe parameters that are to be included in the function and structures the blocks of codeOnce the! basidistructure of a function is finalized, you can execute it by calling it from another function or difeetly from the Python prompt. Following is the example to call printme() function #t/usr/bin/python # Function definition ishere def, printmet str) “This prints a passed string into this function” print str return; # Now you can call printme function printme('I'm first call to user defined function!) printme("A gain second call to the same function”) When the above code is executed, it produces tfifellowing resilt = {'m first call to user defined function! Again second call to the same function Q. What are anonymous functions? ‘Ans, These functions are called anéhymous because they ate not declared in the standard manner by using the def. keyword. You canytise the lambda key wordt create small anonymous functions. Lambda forms can take any number of arguments but feturlfist one value in the form of an expression. They cannot contain commands orsmultiple expressions, ‘An anonymous functighycannotibe a direct rallto, print because lambda requires an expression Lambda functions have their own fogal namespace afid cant access variables other than those in their parameter listand those in the global namespaces Although it appears that Jambda’s ate a onédline version of a function, they are not equivalent to inline statements in © on. C+, whose purpose is By passing function stack allocation during invocation for performance reasons) Syntax: The sfittax of lambda funétions eontains only a single statement, which is as follows ~ lambda [argb{,arg®...argn]}expressfon Followifig is theexample to show how lambda form of function works ~ #t/ysqjbin) python # Funetiotidetinition ishere sum lambda argl, arg? argl + arg2: # Now you can call sum asa function print'Value of total :", sum(10,20) print'Value of total", sum(20,20) When the above code is executed, it produces the following result ~ Value of total : 30 Shtichakradhar.com 35 Value of total: 40 The return Statement: The statement return [expression] exits a function, optionally passing back an expression to the caller, A retuim statement with no arguments is the same as return None All the above examples are not returning any value. You can return a value from a furtctioflas follows sust/bin/python # Function definition ishere def. sum( argl, arg? ): # Add both the parameters and return them.” total = argl + arg? print'Inside the function :", total retum total; # Now you can call sum function total = sum(10,20); print"Oulsice the function :",folal ‘When the above code is executed, it produces the following reStlle Inside the function : 30 Outside the function ; 30 Q. What are modules and packages in python? Ans, A module allows you to logically organize yout Python code. Grouping related code into a module makes the code easier to understand and use Asmérlule is aliPythanvobject with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python ode. A modulélican define fumctions, classes and variables, A moctule can also include runndble esd Example The Python code for a module naméd a nafne normally, resides in a file named aname.py. Here's an example of a simple module, supporpy def. print_fune( par ) print'Hello:", par y - retum ‘The import Statement You can use any Pythén Source file as a riadiile By executing an import statement in some other Python source file. The importhas thétfollowing syntax import modulet{, moefulegf,.. module When the interpreter ehebunters an infiport sfatement, it imports the module if the module is present in the search path, AlSearch path sS'@ilist ofdirectories that the interpreter searches before importing a ‘module. For example, to import the module support py, you need to put the following command at the top of the scriph= #/ustiinipythion, # Importmedulé support inportsupport # Now you can call defined function that module as follows suppottiPrint_func("Zara’) When the above code is executed, it produces the following result ~ Hello: Zara A modulle is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur, ‘The from...import Statement Ed Guess Poper Python's from statement lels you Import Specific altributes from a module into the current namespace ‘The from. .import has the following syntax — from mod name import namel|, name2[, .. nameN]] For example, to import the function fibonacci from the module fib, use the following statement — from fib import fibonacci ‘This statement does not import the entire module fib into the current namespateitjust introduces the item fibonacai from the module fib into the global symbol table of the importing Mtodtle. ‘The from. .import * Statement Itis also possible to import all names from a module into the current namespage by using the following, import statement — from modname import * This provides an easy way to import all the items from a module.into the current namespace; however, this statement should be used sparingly. Packages in Python: A package is a hierarchical file directory stftieture that(@dines a single Python application environment that consists of modules and sub pacages and sub-sub patkages, and so on Consider a file Postop available in Phone directory. This file as following line of sOuurce code ~ stfust/bin/python def Pots() print’ Pots Phone” Similar way, we have another two files having different\functions withsthe sabre name as above - + Phone/Isdn.py file having function Isdri() © Phone/G3 py file having function Gael ‘© Now, create one more file _init_{pym Phone ditectory ~ © Phone/_init py ‘To make all of your functions availablé"When you've impafted Phone, you need to put explicit import statements in _init_.py as follows ~ From Pots import Pots From Isdn import Isc From G3 import G3 , After you add these lines to | imi py, you have all Of these classes available when you import the Phone package. #t/ust/bin/python # Now import your Phone Package. importPhone Phone. Pots() Phone Isdn() Phone.G3() When the above eade is executed, it prtiduces the following result - 1'm Pots Phone! im 3G Phone Int ISDINRhORE Q. Hoielasses and instances are created in python? Ans.Creating Classes: The class statement creates a new class definition. The name of the dass immediately follows the keyword ciass followed by a colon as fellows ~ class Class Name: ‘Optional class documentation string'class suite ‘Shtichakradhar.com 37 ‘+ The class hasa documentation string, which can be accessed via Class Name_doc_ + The class suite consists ofall the component statements defining class members, data attributes and functions, Example Following is the example of a simple Python class ~ classEmployee ‘Common base class for all employees! empCount -0 def, init__(self, name, salary): self. Name= name self. Salary- salary Employes.empCount 1 def.display Count(self): print'Total Employee %d"Employee.empCount def.display Employeetselt): print'Name : "self, Name,”, Salary: "self. Salary ‘> The variable empCountis a class variable whodeWalue is shared amongall instances of a this class. This can be accessed as Employee.emp Count from inside the elassr outside the class, ©The first method _init_()is a special meth@el, which is called ca’ constructor or initialization ‘method that Python calls when you createa new fhstance of thisclass. * You declare other class methods like narmallfiinctions with the exeeption that the first argument to each method is self. Python adds/the'self argument to the list for you; you do not need to include it when you call the methods Creating Instance Objects To create instances of a class, you call thélclass using classname and pass in whatever arguments its_init__ method accepts. "This would create first object of Employee class" empl = Employee ("Zara", 2000), “This would create second object of Ertployee class" emp2 = Employee (’Manni", 5000) Q. Mention some standard exceptions in python? Ans, Python provides!fwa very imy ‘féafures to handle any unexpected error in your Python programs and tg add debigising cap: them. List of Standard B&teptions ~ crt agen SPN 1 | Fxeeption { assoc: forall exceptions 2) Stop Iteration: Raised when the next() method of an iterator does not point to any object 3 ‘System Exit: Raised by the sys.exit() function. 4 Standard Error: Base class for all builtin exceptions except Stoplteration and 38 10 n 19 Guess Paper SystemExit, Arithmetic Error: Base class for all ertors that occur for numeric calculation \Ovection rive Reed when Aephaahon Sroiedamnadintan tim eglle Mic te oatingPaintier Raied when a floating point clculaton tale Zao vsti eed hc division ab aaclo ip erggneairs al acne types. AssertionError: Raised in case of failure of the Assert statement. AttributeError: Raised in case of failure of attribute refererice or assighimiat, FOFError: Raised when there is no input from eithér the raw input() oFliipul() function and the end of file is reached. ImportError: Raised when an import statement fails. Keyboardinterrupt: Raised when the user interrupts progilim execution, usually by pressing Ctlic LookupError: Base class forall fookuplerrors, IndexEtror: Raised when aft inciex is not foundin @ sequence. Keybitor: Raised when thespecified key iS HOt fotind in the dictionary. Name Error: Raised when an identifienis not found in the local or global namespace. Unbound CogalError Raised Wwhel flying to access a local variable in a function or method but no vale has been assigned to it Environment, Error: Base )xlass for all exceptions that occur outside the Python envitaiinent 1O Fb, Raisee when aif inpul/ oulput operation fails, such as the print statementor the Jopen{) function when trying to open a file that does not exist TOF ror: Raised for operating system-related errors ‘Syntax Error: Raised when there is an error in Python syntax. Indentation Error: Raised when indentation isnot specified properly System Error: Raised when the interpreter finds an intemal problem, but when this error is encountered the Python interpreter does not exist. Shrichakradhar.com | System Exit: Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. ‘Type Error: Raised when an operation or function is attempted that for the specified data type. Value Error: Raised when the built-in function for a data typ: valid type of arguments, but the arguments have invalid values specified. Romie Hurie Balad Waehal peel cexcos Notimplementedtrror Raised when an abstract method thatneeds tobe implemented in an inherited class is not actually implemented.

You might also like