0% found this document useful (0 votes)
126 views108 pages

IP Book (PDF) - Techmax

ip

Uploaded by

kfv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
126 views108 pages

IP Book (PDF) - Techmax

ip

Uploaded by

kfv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 108
Imperative Programming Prof, Smruti Nanavaty, Prof. Deepali M. Deshmukh, Prof. Dimple Bavlechs, Prof. Pankaj R. Chandre (EY. BSc. - Semester, Information Technology, MU) Copyright © by Tech-Max Publications. All rights reserved. No part of this publication may be reproduced, copied, or stored in a retrieval system, distributed or transmitted in any form or by any ‘means, including photocopy, recording, or other electronic or mechanical methods, without the prior ‘writen permission ofthe publisher “This book is sold subject to the condition that it shall not, by the way of trade or otherwise, be lent, resold, hired out, of otherwise circulated without the publisher's prior written consent in any form of ‘binding or cover other than which it is published and without a similar condition including this condition being imposed on the subsequent purchaser and without limiting the rights under copyright reserved| above. First Edition: August 2016 ‘This edition is for sale in India, Bangladesh, Bhutan, Maldives, Nepal, Pakistan, Sri Lanka and| designated countries in South-East Asia. Sale and purchase of this book outside of these counties is| ‘unauthorized by the publisher. Printed at : Image Offset, Dugune Ind. Area Survey No. 28/25, Dhayari, Near Pari Company, ‘Pune 41, Maharashtra Stat, India E-mail: rahulshahimage@ gmail.com ISBN 978.93-5077-564.6 Published by ‘Tech-Max Publications Head Office : B/S, First floor, Maniratna Complex, Taware Colony, ‘Aranyeshwar Corer, Pune ~ 411 009. Maharashtra State, India Ph : 91-20-24225065, 91-20-24217965. Fax 020-24228978, Email: [email protected], Website: www techmaxbooks.com Branch Office : Ground Floor, A-133, Okla Phase-II, New Delhi - 110020 (FID : TM309) (Book Code : M1023) Dear students, We are extremely happy to present the book of “Imperative Programming” for you. We have divided the subject into small chapters so that the topics can be arranged and understood properly. The topics within the cchapters have been arranged in a proper sequence to ensure smooth flow of the subject. ‘We are thankful to Sri. Pradeep Lunavwat and Shri. Sachin Shah forthe encouragement and support that they have extended. We are also thankful to the staff members of Tech-Max Publications and others for their efforts to ‘make this book as good as iis. We have jointly made every possible efforts to ‘eliminate all the errors in this book. However if you find any, please let us ‘know, because that will help us to improve further. We are also thankful to our family members and friends for their patience and encouragement. Syllabus UNIT I Introduction : Types of Programming languages, History, features and application. Simple program| Togic, program development cycle, pseudocode statements and flowehart symbols, sentinel value to end ‘program, programming and user environments, evolution of programming models, desirable program| characteristics. Fundamentals: Structure of a program. Compilation and Execution of a Program, Character Set, identifiers and) Keywords, data types, constants, variables and arrays, declarations, expressions, statements, variable |void abe(); lint main() it lint x= 5, y=10; // variable x & y are local to main method lorintf("\n values of variables from main method are : x = ed and y ~‘ed", x, y); label)2 i lvoid abc() HK lint p'= 15, q= 20: |/+ variables p & q are local to abc( ) method however variables x & y are not and any lattempt made to tefer these variable will give error. */ lprintf(*\nvalues of variables of abc( ) method are : p= %ed and q = %d",p, 4); } Output values : x= 5 and y= 10 values : p= 15 and q= 20 Example of global declaration fyincludecstdio.t> |void abc(); tnt x5, y= 10; lint p= 15, q= 20; lint man() i Jprintf(” falues of all variables that belongs to main function’) panti("\ivalues: x=Yodoy-Med:p=Med:qetd", xy,P.4); fabet )s i juoid abet ) H{ lprintf("\n\nvalues of variables accessed from abc( ) function"); lrintf("\nvalues: x=Yed:y=Mod:pmtediqn%d, x,,p.0): y ‘Syllabus Topic : Statements 1.19 Statements @, What is Statement ? Statements in C are like sentences in text. Every C statements performs an action. Every C statements ends with a semicolon (;). For example, the simple statement printf(‘my first program”); sends the text “my first program” on the screen. Besides simple statements, C also supports compound statements. A compound statement is a set of simple statements enclosed inside curly braces, { and }. To understand the concept of compound statements, we will give an example of if statement. If statement allows one to take decision, If we have the if statement if3>1) printf(‘three is greater than one”); © If the condition (3>1) turns out to be true, statement after if statement is executed. As, 8 is indeed greater than 1, condition 3>1 will turn out to be true, which will cause execution of the next statement. The message “three is greater than one” will be displayed. In case, we wish t execute a set of statements if the given condition turns out to be true, we can use a compound statement. ffcsa) ig printf("three is greater than one”); printf(” really !"); 324 Programming Fundamentals, * Compound statement, in the above example consists of a pair of simple statements. These two statements have been written inside a pair of curly braces. 1.20 C Tokens, Instructions and Comments 1.20 C Tokens, Instructions and Comments 1.20.1 © Tokens @. Whats Token? Enlist diferent types of tokens in C. In C programs, the smallest individual units are known as tokens, ‘CTOKENS 1.20.2 Instructions @. Explain different types of instructions in C. imperative Programming (B.S0-1T-MU) 4.25 Programming Fundamentals C Instructions “Type decfaration Arithmetic, Controt instruction, instruction instruction a of Declare type of variable | Arithmetic operations ! used to control the sequence lused in the program — are performed. of execution of various statement ike: 5 ke: inac program. int i beatb: lke:- float b; S sub=a-b; if-else for while,de-while etc. char ¢; mutt 4.20.3 Comments @. How we can. comments in C program? In the C Programming Language, you can place comments in your code that are not executed as part of the program. A comment starts with /* symbol and ends with */ and can be used anywhere in your program. ‘Comment in single line (Start with two forward stash) Syntax // Author: Techmax Publication Comment in Multipl Syntax | /* Author: Techmax Publication Addition of two numbers */ ‘There are three types of instructions in C. (Type declaration instruction (i) Arithmetic instruction (ii) Controt instruction 21 Symbolic Constant Q. Whats symbolic constant ? Asymbolic constant is name that substitute for a sequence of character that cannot be changed. The character may represent a numeric constant, a Imperative Programming (8.So-1T-MU) 425 Programming Fundamentals character constant, or a string. When the program is compiled, each occurrence of a symbolic constant is replaced by its corresponding character sequence. A symbolic constant is defined by writing Iddefine name text ‘Where, name represents a symbolic name, generally we write in uppercase, and textrepresents the sequence of characters that is associated with the symbolic name. For example lddefine PL 3.14 l#define TRUE 1 lidefine FALSE 0 Hadefine PUBLICATION “techmax” > Program 1.21.1: Write a program to find area of circle. lddefine PI 3.14 void main() Ht double r = 20. double area; atea= PLT 1: printf("\nArea of circle = %f" area); i Output |Area of circle = 1319,585 Review Questions Q.1 Write shor introduction about Q.2 Write an applications of 2.8 Explain diffrent foaturoa of C Q.4 Explain diferent types of programming language. @.5 Whatis simple program logic? Q.6 Write stops of program development ite cycle. Eh pert rosaming Set a7 ae 1" 12 13 ‘4 18 16 7 18 peeseepee ee 2 Q.20 a2 22 Q.23 24 Q.25 26 a2 Q.28 Q.29 i Programming Fundamentals Wiite a short note on flowchart with its symbols. Write algorthm to find average marks of 8 subjects of the student. And also draw the flow chart. Write a shor note on Pseudo Code. What must be taken care at the writing ofthe pseudo code? ‘Write an example of pseudo code. ‘Write sentinel value to end a program. \Write short note on programming and user environments \Write short note on evolution of programming models. Write some of the desirable program characteristics. ‘Write the structure of C program with explanation’? Explain compilation and execution of a program, Write short note on character set What is identifiers 7 What is keywords ? Enlist the keywords Explain diferent types of data type. Write short note on constants. Explain variables with the help of example ? How to declare variables in ©? Explain with example. ‘What is Statement ? ‘What is Token? Enlist diferent types of tokens in C. Explain diferent types of instructions in C. How we can comments in C program? What is symbolic constant ? oor Imperative Programming (8.Se-tT-MU) 1.28 Programming Fundamentals eau) Operators, Expression and Data I/O syllabus Operators and Expressions : Arithmetic operators, unary operators, relational and logical operators, assignment operators, assignment operators, the conditional ‘operator, library functions. Data Input and output : Single character input and output, entering input data, scant function, print function, gets and puts functions, interactive programming 21 Operators and Expressions [@) What are operatore and expressions ? + Symbolic shapes that are used to perform all different types of mathematical or logical calculations are called as operators. + When two or more values or variables having stored values are attached with each other to perform some specific computation then it is called as an expression. + We will be able to witness finite examples of all these in the theory discuss below. lif (Expressions is true, example if (x >y)) \\Execute all statements from here (if expressions is FALSE, example if (oy) is not true) \\Execute all statements from this else block I r FP imperative Progamming (8.S21T-MU) 22 Operators, Exprssion end Data WO eee ‘Syllabus Topic : Unary Operators 2.1.1. Unary Operators @. Define unary operators. * Unary operators are those operators which operate on only one operand. © Operation like i++, which is same as i= i+ 1, is an operation that is performed on only one operand and that is i. So these types of operations are termed as unary. © ‘There are 6 unary operator supported by C programming language. Unary operators are listed below. ~ | bitwise complement 1 | logical not - | unary minus + | pointer indirection & | address of + | unary plus 24.2 Binary Operators Er ingore Poparming GSesTA) 23 pert, Exrossion and Data vO ee Syllabus Topic: The Conditional Operators 21.3. Ternary Operators / Conditional Operators [Er Det oar oper or contol pao wh eam ‘Those operators that perform arithmetic operations on three variables are termed as ternary operators (i.e. Include three Operands). a Condition ? Statement 1: Statement 2; es Tne @. Explain binary operators. «Those operators that perform arithmetic operations on two variables are termed as binary operators (i.e. Require two Operands). ‘Oporator ab C=a-b Vv Operands For example: a= 10 and b= 20 © Operation like ¢ = a + b, is performed using two variables attached to the operator “+” on both sides. So, these types of operations are termed binary. | Syllabus Topic : Arithmetic Operators 21.4 Arithmetic Operators | Type of Operator | Name and Functionality Example + Phus ~ Addition 24+3=5 : ‘Minus - Subtraction 5-3-2 sg Star - Multiplication 5*2=10 i Slash — Division 8/224 PEE iporatve Programming (BS0-T-MU) 24 operators, Expression and Data lO ‘Type of Operator ‘Name and Funetionality Example 9%2=1 Percentage ~ modulus Double Plus - Increment Double Minus - Decrement i++ is same as izi+1 - is same as Program that expl operator ins working of arithmetic = Sed \n" hk); = %d \n ‘ed \n"sK) keifi, printf) = ed \o" A): eines printf("Remainder when i divided by j = %d \n".k); return 0; i} De eee Output lnj=5 ij=1 lint itei=t r [Bf epaive Prngaming Se) 28 costo, Bgrsson ans Daa YO 24.8. Increment and Decrement Arithmetic Operators Gi Bape pre increment and post increment with suitable example. la. Explain pre decrement and post decrement wih sultable example. ‘These are unary operators that perform operation on single eperand where value of the variable or operand is increased (in case of increment operations) or decreased (in case of decrement operation)by one. Increment operator (++). «Decrement operator (—~) Tremont operaion =) Pre Iorement (inom rt and then assign) + a= 10, bata Output aati ban Poa inorement (Asalan frst end then increment) Pre Decrement Post Decrement (Qeorement test and then assign) (Assign fist and then Decrement) 0; aut ° 8 ceore > Program 2.1.2: Program that explains working of increment and decrement operator “float 2 = 10.2, p= 20.2; =r) _ BEF imperative Programming (8Se-1T-MU) 2-6 Spero Expression end Date lO FF imperative Programming (B.Se-1T-MU) 2.7 ‘Operators, Expression and Det VO Drintf('+4x = ted. \n", 4x); Operator Meaning Use | Output printf("--y = Sed \n", —-y)e | printf(‘+42 = 96f \n", +42); Equals to 1-true printf("--p = %f \n", —p); return 0; 0- false It 1 Not equal to 1-true Output 101=10 | 0-false ee Syllabus Topic : Logical Operators y= levzett.2 24.7 Logical Operators (Logical Connectives) |-p19.2 Gl_List the logical operators used in 'C | Syllabus Topic : Relational Operators © Logical operators usually used with conditional statements. + Logical operators supported by C programming languages are listed below. 216 : a Relational Operators a Tas | Q. Wile short note on relational operators. && | Logical And | (a5) |1-true I} Relational operators aro used to perform comparison. Relation operators 0- false always results into Boolean value which is either 1 for — TRUE and 0 for I] | Logical Or |(a 100)| 1-true — FALSE, Relational operators supported by C programming language are listed 0- false bal 1 | Logical Not | a 10<10 | 0- false Winclude lint main() if > | Greater than a>b | 1-true 10>10 | 0-false int x=2, y= 3, z= 6, Finalvalue; less than equalto |a<=b |1-true | 10.<= 10 | 0- false Finalvalue = (x = | Greater than equal to 1-true Finalvalue = (x -y) && (2= 10 | 0- false erators, Expression and Data VO [EP imperative Programming (8.Se1TMU) 28 ry Finalvalue = (x y) results to 1 I(x =y) 88 (2 Right Shift Operators, Expression and Data VO [F imporaive Programming (BSeAT-MU) _ 22 2.1.8.1 Truth Table and Example of Bitwise Operations itwise AND ‘Truth Table Example a 1984 ° 11 0tpis 2 o1oops o 1 Bitwise OR Example 114 Tiotpis or oops Bitwise XOR (*) Right shift (>>) THE 00001101 is shifted rane right by 2 bits oo Lett Shitt (<<) oTo (00001101 is shifted left by 2 bits ne eo EP imperative Progamming (.S2-E-MU)__210 Operators, Expression and Data UO Bitwise Complement Bitwise compliment operator is a unary operator (works on one operand only), It changes the corresponding bit of the operand to opposite bit, ie., 0 to 1 and 1 to 0. It is denoted by ~. ‘85 = 00100011 (In Binary) Bitwise complement operation of 35 ~ 00100011 11011100 = 220 (In decimal) ‘Twist in bitwise complement operator in C Programming Output of -35 shown by compiler won't be 220, instead it shows -36. For any integer n, bitwise complement of n will be (n+1). To understand this, you should understand the concept of 2's complement. ‘Syllabus Topic : Assignment Operators 2.1.9 Assignment Operators Explain assignment operators with example. Imperative Programming (B.Sc-IT-MU) 2-11 Operators, sion and Data VO Type of ‘Name and Functionality Example Multiply and assign operator. Firstly multiplication operations performed and then final value is transferred to the variable on left hand side XY Is same as =X*Y Divide and assign operator. Firstly division operations performed and then final value is transferred to the variable on left hand side Xie¥ Is same as Find modulus and assign operator. Firstly mod operations performed and then final value is transferred to the variable on left hand side X%eY Is same as X=X®Y << Shift left value to variable on left side by number of bits specified on right side and assign resulting value back to variable on left side X Shift right value to variable on left side by number of bits specified on right side and assign resulting value back to variable on left side ‘Add and assign operator. Firstly addition | x ,_ y operations performed and then final value is transferred to the variable on left hand side Is same as X=X+Y Subtract and assign operator. Firsly | x __y subtraction operations performed and then final value is transferred to the variable on left hand side Is same as X=X-¥ Do bitwise AND operation on value of variable on left side by number of bits specified on right side and assign resulting value back to variable on left side X&=2 Do bitwise Ex-OR operation on value of variable on left side by number of bits specified on right side and assign resulting value back to variable on left side xA Binpenmeropemns cesta) 212 opatos, exmenen anon 0 Program that explains working of assignment operator > Program 2.1.4: lint main() is a int x6, ys yex printf'y = "ed \n"y); Yann dy= yew printf("y = ted \n".y); ya Wy=y% printf(*y = %ed \n"y)i y tax Hy-y printf("y = ed \n"y)s yi Hy= vie printf("y = %d \n“y)s yew printf(*y = %d \n"y)i return 0; dynes i} Output ly=4 ly=8 ys ly~16 ly=4 ly=0 ere cer ee eee eens Operator precedence will decide which operator is to be evaluated first, and ‘which operator should precede the order. Associativity describes whether the expression is to be evaluated from right to left or left to right. All C operators, their precedence and associativity are presented in Table 2.2.1. Table 224 Precedence | Operator Category | Operator _| Associativity 1 Unary operator = RoL 2 Arithmetic operator | */,% Lok 3 Arithmetic operator_| +,- L>R 4 Relational operator _| <,>,<: L>R 5 Equality operator LoR | 6 ‘Logical operator &&,|| RoL fa Assignment operator | =,+=,-=,*=/=,%= |R->L 8 Bitwise Operators _| -, >>, <<, & |, *|L->R Example 15-2* (6 +18)/3+6 5-2*24/3+6 = 15-49/3+6 5-16+6 =-1+6 3_Type Conversions / Type Casting 2.2 Operator Precedence and Associativity @. Explain Operator Precedence and Associativity. @._ Wiite short note on implicit and explicit type conversion. It is a technique of converting data type of one variable to another as and when required. There are two ways of doing this "The operator precedence is a theory that decides about the priority of processing/Evaluating the given expression. Implicit type casting/conver Ex type casting/conversion [ZEP imperative Programming (B.Sc-(T-MU) 2-14 1. Implicit Conversion poretors, Expression and Data VO ‘© Implicit conversion is a conversion that is done by compiler itself automatically without coders interventions through code. * We know it very well that total size of inter type variable is 32,768 to 82,767 where as size of float type of variable is -1.2E — 38 to 3.45 + 38, ‘This becomes easy for compiler to have a value converted from integer type variable converted in to float type without any operations. It is just a promotion of value from int to float. Example inciudeestdio.t> |#include oid main) fC int x-10; double y; drs yrs: // This is a automatic implicit conversion printf” value of variable y after implicit conversions is %bd".y); sgetch(); ib Output value of variable y after implicit conversions is 10 2. Explicit Conversions ‘When interpretation is between a variable having a data incompatible data type with respect to size and type both coder need to code for explicit conversion and is not taken up by compiler automatically. Example * Inta=2; © Flosth © Chare='A' © D=float(c); // Sets f= 65.0 © a=intlh* 3); // Sets ato7 uf imperative Programming (B.Sc-IT-MU) 245 ‘Operators, Exoression and Data VO. Example of integer and float conversion Operation | Result 5/2 al 5/20 2.50000 5.0/2, 2.50000 215 0 2.015 0.40000 205.0 0.40000 2.0/5.0 | 0.40000 2.4 Input and Output Functions Fig. 2.4.1 explains about the functions that are used for obtaining input as ‘well disclosing output in ¢ programming language. ‘Console npuvoupattuncton ad = ' Input Output Input Output a Ea ° oe mt ae ce BS = Fig. 24.1 Syllabus Topic : printf () Function 24.1 printf () Function a printf ‘This fonction is used to display output on screen. How to use printf function. wte i's syntax. LEP imperative Programming (®.SeAT-MW) 216 Operators, Expression and Data UO EE trouve Pogaming .sesT4) 247 pra Sxpeson and Dtav0 Syntax For example 2 printf( “ format string” , list of variable ); void main() { backsash format specifier Format specifier ‘Meaning fe For a single character Sed or %i For an Integer/Decimal numbers f For float number alt Double aa Long int OLE Long double Unsigned ee For floating point data in exponential form %0, For octal value ex. For Hexadecimal value Backslash code| Meaning \n New line \a Alert (Beep sound) it ‘Tab(space) ny Asingle \ v 7 Ww > For example 1 printf( “ Yed*bc%ef*, a,b,c ); printf("TechMax Publication "); ——» without format specifier. ‘This will display TechMax Publication on the monitor. __ printh("™***\nitt#\t@@@"); \tt C@@ ‘Syllabus Topic : Entering Input data : scanf() Function 24.2 scant () Function (Entering Input data) [f@ How to use scant function ? Wie Re syntax aa ‘scanf() Data can be entered into the computer from an input device (like keyboard) using the function scanf. _ © This function is useful to accept any type of input, Syntax " scanf(“format specifier’, variable list): scanf (“format specifier” Garg, Bara2 [& (Ampersand) represent address. For example int number: " printf(“enter number”); -_seanf{"%sd" &number): Let’s take an example. > Program 2.4.1 idecstdio.h> //preprocessor directive clude //preprocessor directive ‘main() //main function CE imperative Programming @Se-FTMU) 218 Con, Egesionend Ose 19 (FF grave Pogaming BST) 218 Sperators, Exgteasion and Data UO trser(); /fdlear the screen printf("TechMax Publication”); //Display TechMax Publication on screen. getch(); —_//get single character. iF Output TechMax Publication Birthday wishes to the person. |/* To accept a name and display birthday wishes */ Winclude void main( ) it char name[20]; printf("your good name please : "); ‘scanf(""%s" name); printf("Hello %s”,name); printf("\nHappy Birthday to you"); y > Program 2.4.2: We will accept the name of a person and display Output lyour good name please : Vivek Hello Vivek Happy Birthday to you > Program 2.4.3: Program to add two numbers finclude \void main() { ‘nt a,b,sum; printf("\nEnter the value of a and b*); scanf("%d%ed", 82,8); value of a and b 50 60 ‘two number = 110 > Program 2.4.4 > Program 2.4.5 f(*\nEnter the value of a and b"); odd" a, 8); Imperative Programming (B.S0-fT-MU) __ 2-20 Output [Enter the value of a and b13 4 lo > Program 2.4.6 i#include void main() { ‘int a,b; printf("\nEnter the value of a and b : scanf(“%ed%d",&a,&b); printh(ed" (28); etch; y Output Ses Is Imperative Programming (B:So-IT-MU) _2-21 Operators, Expression and Data VO For example 1 [Enter the value of a and b : 13 4 4 ‘Syllabus Topic : Single character Input and Output 2.4.3 Single Character Input and Output 2.4.3.1 Single Output Character @. When wo use putch( function Q. What s the difference between puich() and putchar() functions ? In single output character, only single character is display on the screen. putch0 and putchar( are some single character library functions. @ putchd) Syntox lputch(variable_name); putch displays single characters to the screen. (putchard [BD Wer wo se puchard fanaion? Syntax ue ichar(variable_name); r Fi npeassregeerng ease) tes cunt tyme anianie PP mpuave Pozen Ses) 229 es putchar displays single character to the screen. For example For example findudesstio.t> ae [eid mang a iG ° char fe; i erdy patch Ener the van of ch iu chagetch(): — , _pitf(‘haracter vale = ech; fe Output For example BETSMico ace |void main() | |Oharacter value ~ p it chat eA; — putchar(‘e’); Like getch0), getche() also accepts only single character, but unlike getch(), } getche() displays the entered character in the screen. Output i | frariable_came = getche(); i = ~ (ii) getcharg ooo] Seve put Character getchar() accepts single character type data from the keyboard. @._ What are the aifaronce between gatcho, gotched and getchar) ? B Syntax In single input character, Only single character is accepted through [ffable name = getchar(); keyboard. geteh(), getche() and getchar() are some single character library functions. (i) getcho) It is used to input single character. It will instantly read a character and I Syllabus Topic : Gets() and Puts() functions t {does not require enter key to be pressed. | Syntax \variable_name = getch This function is useful to accept from the keyboard and store it into a variable. BP imperative Programming (@Sc-AT-MU) 224 Operators, Expression and Data io Syntax gets(str): ‘Accept a string from the keyboard and store it into the variable str. di) puts) This function displays a string on the monitor. Syntax puts(str); Content in str is displayed. r Fh pane roganming@setTMy 225 person, Seremion and Dan ————— Syllabus Topic : Interactive Programming 2.5 _ Interactive (Conversational) Programming Write short note on interactive programming. Computer program are made interactive, so that conversation become easy ‘retween the computer and the person using the program. For conversation, generally we use scanf and printf functions. Printf function is used for displaying data or information, scanf function is used for accepting actual data. For example want } Program 2.5.1: Program to find area of circle ~ — - ee fFincludecstdio.h> puts(Techmax Publication”); _//isplay Teehmax Publication onthe screen. Noid main() Example 2 it a at area; fincludecstdio.h> ~ printf*\nEnter radius"); Ifincludecstring.h> scanf("%f" 8); be main() | area=3.14*r*r; int(C%F* area); char stil}="techmax"; | Be: : puts(st); i} [Es eee Ce ee ee Output Sad ltechmax fenter radius 5 5000 Example 3 a ltinclude HHinclude lvoid main() t cchar str{}="techmax"; puts("str"); b Output str > Program 2.5.2: Program to find average of 3 numbers jfinclude id main() Ke | foat a,b,cave: | printf("\nEnter the value of a,b and c"); Scanf("%PPLP a Bb, Bc); avan(erbeo)/3: EER inperave Programing (8S0-ATMU) 226 Operators, Expression and Data VO amt ative Programming (B.S6-1T-MU) 227 Operators, Exression and Data VO printf(*Average = Sf", ava); getch(; Output Enter the value of a,b and c3.45 lAverage = 4.000000 iP > Program 2.5.3: A customer is offered 15% discount on the printed price of a book. The customer has to pay 7% sales tax on the remaining amount. Write a program in C to calculate the amount to be paid by the customer. lfinclude Htinclude |void main() Ht printf("\nEnter the price of book:"); scanf("%ef*.&price); dis_priceeprice-(0.15*price): printf("\nPrice after discount = %f*,dis_price): ‘taxe0.07*dis_price; printf("\nSales tax paid by customer {_amtedis_pricestax; printf(*\aFinal Amount to be paid by customer is: %&f",£_amt); sgetch(); ff tax); Output Enter the price of book:200 Price after discount : 170.000000 [Sales tax paid by customer : 12.900000 at a2 as a4 as a6 a7 as as 2.10 a1 012 a13 a4 as a6 a7 a8 a19 0.20 Review Questions What are operators and expressions ? Define unary operators. Explain binary operators. Define temary operators or conditional operators with example. List the arithmetic operators with example, Explain pre increment and post increment with suitable example Explain pre decrement and post decrement with suitable example. Write short note on relational operators. List the logical operators used in 'C What is bitwise operators. Explain its operation with suitable example. Explain assignment operators with example. Explain Operator Precedence and Associativity Write short note on implicit and explicit type conversion. How to use print() function. Write i's syntax. How to use scant) function ? Write its syntax. ‘When we use putch() function ? ‘What isthe difference between putch() and putchar() functions ? ‘What are the difference between getchi), getche() and getchar() ? What is the use of gets() function ? Write short note on interactive programming. oo0 LEP imperatve Proyamming (®.Se-AT-MU) 2.28 ‘Operators, Expression and Data UO CHAPTER Conditional Statements and Loops ‘Syllabus Conditional Statements and Loops : Decision Making Within A Program, Conditions, Relational Operators, Logical Connectives, If Statement, ItElse Statement, Loops : While Loop, Do While, For Loop. Nested Loops, Infinite Loops, Switch Statement ‘Syllabus Topic : Decision Making Within a Program. 3.1_Decision Control Structures (Decision Making within A Program) ‘Any programming language must be able to perform different sets of actions depending on the Situation. C has three main decision making instructions the if statement, the if-else statement, and the switch statement. Control statements are the statements which change the flow of execution in such a way that the programmer can execute the statements as desired by him. The following are the decision making instructions and control statements available in C : + if-statement + iftelse statement © switch case © goto statement + do-while loop © while loop + forloop r EEF imperative Programming (BSeAT-MU) 3-2 Conditional Statements and oops | 2) imperative Programming (@SCAT-MU) 33 Conditional Statements 2nd Loops © break statement : i if(condition) + continue statement (7 Tue Note In the control statements, sometimes we are using the word , étatement and False{ statement 1; sometimes loop. There is some difference. A statement is executed only once where $ '@5 a loop executes repeatedly several times. For example, if....else is a statement else whereas while is a loop. i statement 2; ‘Syllabus Topic : if Statement } 3.2 _if Statement Flowchart 1 Explain if statment. > Program 3.3.1: Find out which is greater among two number. ‘The if statement can control the flow of execution of statements. Like other programming languages, C uses the keyword ‘if to implement the decision control instruction. The general form of if statement is as follow: Wincludesstdio.h= ifinclude | syntax hid main() \) iteansiaon) I B drser(); the value of num and num2 :); ‘Syllabus Topic : if-else Statement Bee Q } scanf(“tdhd Brum, 8num2); 33 _itelse ‘t(oum>num2) @. Explain else slatoment * Can we execute one set of statements if the condition evaluates to true and another group of statements if the condition evaluates to false? ‘Yes, It helps in taking two way decisions .This is what is the purpose of the if-else statement that is showing in the following example : Syntax and Flow chart If the condition is true then it will process statement 1. If the condition is false then it will process statement 2. printi"\n numd is greater than num2 FE imperative Programming (8.S2-1-MU) 34 Conditional Statements and Loops: With Flowchart [tram ram poe 7 Output lEnter the value of numt and num 2:502000 num is greater than num 2 Syllabus Topic : Nested if-else 3.4 _Nested if - else Statement @, Epiain nested iteise statements. It is possible to nest if — else statement within one another. An if — else statement can occur within another if - else. The inner if — else is said to be nested in the outer if else. Nesting can go upon any level. In given example, the second if-else construct is nested in the first else statement. If the condition in the first if statement is false, then the condition in the second if statement is checked. If it is false as well, then the last else statement is executed. (EP imperative Programming (SeATMU) 36 Conditional Statements and Loops Output z Inperatve Programming (8Se-1T-MU)_37 Conditional Statens and Loops, > Program 3.5.1 Ind is greater ‘Syllabus Topic : switch Statement 3.5 _ Switch - case Statement @. Write short note on switch-case statement + The switch statement results a particular group of statements to be chosen from several available groups. * The selection is based upon the current value of an expression which is included within the switch statement. Syntax |switch(variable) if case valuet : statement 1; break; ‘case value? : statement 2; break: case value3 : statement 3; break; case valuen : statement n; | break; dehult statment Ifthe variable value is equal to valuel then statement 1 will executed. If the variable value is equal to value2 then statement 2 will executed and so on. Broak statement in the switch block is useful bring the control out of the switch block | otherwise the control goes to the next case statement sequentially. | | print(*\nEnter your choice : | scanf( "ed" choice); switch(choice) | case 1: printf("\n one"); break; case 2: printf(*\n two” break; case 3: _printf("\n three”); break; case 4: printf("\n four"); break: ‘case 5: printf("\n five"); break: | case 6: _printf("\n six"); break; break: | default: printi("Entered wrong choice”); + / getch(); b Output [inter your choice : 4 four L EF imperative Programming ®ScATMY 38 Conconal Statements nd Lope 3.6 Loop Control Structure @. Write shoit note on loop control structure. * In above topics, the calculations were carried out in a fixed order or an suitable set of instructions were executed depending upon the result of the condition being tested. '* Suppose user wants to execute the certain block of code repeatedly until some conditions are satisfied, loops are used in performing repetitive work in programming. ‘+ Suppose you want to execute same code 1000 times. Then there are two possibilities © First Possibility, we have to write the code 1000 times. Means it will take lots of time to write the code which is tedious. © Second possibility, we have to write the code one’s and execute this, code 1000 times using loop. ‘Types of loops in C- language + while loop = do-while loop © for loop ‘Syllabus Topic : while Loop 3.6.1. while loop Mu) 39 Condional Stetoments and Loops, - whileti<6) \ ¢ printf(hd” i): in Q. Explain white loop. ‘+ This loop is useful to execute a group of statements repeatedly as long as a condition is true. Once the condition becomes false, the loop terminates. + The while tests the condition before executing any of the statements within ‘the while loop. + Firstly a compiler check the condition, if the condition is true then control g0es inside the while loop and executes the statement. If the condition of while loop is false then control goes out of the while loop. 36.2 for loop [@ Explain for loop. ‘The for loop allows us to specify three things about a loop in a single line : ‘+ Setting a loop counter to an initial(first) value + Testing the loop counter to decide whether its value has reached the number of repetitions desired. EF inperaive Programming (.Se-IT-MU) 3-10 Conditional Statoments and Loo mporatve Programming (8.Se-IT-MU) S11 Conditional Statements and Loops * Increment the value of loop counter variable each time when the program segment within the loop has been executed ‘A while loop can be written more concisely using for loop. For loop contains initialization, condition and increment/decrement part. or(initialization ; Condition ; Increment/Decrement) Ht u Statements; / for (initialization ; condition ; increment/decrement) { Gir C programming allows nesting of for loop, one within another. © First go for initialization then check condition. If condition is true then follow the path 3 execute statement and then follow path 4 for increment/decrement., ‘* After increment/decrement follow path 5 and check condition, if condition is true again then repeat path 3. Otherwise, if condition is false then control ‘will go out of the ‘for’ loop (by path 6). © Flowchart and example is given below for the same. ‘Syntax with Flow Trianon [iveeeeeresea eatin ils: eee a For example : Write a program for pattern given below : nee Le |finclude Wvoid main() if int ij; forn0;i<3;144) { printf(“\n"); for(jn0;)<3;}+4) { printf("\e @. Explain infinite loop. ‘When certain block of code executed infinitely (i.e. control never comes out of loop) then the loop is called as infinite loop. In this case loop never terminates. For example liso; lwhile(—0) Ht i Explanat In above example, value of i is zero. Firstly, we will check the condition though while loop, if the condition is true, then control goes inside the lwop and print Hello. Again condition will check and find true, then control goes inside the loop. The same process will repeat again and again, means it goes in infinite loop (condition is not getting false). printf(*Hello” Imperative Programming (B.Se-AT-MU) 3-43 Conditional Statements and Loops — ‘Syllabus Topic : do - while Loop ee ‘The do-while tests the condition after having executed the statements within the loop. ‘This means that do-while would execute its statements at least once, even if the condition fails for the first time. + This loop is useful to execute a group of statements repeatedly as long as a condition is true. Once the condition becomes false, the loop terminates. ‘Syntax and Flowchart False 10 printed"): Tre i Flowchart 11 Jwile(ici0); ae LB imperative Progamming (@Sa-tT-MU) 314 Conditional Statomonts and Loops 3.9 Break Statement Programming (B.Sc1T-MU) 15 Example ‘@.—Wiite shor note on break statement, See ‘The break statement in C programming language has the following two usages : \void main() * It is used in loops. When the break statement is encounter inside a loop, the it loop is immediately terminate and program control resumes at the next tpem statement following the loop. Forlx-Oix<5ixt+) © Téa be used to terminate a case in the switch statement. ce © A break statements takes you out of the do-while loop bypassing the pe) conditional test. | a break; Syntax } break; printf(*%ed *»); The following figure explains the working of break statement in all three b 4 a type of loops. While(Condition 1) _for(nitiaization; condition 3; ine/des) do Psout ( { Gi statements; statements; statements; ee if(Condition 2) ‘(Condition 2) ‘(Condition 2) Y { { { ‘oom shoals 5 3.10 Continue statement statements statements statements ) ) Jwhile(condition 1); [{@. Write short note on continue statements. a + This statement is useful to continue with the next repetition of a loop. When continue inside a loop is executed, the flow of execution goes back to the starting of the loop and the next repetition will take place. ‘+ Acontinue sends you straight to the test at the end of the loop. Syntax eee ‘The Fig. 3.10.1 explains the working of continue statement in all three type floops. [EE imperative Programming (8.S¢-1T-MU) Conditional Statements and Loo ‘ite(Conaiton 1) {eee condition 1; ine/dec) do { *jwtomentx statements; iene 2) Condon 2) (Condition 2) { “nn stn continue; } poe detorerta statomonts } ) ) -whit(condition 1); Fig. 310.1, Normal return floor Example Iwinclude lod main() if int x; lser(); forle-Orx<62x44) { ‘ifo—4) continue; printf("9ed *x); y getch(; Imperative Prog SoAT-MU) 317 Conditional Statements and Loops ‘Output 356 Explanation In above example, when value of x is 4, it enters in the “if condition”. After entering to the “if condition” control will return to the “for loop” because of “continue” statement. 4.11. goto Statement ‘Explain goto statement. + goto statement is useful for directly jump to a particular statement in the program. + While executing the statements, suppose we want to jump directly from statement number 1 to statement number 5, we can use goto. Syntax ‘Statement 1; way a griotabos; bel 2 z ‘Statement 2; a ‘Statement 3; label 3 ‘Statement 5 label 5 Salomon’; gue (ESSERE labels = Smioments; abel [TSatonentS7} r [EF inporive Programming Set) 918 Conditional Sitomen's ard Loops eee a ee printf("three"); ay printf("Four"); label: int n0; printf("Bye"); diser(); b printf("\Enter number : scanf("%d" no); Output (n0%2—0)?printf{ "sed fs even" no):printf("*ed is Odd",no); getch()s loneBye b 3.12 Examples on Loop Control Structure | Output > _ Program 3.12.4 : Program to check Even and Odd Number, ees | |eiseven include { | oid matn() Jp > Procram 9.12.3 : Write a program In cto reverse the digits of a given Ht int no; lfincludesstdio.h> arse); | ffinctudesconio.h> printf(*\Enter number : "); \void main() ! scanf("%d" 80); Ie ff{no%2—=0) {nt no,temp=0; printf(‘ed is even*,no); escr(): ae : printf("enter the number "); printf("d is Odd", no); scanf("Yed" 80); | getch(); “while(n0/10!=0) a { ext ‘temp=10"temp+no%10; Enter number = no=n0/10; 17 is odd ) > Program 3.12.2: Program to check odd or even using Conditional pepe or tempene: Operator. printi("\9ud", temp), finclude-stdio.h> geteh(); jtinclude le FEE cert rogemeng BeT4ny 200 contin Sauer sndioone | wwe Paraning(@Se-TMU) 92 lenter the number 2345. 5432, Alternative method l#include x . eee l#include |void main() 5 g r Ss int no,temp; drsex(); | printf(*\n enter nnumber\n"); scanf("%d" 80); while(no/10!=0) { i —_ printf("d’,temp); no=no/10; } printf("4ed",no); F getch(); > Program 3.12.4 ite a € program to read an Integer and dispity h of the digit of the integer in Engl |tinclude-stdio.h> lHinclude lvoid main() if | int no,digit,1-0; | diser(); printf("\nEnter number"); scanf(""bd" 800); while(no!~0) { r=10*r+no%10; no=no/10; 3 oe . > Program 3.12.5 ltinclude ltinclude void main() Ht {nt num{30}; //maximum array size are 10 {nt no,ij,temp; drser(); printf("How many number do you want to enter!“ scanf("%d",8n0); printf("\n enter number"); for(iO;ienori++) { scanf("%ed" &numfi]): } for(ia0;ienozis) Loo for(}-0;} Program 3.12.7 : Write a C program to store the N data samples in array and calculate mean, mode and median. {yincludecstdio.h> lwinclude lvoid main() t int ij.x.n,a[20],2-0,b[20); float sum0,f,mean,median, mode; arse); printf("\n Enter the no, of elements (Max 10)\n"); scanf("“ed",8n); printf("Enter the elements\n"); for(ieQsicnie+) scanf("%ed", Sali); = "\pMean Wf \nMedian : °F, mean, median): EE inperaive Progamming 8SeiTMY) 925 Conde! Seen 208 cope if(0) { For{ieO; in; i++) £ if (Di}=-2) Printf("\nMode : ted\t", afi]); | + + getch(); iP Output [Enter the no. of elements (Max 10) 4 | [Enter the elements > | i | a Is [Sum: 53.0000 IMean :13.250000 [Median : 8.000000 > Program 3.12.8: A customer is offered 15% discount on the Printed price of a laptop. The customer has to pay 7% sales tax on the remaining amount. Write a program in C to calculate the amount to be paid by the customer, jfinclude ifinclude jvoid main(), H float dis_price,price,tax,f_amt; diser(); printf("\nEnter the price of book:"); scanf("%6F price): dis_pricenprice-(0.15*price); Imperative Programming (6.Se-IT-MU)__ 9.27 Conditional Sttsments and Lc ("\nPrice after discount : %F,dis_price): 7 dis_price; \nSales tax paid by customer : bf",tax); Jis_pricestax: iti("\nFinal Amount to be paid by customer is : %F,f amt): he price of book :200 discount : 170.000000 ax paid by customer : 11.900000 +0 be paid by customer is : 181.899994 Program 3.12.9: Write a C program to accept the length of three sides of a triangle and to test and print the type of triangle as equilateral, isosceles or right angled or none. BEE imperative Programming iff ((s1—=s2)&8,(s2!=3)) || ((s2=s3)8&(s3!=s1)) || ((s3=s1)2&(s1!-s2)) ) |/*Condition for Isosceles triangle*/ < printf("\nfsosceles Triangle’ else { if ((53*s3)—((st*s1)+(52*32))) { ‘printf(*\nRight angled triangle"); : else { print(*\n None); lEnter three sides of a triangle : 20 10 20 [isosceles Triangle 4 E z Write a C program to find out if the number is a > Pythagoras triplet. Ex. : a7 = b’ +c” Program 3.12.10 : Write a C program to accept cost price and sales price of an item and calculate the profit percentage or loss percentage. | Include lint main() if int ep,sp, amt; printf(“Enter cost price: " EEF imperative Progamming ®Sc-TMU) 3.30 Condtional Statements and Loops ‘if(((a™2)—(b*b)+(c*c))]]((b*b)—-(c*c)+(a*a))||((c*c)=-(@*a)+(b*b))) { ative Programming (B.So1TMU) 331 Conditional Statoments and Loops: ma. : numerator = num2; ‘umerator = num; denominator = hum2: } alse { denominator = num: printf(*\nNumbers are Pythagorean Triplets."); } | yemainder = numerator % denominator; eet | while (Femainder != 0) E rH Print("\nNumbers are not Pythagorean Tripets."); Be fissictoe — denominator; , "denominator = remainder; etch); remainder = numerator % denominator; i} | 3 Output cd = denominator; em = (num’ * numa) / ged; Enter the Three Numbers: “printf("6CD of od and ed = %ed\n", numt, num2, ged); | 345 | printf("LOM of 9od and %ed = Sed\n*, num, nume, lem): | | getcn(; INumbers are Pythagorean Triplets. : > Program 3.12.12: Write a C program to implement Euclid’s rope algorithm to find the GCD and LCM of the given exo eiteoere. lEnter two numbers lwinclude 25 void main() [sed of 20 and 25 = 5 Ic Iii of 20 and 25 = 100 ‘nt num1, num2, ged, lcm, remainder, numerator, denominator; = een aliser(); Perfect number or not. Hint: If sum of the factors a ie (including 1 and excluding the number itself) is, ee ey same as that of original number then the number scanf("%ed %d", &rumi, &num2); is said to be perfect number. ‘if (ouma > numa) iE “f finclude FET mperative Programming (B.Sc-[-MU) _332 Conditional Statements and Loops, elrser); printf("Enter the Number: seanf("%ed", &n0); while (1 no) { if (no%i = 0) { sum = sum +4 } ie + 4f (sum == no) printf("%d is a Perfect Number", else printf("4bd is Non Perfect Number", i): geteh(): it Output ROU pe sere [Enter the Number: 6 6 is a Perfect Number > Program 3.12.14: Write a C program to check if the number is ‘neon’ number or not. Hint: If the sum of the digits of Square of the number is the number itself, then the number is said to be neon. For example- 9, Square is 81 and 8 +1 =9. FREER Na linclude |itinclude |void main() it ‘int j,no,sqt,sum=0; ser): pene reganming se 74y) 290 enc Satemens nope scanf( "od" 80); sateno*no; for(i-satsi-0;i~i/10) : sum=sum+i%10; + ‘f(sum=no) { printf("ed is a neon number ".no); } else { printf("bd is not a neon number",no); t getch(); Output lEnter the Number : 9 19 is a neon number > Program 3.12.15 : Write a C program to check if the entered 3 digit number is twisted prime or ni Hint : If the number obtained after reversing the number is also a prime then the number is twisted prime. Example 167, twisted 761, so 167 is twisted prime. Wfinclude [finclude \void main() It {nt 1j.n0,rev=0,count1=0,count2~0; lrser(); printf("\nEnter 3 digit number "); scanf("%ed",&n0); for(ie2;ic=no;ie+) FEF inpoaive Progarming @Se7M)_t Condon Storrs and Loe if(n0%bie0) count++; } ‘f(countt!=1) { printf("\nted is not a prime number*,no); exit(); rev=10"rev + n0%610; o=no/10; } printf("\nReverse number is : %d".rev); For(in2ricnrev;i++) { if{revbieo) t counters: } } ‘f(count2—1) { } else { printf("\ned és twisted prime number*,rev); printf("\yINot twisted prime number"); pe getch(); I} Output Enter 3 digit number 167 Reverse number is : 761 761 is twisted prime number Imperative Programming (B.Sc-MT-MU) 3:95 Condon Statements and Loos } Program 3.12.16 : Write a C program to store N numbers in an array and display only those numbers that are perfect squares. ee [pinctude |ginelude |pinclude Iyoid main() int i.no,saa[20]; | cliser()? | printf("Enter a number of element scanf("%d", &n0); printf(“Enter elements: "for(i = 0; 1 < no: i++) a scanf("%ed", Bafil): bet ~print("\nPerfect square numbers re: \n"); Herd -0: Fon: b+) { sq= sart(afi); | iffsarsa— afi) { printf(" %ed\n",a[i]); J + getch(); Output [Enter a number of elements: 6 lEnter elements: 456789 Perfect square numbers are: i i | ative Programming (8 TMU) _ 3:96 Q.1. Explain if statement. Q.2. Explain itelse statement. Q.3. Explain nested if-else statements. Q.4 Write short note on switch-case statement Q.5 Write short note on loop control structure 2.6 Explain while loop. 2.7. Explain for oop. Q.8 Explain nested for oop. 2.9. Explain infinite loop. Q. 10 Explain do-while loop. Q. 11 Write short note on break statement. Q. 12 Write short note on continue statements. Q. 18 Explain goto statement. Conditional Statements and Loops goa Functions in ‘C’ Functions : Overview, defining a function, accessing a function, passing arguments to ‘a function, specifying argument data types, function prototypes, recursion, modular ing and functions, standard library of c functions, prototype oa function : Fotlal parameter list, retum type, function call, block structure, passing arguments to ‘function: call by reference, call by value. llabus Topic : Overview, Defining a function, prototype of a function C functions can be viewed as basic building blocks of the program. Use of fon motivates software re-usability, simplification of code and simple way of ng code from developer's point of view. Lets us see this in more detail. |1 What is C Function ? Essence of modular programming lies in basic building blocks of the . These blocks are famously known as C function. C funetions comprises of instructions delimited inside by “{ ]" braces. Thus C program is nothing functions are useful in saving developers valuable time as well as systems valuable memory since it helps in avoiding rewriting same logic/code multiple times. rate Programming (B:S0-1T-MU) * These functions can be called multiple times as and when required. there is no limit in calling C funetions. * These functions can be called from any part of the program. Hence thery no restrictions on its usage and is truly anytime anywhere logic. * Big programs with complex logic can be broken down in to smaller, simp tal aanacus functions, This helps in building simpler eee Functions are the building blocks of programs. saves time while debugging. It is mandatory to declare a function before itis called for use. Technically this is termed as function prototype. If not, developers will need to write function definition itself before main function in a C program. In the Program 4.1.1, function “add” is called from main function. 4.1.3 Function Declaration (Prototype) and Function Definition ‘Explain function prototype and function definition. ‘Three important aspects that we need to know while working with are: + Function declaration or prototype : This is to notify compiler ab existence of function having information like function name, parameters and return value’s data type. + Fumetion call : This is activation point. On execution, it jumps to actu fanction definition location and begin function execution. | + Funetion definition : This is actual function that gets executed on ed having all required instructions clubbed in its body. Sr.no,| _C function Syniae af (*\nEnter two numbers for addition \n"); ("ed ed", Bx,By ) 5 ction call | 1 | function definition | return_type function_name ( arguments list ) {Body of function; } 2 _| function call fanetion_name ( arguments list ); 3__| function declaration | return_type function_name ( argument list ); Syllabus Topic : Block Structure 4.1.4 Block Structure @._ Wiite fundtion block structure: Function block structure is given below- \// function prototype |void main() //main function imperative Programming (8.S6-1T-MU) EF imperative Programming (BSe-IT-MU) 44 Function in Output ‘Actual Parameter : The actual value that is passed into the function by a caller. Formal Parameter : Parameter Written in Function Definition is Called Formal parameter lEnter two numbers for addition l23 Result of addition of two numbers is 5 Syllabus Topic : Modular Programming and Functions 7 4.2 Modular Programming and Functions {dition(int x, int y) // x and y are formal parameter (@._Wiite short note on Modular Programming ? Bigger and complicated programs are broken down into smaller functions gp modules or methods and these functions are called wherever required from main function. a While doing so there may arise a requirement of providing required data t» the called function to perform specified task, this data or data set is passed to the function definition through the function call. This data that is to be passed to function is called as parameters or arguments. ————— eee Syllabus Topic : Accessing a function and Passing arguments to a function 4.3 Accessing and Passing arguments to a function . Explain accessing and passing arguments to a function J + A function can be accessed by specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas. If the function call does not require any arguments, an empty pair of parentheses must follow the name of the function. * In passing arguments to a function, the value stored inside variable is passed to the function as parameter. * Here one should note that the value that is passes will be a Xerox of its original and due to this actual parameter will not get modified by formal parameter. ‘Syllabus Topic : Passing arguments to Function : Call by Value, Call By Reference 4341 Call by Value Piaaj6n ee When passing a parameter by value, only a copy of the parameter is passed into the procedure. This means that the original parameter cannot be modified inside the procedure. Advantage of passing by value is its simplicity and the fact | that the procedure does not have access to (and possibly modifying) the actual Program 4.3.1: Swapping of two numbers by using pass by value Heestaio.ti> ‘+ Both original and copied parameters occupy different Memory locations. wap(int x.int y) //x and y are formal parameter temp; i Hi BP imperative Programming (BScATMU) 46 Function in or temp=x ay yetemp: Iprinth(" x= %d : y= %d “xy; i Wvoid main() if ‘nt a~10,b20; swap(a,b); //a and b are actual parameter printf("\n a= %d: b= %d",a,b); » (&2,&b); //passing reference of a and b a= Ted = b= %ed"ayh)s output fa» SS ‘Syllabus Topic : Specifying argument data types, Return type and function call —_— ee OOO na 44 Function Categories based on Use of Arguments and Return Type = 20:y=10 Laan po [Bah ro rs tasden aaa ararounopeT Syllabus Topic : Call by Reference 43.2. Call by Reference Considering use of parameters and return value we can categorize function intofour types. Let us see example for each type. 441 A Function Without Parameters and Without Return Type Explain callby reference with example, When passing by reference, the actual location (address in memory) of the parameter is passed. So in case of pass by reference, the procedure can modify the actual or original data or parameter. > Program 4.3.2: Swapping of two numbers by using pass by reference [Brie @ program for function without parameter and witout relum ype: 4 ltincludeestdio.h> void swap(int *x,int *y) He int temp; ‘temp='x; ao yrtemp;

You might also like