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

C & DS Unit - I

Anna University Syllabus C Programming and Data Structure Unit 1 Notes.

Uploaded by

hostdkn73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
13 views

C & DS Unit - I

Anna University Syllabus C Programming and Data Structure Unit 1 Notes.

Uploaded by

hostdkn73
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 58
WR 1 C Programming Fundamentals Syllabus Data Types - Variables - Operations - Expressions and Statements - Conditional Statements - Functions - Recursive Functions - Arrays - Single and Multi-Dimensional Arrays. Contents 4.1. Introduction 1.2. Keywords, Variables and Constants 1.3. Header Files 1.4 Data Types vores ees, May-19, Dec.-19, 1.5. Expressions using Operators... . May-19, Dec.-19, 1.6 Input and Output Operations 1.7. Decision Making and Conditional Statements . Dec.-19, 1.8 Functions ~.. Dec.-18, May-19, 1.9 Recursive Functions .. ++. Dec-18,19, - 1.10 Arrays +e May-19, 1.11 Simple Programs fee leeeee cesses, Deoet8, 1.12 Two Marks Questions with Answers 7 and Data Structures 1-2 Programming Fundamentals 4.4 | Introduction * Cis a structured programming language developed by a programmer Dennis Ritchie. + It is also called as a high level programming language. elt has small instru possible, ‘1 set using which development of many engineering applications is +t is a case sensitive language. That means it differentiates between the two variables having the same letters but different cases (upper and lower case). 1.2 | Keywords, Variables and Constants Keywords : + Keywor wre the standard words in C. + These key. © All key '* Various keywords used in C are listed below - sically’ the reserved words which have special meaning. The meaning of rds cannot be changed. ‘ds are written in lower case. | alien auto break | | case char const continue default do |__ double else enum | extem float for | goto if it | | Tong | shor static struct Identifiers : + Identifier is a collection of alphanumeric characters in which the first character must not be numeric. ° « Identifiers are the names given to the variables, functions or constants, «+ The name of the identifier must not be the keyword TECHNICAL PUBLICATIONS” - an up-thrust for knowledge C Programming and Data Structures CC Programming Fundamentals Validity of variable names Following are the rules which should be followed while deciding the variable names 1) The first letter of the variable must not be digit or any special character. 2) Special characters (such as §, #, %) are not allowed in the variable name except underscore. 3) The variable name is case sensitive. A variable name can_ be in capital letters. 4) The length of the variable name can be any but only first 31 characters are recognized. 5) The keywords are not valid variable names. 6) Blank spaces or special characters, commas, use of quotes are not allowed in the variable name. 7) Arithmetic operators should not be used in the variable names. ‘The variable names should be informative. It should describe the purpose of it by its name. 7 ‘The valid variables are Count;tax_id, INDEX Xyz,brick01 ‘The invalid variable names are -file,char,#id,1A,velid name Constants Definition of constant : The specific alphabetical or numerical value that never gets changed during the processing of the instructions is called as constant. + The constant can be alphabetical, numeric or special symbol. * The constants are given some names and are referred by the names. + Example : The most commonly used constant is PI. Once the value to this constant is assigned then it does not get changed. + The names to the constant help in accessing them easily. + Generally all the letters in the name of the constant are capital. Comparison between Constants and Variables Constant Variable 1. Constants can not be changed. Values of the variable may get changed, during processing. Storage location is given a name Storage location is given names. TECHNICAL PUBLICATIONS® an up-thrust for knowledge h RE TT The evtants are The variables are giver the names ang ind ane reer theft by the name in the instruction, Tvample : Namew"AAAY En contain st ‘andard library functions. For using these library fungig, the program, Wis necessary to include the header file at the beginning of Following are the header files supported by C ——_ paloch, aseth bel biosh | }omrrlech —conioh ——agpen ch | [airenth dosh econ. ostream} fentlh fstreamh __generich math Lioh limitssh malloc 3 | Jocaleh mem sefjmph |_processh signalh—stddeth iol _stdargh stdiostch ——streamh eo | Sidlibh ststreah —_valuesh oa timeh Some commonly used header files are Stdio.h : It is standard input output header file. In this fie the functions for print scanf, fprintf, fscanf are defined. These functions deal with input and output functions, Conio.h : It is Console Input Output header file. In this file the typical functions such a chsscr{) is defined. By using clrscr(), the console output) screen gets cleared. math.h : In math.h all the functionalities related to mathematical operations are define Such as pow for computing power, sqrt for computing square root and many more. alloc.h This header file is used when a function for allocating. the memoq dynamically, such as malloc) is used in the program [ Key Point : We have to include header files a the beginning of C program, TECHNICAL PUBLICATIONS” - an ups for knowiedge Nc Profi ming ond Dae Siructures 1 ‘ Data Types C Programming Fundamentals + Data types specify the type of data we enter in our program. «In C there are some predefined set of data types which are also called as primitive data types. Primitive data ' ype char | void | integer float Fig. 1.4.1 Data types + Primitive data types are fundamental data types. (1) integer type without fraction). These data types are used to store whole number. (ie. the number Size and range of Integer type on 16-bit machine? Type Size(bytes) Tenge! int or signed int 2 — 32,768 to 32767 long int or signed long 4 i unsigned long int 4 4 (2) float type : These are the data types used to store the real numbers (i.e. the numbers with fractional part). TECHNICAL PUBLICATIONS® - an up-thrust for knowledge | Giaesey eer : C Programming Pung, amen, Size and range of Integer type on 16-bit machine ype Stretbyten) Range float ‘ 34P = a8 to 34E + 38 doubic s 308 tw LTE + 308 Jong af f 348-4932 to 116 +4932 (3) char type : Thu a type is used to store the character value Size and range of Integer type on 16-bit machine Type Size(bytes) saxtenediGiae 1 ~ 128 to 127 unsigned char 1 0 to 255 a (4) void type : Void data types mean no value. This data type is normally associate, non that return no value. Review Questions ¢ the various data types in C with an example. AU : May-19, Marks 6 2 ¢ and range of the primitive data types. REDS 1.5 | Expressions using Operators AU : May-19, Dec.-19, Marks 13} For handling the expressions the operators are used. C support following set of operators Type Operator Meaning For Example Arithmetic + Addition or unary c=.a tb plus - Subtraction or unary d= - a, | minus cea-b . Multiplication ceatb I Division c= afb | % Mod ab | Relational < Less than as4 | Greater than a>4 < Less than equal to a<=4 TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming, and Data Structures 7 CProgremening Fiswlenientele Greater than equal to a >= 4 Equal to ams anh 0 bk t Os ony ol ot) Conditional operator ¢ ' ‘The conditional operator is ? The syntax of using conditional operator is condition?expression1:expression2 True condition a Lara condition For example . a>b?tme:false ~ , This means if a is greater than b, if yes then the value will be true otherwise it will be false. Precedence of Operators Precedence means the priority of certain operation. of operation Name of operation Functions | TECHNICAL PUBLICATIONS® - an up-theust for knowledge C Programming and Data Structures Ven C Programming Fundamental Is In case there is a is a tie hetw of same priority preference is given to the operator which occurs first N Within a pare ranthesi: e r ‘S the same hierarchy is operative. If there are more than one set of paranthesis inner mest Ost parantheses. wi . , within second Perantheses will be performed frst, followed by operations eg. a BEAR863 Stepwise evaluation & = 3/3"4+3/8+3 operation / 1433/83 operation * 4+3/8+3 ‘operation / = 44093, operation + = 493 operation + -7 Ex. 15.1 Determine the output of the followiug “C” statements : Assume a = 13, b = 25 and c= 5. Dieanb iix=+a-b ii) ys bot ip) x= 0>b271:0. Sol : i) z = 20 as it is logical bit wise EX-OR operation The truth table for EX-OR operation is as shown below re increment operator the value of a is incremented by one before the oO oF 0 ; 0 ia = 1 jesai: >) 0 saetaee 1 1 Jao i ii) - Vi sincex = +a-b = 14-25 =-1 ; i As +12 is 2 Pp expression gets evaluated iii) 30 since y = bee =25+5 ‘As bet is a post increment operator, after expression becomes 26 gets incremented the value of b iv) 0 TECHNICAL PUBLICATIONS® - an up-thnust for knowiedge C Programming, and Data Structures 19 C Peoppatrenioy Futdamartals The meaning of this expression is if ¢> b is true then print | otherwise 0. As value of eis ess than b the output will be 0. Review Questions 1. List all the operators in C with an example for each Cee 2. Describe the various operators in C with examples and the associatroity Input and Output Operations In C inputting some data is done by scanf and outputting or printing the data on console (output screen) is done by printf statement. These are standard library functions. The way to write these statements is, scanf(format specifier,variables); Variable(s) For example : scanf("%d",&val L, Format specifier Note that the format specifier is %d since the val is an integer variable. Also the val variable is taken with the & symbol. The & (ampersand) means “address of”. Any variable is referred by its address. It is exactly similar to the way you find your friend, either by his address or by his phone number. Thus any variable can be obtained by its address, printf(format specifier,variables); For example : printf("%d",val); Note that here there is no need of & because we are printing the value of val variable. This value is already stored in some statement. Even the printf can also be used to simply print the message on the console. Decision Making and Conditional Statements Various control structures are-- 1. if statement 2. while statement ‘ 3. do-while statement 4. switch case statement 5. for loop Let us discuss these control structures with the help of simple examples TECHNICAL PUBLICATIONS® - an up-thrust for knowledge CProgramming and Data Structures yew C Programming Fundamentals 1, W statement There are two types of if statements ~ simple if statement and compound if statement, The simple if statement is a hind of if statement which is followed by single statement, — The compound uf statement is a kind of if statement for which a group of statements are ye followed. These group ot statements are enclosed within the curly brackets, If statement can also be accompanied by the else part. Following table illustrates vanous forms of if statement. yee ct Syntax Example eimpie Miconditien) tach) a statement ___print{(‘a is smaller than compound if (condition) ifa | and Data Su CProgramn if..eloe if ifoondition) iMaqb) ars { printiCa ie ematior thas WY: statomont 1: ss wdad é . rintt'a ie erat than 3) cise ) print{’a is targor than B © cso i{conaition)~ 884 3 { statement 1: 2. While statement \ . ¢ The while statement is executing repeatedly until the condition is false. The while statement can be simple while or compound while. Following table illustrates the forms of while statements - ae - Benet » Example S ‘simple while while(condition) statement while(a >choice; | case caseno:statements break: ——"_gwitch(choice) } 2 t — caso 1: print{('You have selected 1"); , break: | case 2: printf("You have selected 2°); break: case 9: print{("You have selected 3"); break; default: printi(’good bye’); + 5. for Loop The for loop is a not statement it is a loop, statements occurs. Following table illustrates the use of for loop - using which the repeated execution of Syntax Example forlinitfalization; vermination; step count) __forli=O1<10:i+ +) statement clil=ali)+bIik TECHNICAL PUBLICATIONS” - an up-thrust for knowledge C Programming, and Data Structures 1 C Programming, Fundamentals Compound for loon farliniiaization; tormiunicm: step ecunt) Wa=DIADAN a) 4 4 matomoen 1, fortiooge10444) statement 2; biotin +p. 5 } Ex. 1.7.1 Write output of the following C code : i) # include main () f int x=3; float y=3.0; if o=y) printf ("\nx and y are equal”); else printf ("\nx and y are not equal’); 1 ii) # include void main() t printf ("\n Here is some mail for you"); iii) # include main( ) t int x=4; while (x=1) { x=x-L printf ("\n%d", x); --X% } } Sol. : i) x and y are equal ii) The printf statement will not be executed. Hence there will not be any message onthe console. TECHNICAL PUBLICATIONS® > an up-thrust for knowledge: C Programming and Date Stanton a Programming Fundamentaly iii) The PTINtt statement veaill not be executed As wd and the condition in while loop gets false. The contns! will ot enter in the loop at all, Hence there will n6t be any message | on the console 4 7.2 Explain ase of “break” and “continue” keywords in “C” with suitable example, — Sol. : The break statement is used to terminate the execution of the loop. It can be used to break the looping of for, while, do-while and switch For example ; Ex. 1 whilefi<10) { PaRtf"Rd", a) 4{0==S) — when i reaches to the value 5 the while loop will be terminated. bresk: iss: } The continue statement is used to continue the execution of the control loop. For example : fert=0; i<3;i++) for()=0; <3; j++) if(e[i] = =blj|) + continue statement skips this value continue; else } printf("%d%d’, ali], bij)); } ' By above code if afi] = bfj) simply go back and increment j. Hence if afi] # bfj] then both afi] and b{j] will be displayed. . Review Questions 1. Explain - Control Statement in C 2. Describe the decision making, branching and looping statements in C. OES 1.8 | Functions If certain set of instructions is required frequently then those instructions are wrapped within a function. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming and Data Structures A Prony senening, Fundamental Passing parameters aed Fig. 1.8.1 Types of function C programmer handles the C function using three methods - /. 1. Declaration of function 2. Definition of function 3. Call to the function For example void main() . - OF { void sum(); /*declaration of the function*/ sum(); /*call to the function*/ } void’ sum() /*definition of the function*/ { int a,b,c; print{("\n Enter The two numbers"); scanf("%d %d" ,&a,&b); c=ath; print{("\n The Additon Of two numbers is %d", } ‘The syntax for declaration of the function is Retum_type Function_name(Data_type Parameter); The syntax for definition of the function is Retum_type Function_name(Data_type Parameter) { /foody of function } TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming and Data Structures 1-16 The syntax for call to the function is Function_name(Parameters); 1] Parameter Passing Method Type 1. Passing nothing and returning nothing. void main() { void sum (); /*declaration of the function*/ sum(),/*call to the function*/ void sumj() /*definition of the function*/ amt abd.c: prnti("\n Enter The two numbers”); scanfi"%d Sid" f&a,&b); atb: printf("\n The Additon Of two numbers is %d",c); } In above example no parameter is passe Hence the data type of the above function is voi function is returning nothing or returning NULL. We can also pass the argument as void to the function main indicates that there are no paramet void main() we can write void main(void) Ex. LE Write use of void data. Solution : « The void data type indicates that the function is returniny function then its data type is specified argument void to the function to indicate that there are no “e If the function is not returning anything from the as void. We can also pass the parameters to the function ‘Type 2. Passing the parameter and returning nothing. d and there is no return value d. The void data indicates that the function main. The parameter void to ° ers to the function main. Thus instead: of - C Programming Fundamentals from the function. Here we will see a sample C code in which the function is written with some parameter. main() 1° int a,b; void sum(int a.int b);/*declaration*/ a TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming and Data Structures 1 printf("\n Enter The two numbers”); scan{("%d" Bea, fb); sum(a,b);/*call*/ } void sum(int x,int y)/*definition*/ { int ¢; lary printf("\n The Addition is %d",c); } C Pregraenenierg Fundamentals The parameters a and b are passed. In the definition we have interpreted them as x and y You can take them as a, b respectively or x, y or any other names of your own choice. It makes no difference. It takes them as a and+b only. There are actually two methods of parameter passing. 1, Call by Value. The above example which we have discussed is of parameter passing by call by value. This is called by value because the values are passed. 2, Calll by Reference. In call by reference the parameters are taken by reference. Pointer variables are passed as, parameters. For example main() { int ab; void sum(int * int *); printf(“\n Enter The Two Numbers"); scanf("%d%da",&a, 8b); sum(&a,&b); } void sum(int *x,int *y) { int c; ctxt ty; printf("%d",c); } TECHNICAL PUBLICATIONS an up-thrust for knowledge CTrogramming and Data Ste bas Programming Purdamentate Difference between Call by Value and Call by Reference ~ eee PS Call By Valoe Call By Reference When a function is called, then in that function When 2 function ix called, then in that function addresses of the parameters are passed: | Aetal valor of the parameters are passed _The parameters are simple variables The parameters are pointer variables. A the values of the parameters get changed in If the values of the parameters get changed in ‘the fomction then that change i not permanent. the function then that change is permanent. Thm means the values of the parameter get ‘That means the values of the parameter get restored when the control Fetume back to the changed when the control returns back 10 the ‘caller function. caller function. for example : for example maxing) { x=10; suntx); fun(x); * primi "Sa" x) print{(*%d",*x): 3 . } ‘wold funtx: , 4 xnis, 3 ‘Oxtpot will be 10 and not 15 Output will be 15 and not 10 Compiler executes this type of function faster ‘Compiler executes this type function slowly as values get copied to seal parameters. i as addresses get copied to the formal ‘ | + parameters. é b Type 3. i Passing the parameters and returning from the function In this method the parameters are passed to the function. And this function returns some en the data type of that function is int. welue. Tf the function is returning integer value th Thus depending upon the type of data which ig returning from the function the data type of that funcuon 1s determined. If nothing is returned form the function then that function | has 2 void date type void main() . . f 1 ‘ int abc, . i int eum(int.int),/* Only mentioning of data type is allowed . for the parameters*/ . | : TECHNICAL PUBLICATIONS® - an up-thnust for knowledge | ae C Programming, and Data Structures Vio . © Peogpamenseg, Fundamentals print{("\n Enter The Two Numbers”); scanf("%d %d" fea,&eb); c=sum(a,b); printf("\n The Addition Is =%d",c); } int sum() { . : c=atb; return c; /*returning ¢ which is of int type*/ } /*s0 data type of sum is int*/ Ex. 18.2 Write aC program to interchange two variables without using third variable. Solutios prenenenees Program to interchange two variables without using third variable tusitseeestecesensustersesecwansouseeee veeey #include void main() ; { 7 int a=11; int b=20; print{("\na= %d b=%d",a,b); a=atb; a=ab; printf(\na= %d b=%d",a,b); } Ex. 1.8.3: Write a C program to get two numbers and exchange these numbers using pass by value and pass by reference. Sol. : #include void swap_by_value(int a, int b) { int temp; temp De Ces a=b; b= temp; } TECHNICAL PUBLICATIONS® - an upthrust for knowiedge C Programming and Data Stractunes Ln _C Programming Fundamentals void swap_by_reffint "a, int *b) { int temp: } int maing) { int x. y: printi(\nEnter First number : scanf("hd", &x); pmntf"\nEnter Second number : scanf(%d", &y); printfi"\nBefore Swaping x = %d and y = %d", x, y); swap_by_value(x,y); // Function Call - Pass By Value printi("\nAfter Swaping(By Value) x = %d and y= dx yi prnti("\nBefore Swaping x = %d and y = %d", x, y); swep_by_ref(&x,&y); // Function Call - Pass By Reference prinyi("\nAfter Swaping(By Reference) x = %d and y = %d", xy): 3 Output Enter First number : 10 : Enter Second number : 20 Before Swaping x = 10 and y = 20 After Sweping(By Velue) x = 10 and y = 20 Before Sweping x = 10 and y = 20 After Swreping(By Reference) x = 20 and y = 10 TECHNICAL PUBLICATIONS® - an up-thrust for knoydedge nd Structures tea © Proggateaniny, Fundamentals | Review Quostions | 1. Explain with a suitable example, function call by reference and function call by value | 2. Write suitable ‘C’ program that creates different results after passing a parameter by | reference and by values. 3. Mlustrate pass by value and pass by reference in functions with an example. LEAT EES _( | 4.9 | Recursive Functions LOTTERY (\ Befinition + Recursion is a programming technique in which the function calls itself repeatedly for some input. By recursion the same task can be performed repeatedly. Properties of Recursion Following are two fundamental principles of recursion 1, There must be at least one condition in recursive function which do not involve the call to recursive routine. This condition is called a “way out” of the sequence of recursive calls. The is called base case property. 2. The invoking of each recursive call must reduce to some manipulation and must go closer to base case condition. While computing factorial using recursive method - /[This is a base case else return n*fact(n-1);//on each call the computation will go closer to base case 1.9.4 | Factorial— Algorithm for Factorial Function using Iterative Definition 1. prod 2. xen; 3. while(x>0) 4. 5. prod = prod*x; 6. x--; 7) 8. return(prod); TECHNICAL PUBLICATIONS® - on up-thrust for knowledge C Programming and Data Structures 4-22 C Programming Fundamen, Algorithm for Factorial Function using Recursive Definition 1. if(r0) 2. fact #1; 3. else : { 4. xen; 5. y= value of xt; 6. fact=n"y; } Pelse ends here */ . This definition is called the recursive definition of the factorial function. This definition called recursive because again and again the same procedure of multiplication is followe but with the different input and result is again multiplied with the next input. Let us s how the recursive definition of the factorial function is used to evaluate the 5! Step 1. 5!=5° 4! Step 2. 44% 3! Step 3. ape3*2! - step 4. ue1"0! Step 5. we2"1! Step 6. ol=1. is giving the direct result.So to solve 5! we-hav ctuall 6 is the only step which i eee g the result from each step. Let us see how t to backtrack from step 6 to step 1,collectin| do this. Step 6. O!=1 Step 3. = 10!=7 from step 6° Step 4’. 2-21! =2 from step 5° Stop 3. 31= 321-6 from step 4 Step 2. 41-473! = 24 from step 3” pf = 5Y4! = 120 from step 2’ Step 1’. TECHNICAL PUBLICATIONS® - an up-thrist for knowledge C Programming and Data Structures 1-23 C Proggatrening, Pundamentale ¢ Program Ex. 1.9.1 Write a C program to find factorial of a number. Using recursive function. Solution : proseeenen Program for finding out the factorial for any given number. #include #include #include void main(void) { int nif int fact(int n);/*declaration*/ elrscr(); printf("\n\t\t Program For finding the factorial of n"); printf("\n\n Enter the number for finding the factorial: *); scanf("%d",&en); f=fact(n);/*call to fucntion*/ printf("\n the factorial of %d is %d".n.f); getch(); + int fact(int n) { int xy; if(n<0) { printf("The negative parameter in the factorial function"); exit(0); } if ) return 1; x=n-1; fact(x); _/*recursive call*/ retum(n*y); } TECHNICAL PUBLICATIONS® - an up-thrust for knowiedge Programming and Data Structures 124 C Programming Fu Output Program For finding the factorial of n Enter the number for finding the factorial: § the factorial of 5 is 120 1,9.2 | GCD (Greatest Common Divisor) In this method the GCD is calculated using following function ged(a,b)=ged(b,a mod b) provided a>b when we get ged(a,0) then GCD=a Consider there are two numbers 30 and 18 then we can find GCD as follows - Remainder ged(a, b)=ged(, a, mod b) ged(a, b)-ged(b, a mod b) | gcd(a, b)-gcd(o, a mod b) ged(a, 0)-GCD=a The above table itself illustrates the procedure for finding GCD using Euclid’s algorith The algorithm in simple steps can be given as - Step 4 : Divide a by b and assign the value of remainder fo variable c. Step 2 : Then assign the value of b to a and value of (remainder of a/b) to b. Step 3 : Repeat the steps 1 and 2 until value of b becomes 0. Step 4 : If b=0 then return value of a as the GCD value of a and b. Step 5 : Stop. Cc program ponneeeensenes Program to find out the greatest common divisor of the two integers. seneeeenseseeunaaeaneen] #include #include TECHNICAL PUBLICATIONS® - en up-thrust for knowedge eo Progamming, and Data Structures 1-35 _C Progzatnening, Pundarnentals #include void main(void) { int a,b,ans; int ged(int a,int b); clrscr(); print{("\a\t\t GED Of two integers") printf("\n\n Enter the two numbers: " scanf("%d %d",8a,&b); ans=ged(a,b); print{("\n The ged of %d and %d is = %d",a,b,ans); getch(); } int ged(int a,int b) { int temp,ans; if( b<=a &&a%b return b; else { ifla 0" element + 1" element I+] = 2, ———> I element + 2"4 element 142 = 3, ———> 2" element + 3 element 263 = 5, ———> 3 element + 4'" clement 5 = 8, ———> 4" element +5" element y Let fib(0) = O,fib(1) = 1,We can define the recursive definition of Fibonacci sequence by the recursive definition : - @) fib(n) = nif n=0 or n=1 fib(n) = fib(n-2)+ fib(n-1)if n>=2 Let us apply this definition to compute fib(6) fib(6) = fib(4) +fib(5) using definition (2) fib(4) = (fib(2)+ib(3)) fib(6) = (fib(2)+fib(3)) +fib(5) .... where fib(2) is fib(0)+fib(1) .. fib(0)=0 and fib(1)=1 where fib(3) is fib(1)+fib(2) = (fib(0}+fib(1))+fib(3)+fib(5) = 0+1+fib(3)+fib(5) = I+fib(1)+fib(2)+fib(5) .... = 1+1+fib(2)+fib(5) ..fib(1) is 1 and fib(2) = fib(0}+fib() = 2+fib(0)}+fib(1)+fib(5) = 2+0+1+fib(5) TECHNICAL PUELICATIONS® - an up-thrust for knowledge C Programming, and Data Structures B4fib(S) 34fib(3)+fib(4) S+fib(1)+fib(2)+Fib(4) 341 +fib(2)sfib(4) 44+fib(0) +fib(1)+fib(4) 4+0+14+fib(4) 5+fib(4) 5+fib(2)+fib(3) S+fib(0}+fib(1)+Fib(3) 5+0+1 +fib(3) G+fib(1)+fib(2) G+1+fib(2) 7+fib(0}+fib(1) = 74041 Hence —_fib(6) = 8 C Programeing, Fundamentals Here the recursive definition appears twice e.g. fib(6)=fib(4)+fib(5). Algorithm for Fibonacci series by recursive method : int fib(int n) { int x, if(n<: retum n; (n-1); y=fib(n-2); retum (x+y); } Algorithm for Fibonacci series by iterative method : if(n<=1) return (n); TECHNICAL PUBLICATIONS® - an up-thrist for knowtedge C Programming and Data Structures 1-28 C Programming Fi i<=ni++) retum (b); C Program Program for computing the number in the fibonacci series at certain location.For e.g.the sixth number in fibonacci series will be 8.The fibonacci series is 11235 8 13 21 34... “header files*/ #inslude #include void main(void) ¢ n.num:; int Sibtint n); ctrscx(); printf"\n Enter location in fibonacci series: scanf("d",&n); num=sb(n); printfi"\n The number at %dth position is %d in fibonacci series'.n.num); getch(); } . int fib(int n) { int xy: - if(n<=1) retum n; x=fib(n-1); y=fib(n-2); retum (x+y); } poreee > +*99* End of Program ***#ts###eewweee TECHNICAL PUBLICATIONS® - an up-thrust for knowledge CProgeammin 1a Output Enter location in fibonacci series: 9 ‘The number at 9th position is 34 in fibonace/ series [84] toner of Hanoi The problem is the “Towers of Hanoi”. The initial setup is as shown in Fig, 1.9.1. Ps a | Fig. 1.9.1 ‘There are three pegs named as A,B and C. The five disks of different diameters are placed on peg A. The arrangement of the disks is such that every smaller disk is placed on the larger disk. ‘the problem of “ Towers of Hanoi” states that move the five disks ftom peg A to peg! C using peg B as a auxillary. * The conditions are : i) Only the top disk on any peg may be moved to any other peg. ii) A larger disk should never rest on the smaller one. The above problem is the classic example of recursion. The solution to this problem is very simple. First of all let us number out the disks for our comfort A B c 1 Fig. 1.9.2 The solution can be stated as ‘1, Move top n-1 disks from A to B using C as auxillary. 2. Move the remaining disk from A to C. 3. Move the n-1 disks from B to C using A as auxillary. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming and Data Structures We can convert it to move disk move disk move disk move disk move disk move disk move disk move disk move disk move disk move disk move disk move disk move disk move disk n TECHNICAL PUBLICA’ Tions® from A to B. from A to C. from B to C. A from A to B from C to A from C to B from A to B from A to C from B to C from B to A from C to A from B to C from A to B from A to C from B to C € Programming Funda, A uk Fig. 1.9.3 Fig. 1.9.4 Fig. 1.9.5 = an up-thrust for knowledge C Programming and Data Structures 1-31 _C Programing, Fundamentals A B c Fig. 1.9.6 Thus actually we have moved n-1 disks from peg A to C. In the the remaining disk from A to C. 5 ‘c’ Program) same way we can move [ttsneneneenerenenenserruanennanaesasssasiaasasensesesesnenaases Program For Towers of Hanoi.The input will be the number of disks for which the program should operate. #include #include #include void main(void) { int n; void towers(int n,char from,char to,char aux); elrser(); printi(“\n\t\t Program For Towers Of Hanoi” printf("\n\n Enter the total number of disks"); scanf(" towers(n,'A','C','B’); getch(); } void towers(int n,char from,char to,char aux) { /*if only one disk has to be moved*/ ifm==1) { Printf("\n Move disk 1 from %c peg to %c peg’ from,to); Tetum; } /*move top n-1 disks from A to B using C*/ towers(n-1,from,aux,to); TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming and Data Structures 1-32 criogiantilh printf("\n Move disk %d from %c peg to %c peg",n,from,to); /* move remaining disk from B to C using A*/ towers(n-1,aux,to,from); } Output Program for Towers of Hanoi Enter the total number of disks 4 Move disk 1 from A peg to B peg Move disk 2 from A peg to C peg Move disk 1 from B peg to C peg Move disk 3 from A peg to B peg Move disk 1 from C peg to A peg Move disk 2 from C peg to B peg Move disk 1 from A peg'to B peg ‘Move disk 4 from A’peg to C peg Move disk 1 from B peg to C peg ‘Move disk 2 from B peg to A peg Move disk 1 from C peg to A peg Move disk 3 from B peg to C peg Move disk 1 from A peg to B peg Move disk’2 from A peg to C peg _ Move disk 1 from B peg to C peg 1.9.5 Ackerman's Recursive Function The Ackerman's recursive formula is as given below 2A, n= n +1 forn 20 = A(m, 0);= Am - 1, 1) form>0 -1, Am, n-1)) form,n>0 AG, n)= A(m Ex. 1.9.2 Solve AQGYD using Ackerman’s function = A(m-1,A(m,n- 1) = A(1,A (2,0) TECHNICAL PUBLICATIONS® - an up-thrust for knowledge (C Programming and Data Structures 1-33 =AWLAQ-1,1) = A(LA(L1) = A(L, [AQ -1, A (1, 0)))) = A(LA(@A (1,0) = A(LA@AQ, 1) = A(WLA@2) = A(13) ~(l) A(L,3) = A(1-1,A (13-1) =A@A(L2) = A@A(Q-1A(,2-1)) = A(0,A(,A (1,1) = A(@A(Q,A(1-1,A(1,1-1))) =A@A(@,A(,A (1, 0) =AGAOGAGAQ, 1) =A@AOAO2) =A@A@3) ALD = A@4)=5 ~@) Putting value of equation (2) in (1) ; AQ) =5 Ex. 1.9.3 Compute A(,1) using Ackerman’s formula, Solution : Let us compute A(1,1) A(L1) = A(m-1,A(mn-1)) = A@A(L0) = A@,A(m-1,1)) = A@A(O1) ~) AQ) = nt1=2 TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming and Data Structures 1a _€ Programming Putting this value in equation (1) we will get A(LA) = A@2) = nt = 3 ¢ Function int ackerman(int mm, int n, int &count) { count++; AQ, n)=n+ 1 forn20 if(m == 0) { retum (n + 1); } A(m, 0):= A(m - 1, 1) form>0 if (n == 0 && m>0) { retum ackerman(m - 1, 1, count); if (m>0 && n>0) ‘A(m, n):= A(m - 1, A(m,n-1)) form,n>0 { eee | return ackerman(m - 1, ackerman(m, n - 1, count), count); } } C Program #include #include #include int ackerman(int m, int n, int &count) { count++; if (m == 0) { return (n + 1); 0 && m>0) *. return ackerman(m - 1, 1, count); TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming and Data Structures if (m>0 && n>0) % C Programming Fundamentals { return ackerman(m - 1, ackerman(m, n - 1, count), count); } + int main() { int m,n; printi("\n Enter value of m: scanf("%d", &m); printi("\n Enter value of scant("%a", 8n); int count 5 printf("%d", ackerman(m, n, count)); } Output Enter value of m: 2 Enter value of n: 1 5 1.9.6 Comparison between Iteration and Recursion Iteration : Recursion. Iteration is a process of executing certain set of instructinos repeatedly, without calling the.self function. _ Recursion is a process of executing certain set of instructions repeatedly by calling the self function repeatedly. ‘The iterative functions are implemented with the help of for, while, do-while programming constructs. Instead of making use of for, while, do-while the repeatation in code execution is obtained by'calling the same function again and again ‘over some condition. The iterative methods are more efficient because of better execution speed. ‘The recursive methods are less efficient. Memory utilization by iteration is less. Memory utilization is more in recursive functio: It is simple to implement, Recursive methods are complex to implement. The lines of code is more when we use iteration, ~ Recursive methods bring compactness in the program. TECHNICAL PUBLICATIONS® - an up-thrust for knowiedge C Programming and Data Structures 1-36 C Programming Fundayy | Review Question 1. Explain recursion and write a C program to print the first 'n' numbers it the Fibonacg, series using recurs Arrays Arrays can be defined as a set of pair-index and the value. Two basic ope! be performed on arrays are Storing of data at desired location or index and retvievin rations that eg, data from desired location (index). a2] a3} aft} af5]_af6)_ a7) al8_ 219) a [10 | 20 | 30 | 40 50 so | 70 so | 90 100 Fig. 1.10.1 Array as index and value pair Advantages of Arrays 1. Elements can be retrieved or stored very efficiently in array with the help of index or memory location. 2 All the elements are stored at continuous memory locations. Hence searching « element from sequential organization is easy. Disadvantages of Arrays 4. Insertion and deletion of elements becomes complicated due to sequ ring the data large continuous free block of memory is required. ential nature, 2. For ste 3. Memory fragmentation occurs if we remove the elements randomly. ‘Syntax The syntax of declaring an array is datatype __ mam For example, int a [10]; double b{10] [10]; Here ‘a’ is the name of the array inside the square bracket size of the array is given. Thi array is of integer type i. all the elements are of integer type in array ‘a’. Similarly array may be of user defined type, called as array of structure C supports both one dimension2 and multidimensional arrays. Initialization + It is possible to initialize an array during declaration only. For example int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8 9; TECHNICAL PUBLICATIONS® - an up-thnust for knowledge € Programming and Data Structure tary Prop ermog Funland + The list of values, enclosed in braces {J, separated by commas, provides the initial values for successive elements of the array. «If there are fewer initializers than elements in the automatically initialized to 0. For example, int a[10] = {0, 1, 2, 3, 4, 5, 6); array, the remaining elements are would initialize a[7], a[8], and a[9] to 0. + When an array definition includes an initializer, the array dimension may be omitted, and the compiler will infer the dimension from the number of initializers. For example, int bf] = (10, 11, 12, 13, 14); would declare, define, and initialize an array b of 5 elements. Here only the dimension is omitted; the brackets [] remain to indicate that b is in fact an array. 4.10.2 | Single Dimensional Arrays “ Array can be one dimensional-and two dimensional. For example You can visualize one dimensional array as : we) Here a[2] = 40 Actual value at some index ale] = 75 Fig. 1.10.2 Array a[10] Note that the elements in array are always stored in contiguous memory locations. Now let us see how to handle this array. We will write a simple C program in which we are simply going to store the elements and then we will print those stored elements. ¢ Program #include #include . main() TECHNICAL PUBLICATIONS® - an up-thrust for knowledge a € Programming and Data Structures Less = Programming Funding = { int a[10],index; elrser(); printf("\n Store The Elements In An Array for(inde: -index< =9;index+ +) scanf("%a" &alindex)); printf("\n You have stored these numbers in the array a"); for(inde: ;index< =9;index+ +) printf("\n &d",alindex}); } 4.10.3 | Two Dimensional Arrays The two dimensional array is something which you can compare with the two storic building! Extra space which is arranged in rows and columns. Let us draw @ figure whic will represent the two dimensional array. a Fig. 1.10.3 Two dimensional array The syntax of two dimensional array is : Data_type Name_Of_arraylrow_size][column_size]; For example int af10}{10); By this allocation the memory block of 10 x 10 =100 is getting created. The nested oops can be effectively used to access all the elements of an two dimensional array: will take a sample example to explain this idea. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge ming, and Data Structures 1-9 C Programmning, Pundamentals scanfi("%d" Bealillil); } } Execution of Nested for Loop Initially the value of i-0 at that time j-0 it will store the element in a{0}[0] j-1 it will store the element in a{0]{1] j-2 it will store the element in a[0]{2} Next time i will be incremented by 1 and now Again je0 it will store the element in a[1][0] j=1 it will store the element in a[1}[1] je2 it will store the element in a[1][2] Next time i will be incremented by 1 and now i j-0 it will store the element in a{2][0] jel it will store the element in a[2][1] j-2 it will store the element in a[2][2] \ Since now value of i and j has reached to 2 the scanning procedure will get terminated as condition is i<-2 and j<-2. Thus all the elements from a[0][0] to a[2][2] get scanned. Array positions \\ 200 \. abt a0z ato “alt ai2 azo ‘2et 322 Fig. 1.10.4 al0}[0] to a{2]{2] ve[ EX $10.1 How two dimensional arrays are created in C? Write a C program to generate @ population survey having citizen's record stored as a collection .of year-wise population. ‘AU : May-19, Marks 7 Sol. : Two dimensional array - Refer section 1.10.3 #include int main () TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming and Data Structures rao { int arr[3][3] i: for (i=0;1<3;i+ +) { printf(’\nEnter the population for country#%d'(i+ 1); for (j=0;<3++) ‘ - printf("\n Enter the population for Year#%d",(j+1)); scanf("%d",&arrli fj); } printf("\n printing the population ....\n"); printf("\n\t country#1 country#2 country#3\n"); printf("\n- --\n"); for(i=0: { i++) printf("Year#%d |"\(i+1)); for §=0;j<3;j++) printf("\t%dL"arr[il [j]); } printf("\n"); } return 0; 4_| Simple Programs > Program 1.11.1 : Sorting Program [eeeneea tenn ne nnn RRNA RAR RE AA ARN ARNE REA TAIT EY Program for sorting the elements een R DERE EERE REE REI EERE STII RTIR /* Header Files*/ #include #include #include /*Declaration*/ a. TECHNICAL PUBLICATIONS® - an up-hrust for knowledge C Programming, and Dato Structures 14 C Programming Fundamentals void sort(int a[20],int n) { int i,j.m,temp; int main() { int n, reverse = 0; printi("\nEnter a four digit number: scanf("%d",8n); while (n != 0) { reverse = reverse * 10; int digit = n%10; ; TECHNICAL PUBLICATIONS® - an up-thrust for knowledge ‘C Programming and Data Structures 1-50 C Programmi Teverse = reverse + digit; n = n/10; } printf("\nReverse number is = %d", reverse); retum 0; ) - _ _ —== —— Ex.L11.2: Write a C program to find the following, where A, B and C are the matricg, whose orders are M*N, M*N and N*N respectively, A = A+tB"C Sol. : #include int main() { ha int A[3][3],B13][3],C[3}[3],Temp|3}13),i,.4.m,n; printf("Enter the order of the matrix::\n'); scanf("%d%d",&m,8n); printf("Enter the A matrix: for(i=O;i # include main() 1 int a[10], index; elrser(); printf (In Store The Elements In An Array a’); for (index = 0; index < = 9; index ++) TECHNICAL PUBLICATIONS® - an up-thrust for knowledge C Programming Pundamentals scanf("%d", &alindex|);//storing elements in array printf ("\n Retrieving the array elements"); for (index= ; index<=9; index++) printi("%d", alindex]); //retrieving elements from array } Q.11 List the primary data types in C. ee ‘Ans.: Primary data types in C are as given below Primary data types t | T 4 char_| int] float [voi ned | | unsigned} | signed | [unsigned Fig. 4.12.1 long double 12 What are string operations defined in C ? Ans.: Various string operations defined in C are - D strlen : For Finding out length of string 2) strepy( : For copying the one string to another 3) strcat() : For concatenating two strings | 4) stremp() : For comparing two strings 5) strrev() : For reversing two strings Q.13 What Is a static variable ? Give an example. : . En Ans.: Static variables are those variable that retain their values even after they come out of the scope. For example #include int fun() { static int count =0; count ++; retum count; TECHNICAL PUBLICATIONS® - an up-thrust for knowledge Programming Fundag, C Programming and Data Structures 1-56 } int main() { printf("\n%q" fun()); printf("\n%q°fun()); printf("\n%q",fan()); printf("\n%d" fun()); return 0; } Output Rone as input. EEE Q.14 Write a C program to get a paragraph of text Ans. : #include int main() { char para[100}; printi(Enter Paragraph : ") scanf(%| *\t]s", para);//accept printf(‘Accepted Paragraph : %s", para): all the characters except tab return 0; t Q.15 How an n dimensional array is represented ? 'A multidimensional array is declared using the following syntax : [dn]; dn is the size of final dimension. Ans. = type array_name|d1}{d2][43][441. where each d is a dimension, and tual syntax for 3D array is this : The concept 1y_name|table}[row]{column}; data_type ara’ Q16 Differentiate between row mn major representation of arrays. major and colin s of the rows of the array @ major order, consecutive element ecutive elements of the columns @ Ans.: In row: in column-major order, cons contiguous in memory; contiguous. The difference be! the dimensions is reversed. tween row-major and column-major order is simply that the order ( at TECHNICAL ‘PUBLICATIONS® - an up-thrust for knowiedge C Programming - Advanced Features ‘Syllabus Structures - Union - Enumerated Data Types - Pointers : Pointers to Variables, Arrays and Functions - Fite Handling - Preprocessor Directives. Contents 2.1. Structures 2.2. Union 2.3. Difference between Data Type, Structures and Unions 2.4 Enumerated Data Types 2.5 Pointers 2.6 Arrays and Functions 2.7 File Handling 2.8 Preprocessor Directives 2.9. Two Marks Questions with Answers ~ @-1)

You might also like