Sei sulla pagina 1di 14

COMPUTER PROGRAMMING

Module 2 Control statements The statements are part of a program that performs some action. The compiler will check the program sequentially from the main(). It execute in the order they have written. The control structures can determine the flow of control in the program depending upon certain conditions is true or false. C provides the following three different types of control statements. 1. election control ! election control statements allow the computer to decide whether to execute the statements or not.

". Case control ! Case control statements tell the computer to execute the statement if that particular case happens. #. $oop Control ! $oop control statements execute a group of statements repeatedly until a particular condition is satisfied Selection Statements The selection statement refers that it will execute the group of statements when a particular condition is satisfied. The compiler selects the statements for execution according to the condition given. if statement ! The if statement is a powerful selection statement and is used to control the flow of execution of statements. %ne of the possi&le actions can &e executed &y this statement. The general form of 'if( statement is if(expression) ) statements* + The expression must &e placed in parenthesis. The statement will &e executed if the expression is true or returns a non , -ero num&er. If the expression is false. then the statement will not &e executed. The conditional operators /01 and /!1 are used in alternative for /if / statement. If , else statement ! The general form of if , else statement is if(expression) ) statements 1* + else ) statements "* + If /expression1 returns a true. then it will execute statements 1 otherwise if it returns false. then it will execute statements ". The statements can &e simple or compound statements.

Expression ?

Statements 1

Statements 2

2lowchart of if , else statement 2or example if(x314) ) x5x61* + else ) x5x71* + If the value of x is greater than 14. it will execute x5x61. I the value of x is less than 14. then it will execute x5x71. if , else , if tatement ! The general form is if (expression 1) ) tatements 1* + else if(expression ") ) tatements "* + else ) tatements #* + 8s soon as a true condition has occurred. the statement associated with it gets executed and rest of the ladder will not &e executed. If no true condition is found. the control will come to the final else statement. 9ested if tatements ! The general form is If(expression 1) ) if (expression ") ) tatements 1* + else

) tatements "* + + else ) tatements #* + If the first expression is true then the following if statement gets executed. If the expression " is true then statements 1 gets executed otherwise statements " will &e executed and comes out of the &lock. If the expression " is false. it comes to the final else statement and tatements # gets executed. Exercises 1. ". #. =. >. :rite a program to check whether the given num&er is prime or not. ;xamination result &ased on the marks in various su&<ects. :rite a program to find the largest num&er among three num&ers. :rite a program to calculate roots of a quadratic equation. :rite a program to find whether the given year is a leap year or not.

The switch Statement This is another form of the multi way decision. It is well structured. &ut can only &e used in certain cases where* %nly one varia&le is tested. all &ranches must depend on the value of that varia&le. The varia&le must &e an integral type. (int. long. short or char). ;ach possi&le value of the varia&le can control a single &ranch. 8 final. catch all. default &ranch may optionally &e used to trap all unspecified cases.

The general form of switch statement is switch(varia&le name) ) case constant 1 !

) &lock 1* &reak* +

case constant " !

) &lock 1* &reak* +

?????.. ?????.. default ! ) default &lock* &reak* + + switch statement tests the value of a varia&le name against a list of integer or character constants. :hen a match is found the statements corresponding to that constant are executed. The switch differs from the if , else. as switch can only test for equality whereas if , else can do any type of relational @ logical condition checking. 9ote that the &ody of the switch statement is a compound statement. The expression must evaluate to an integertype. %nce the expression is evaluated. the control <umps to the appropriate case la&el. The statements corresponding to that case is executed until the &reak statement is reached. The &reak statement is used as an exit from the switch statement.

otherwise the following case statements will get executed. If none of the case matches. the control goes to the default statement and that particular statement gets executed. 2or example estimate(num&er) int num&er* AB ;stimate a num&er as none. one. two. several. many BA ) switch(num&er) ) case 4 ! ) printf(C9oneDnC)* &reak* + case 1 ! ) printf(C%neDnC)* &reak* + case " ! ) printf(CTwoDnC)* &reak* + case # ! case = ! case > ! ) printf(C everalDnC)* &reak* + default ! ) printf(CEanyDnC)* &reak* + + + ;ach interesting case is listed with a corresponding action. The &reak statement prevents any further statements from &eing executed &y leaving the switch. ince case # and case = have no following &reak. they continue on allowing the same action for several values of num&er. Exercises 1. :rite a program to check whether the character entered is a vowel or not using switch. ". Implement a calculator using switch statement. #. :rite a program to find the day corresponding to any gicen date. oo! Statements C gives you a choice of three types of loop. while. do while and for. The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will &e traversed.

The do while loops is similar. &ut the test occurs after the loop &ody is executed. This ensures that the loop &ody is run at least once. The for loop is frequently used. usually where the loop will &e traversed a fixed num&er of times. It is very flexi&le.

while statement ! The /while statement1 is an entry controlled loop statement. :hen the expression is evaluated and the condition is not satisfied. it won1t allow executing the statements inside the loop. If condition is true. then statements get executed. It checks the condition repeatedly until the condition goes false. %nce false condition occurs the control is transferred to out side of the loop. The general form of while statements is while(expression) ) statements* + ;xample! while(xF>) ) x5x6>* + do , while statement ! The do , while loop is an exit controlled loop. The &ody of the loop gets executed at least once if the condition is not satisfied. The general form is do ) statements* + while(expression)* :hen the control reaches the do statement the program proceeds to evaluate the &ody of the loop first. 8t the end of the &ody of the loop first. 8t the end of the &ody of the loop the while statement is evaluated. If the condition is true. then the &ody of the loop will &e executed again. This will continue until the condition &ecomes false. This is very similar to the while loop except that the test occurs at the end of the loop &ody. This guarantees that the loop is executed at least once &efore continuing. uch a setup is frequently used where data is to &e read. The test then verifies the data. and loops &ack to read again if it was unaccepta&le. do ) printf(C;nter 1 for yes. 4 for no !C)* scanf(CGdC. @inputHvalue)* + while (inputHvalue I5 1 @@ inputHvalue I5 4)* for statement ! $ike the while statement. for loop is an entry controlled loop. The code of the for loop will &e executed itereatively. The for loop works well where the num&er of iterations of the loop is known &efore the loop is entered. The head of the loop consists of three parts separated &y semicolons. The first is run &efore the loop is entered. This is usually the initialisation of the loop varia&le. The second is a test. the loop is exited when this returns false.

The third is a statement to &e run every time the loop &ody is completed. This is usually an increment of the loop counter.

The general form of this statement is for(initiali-ation*condition*incrementAdecrement) ) statements* + Initiali-ation refers to the assignment of control varia&le. The control varia&le is any varia&le that is used in the for loop. The condition is a relational or logical expression for testing the value of control varia&le. If the condition is true. then the &ody of the loop will get executed. otherwise the control will come to the statement that immediately follows the loop.%nce the loop gets executed. the control is transferred &ack to the statement after evaluating the last statement in the loop. The control varia&le is then incremented or decremented. and the new value of the varia&le is tested to see whether the condition is satisfied. ;ach expression should &e seperated using semicolon. 2or example for(i54*iF514*i66) ) sum5sum6i* + The expression /for(**) is also valid. &ut this loop will execute infinite times. 9ested for loops are allowed in C programs. 2or example for(i54*iFn*i66) ) for(<54*<F5n*<66) ) sum5sum6i* + + This can also &e written as for(i54. <54*iFn. <F5n*i66. <66) ) sum5sum6i* + Exercises 1. ". #. =. >. J. K. L. M. 14. 11. 1". 1#. 1=. 1>. :rite a program to print a multiplication ta&le of an input num&er. :rite a program to find factorial of a num&er. :rite a program to print fi&anocci series. :rite a program to find the value of exponentiation. x n :rite a program to print all armstrong num&ers less than a given num&er :rite a program to check whether an input num&er is a palindrome num&er or not. :rite a program to find ex :rite a program to find sin(x). :rite a program to find cos(x). :rite a program to find log x. :rite a program to evaluate the &inomial coefficients of polynomials. :rite a program to print 2loyd1s triangle. :rite a program to print Nascal1s triangle. :rite a program to find the perfect num&ers upto a given num&er :rite a program to find the OCP of two num&ers.

The "rea# statement The break statement is used an interrupt to the normal flow of control. This statement causes as exit from the switch statement. It can &e used within a for. while. do , while or switch statement. The &reak statement causes the control to come out of the entire loop. 8 &reak within a loop should always &e protected within an if statement which provides the test to control the exit condition. char ch* ch5getchar()* switch(ch) ) case /a1 ! case /e1 ! case /i1 ! case /o1 ! case /u1 !) printf('Qowel()* &reak* + default !) printf('9ot a vowel()* &reak* + + If the input happens to &e /a1 or /e1. /i1. /o1. /u1 . the control goes to that particular case and prints 'Qowel(. Ry executing the &reak statement. cannot will come out of the loop. The continue statement This is similar to &reak &ut is encountered less frequently. It only works within loops where its effect is to force an immediate <ump to the loop control statement. In a while loop. <ump to the test statement. In a do while loop. <ump to the test statement. In a for loop. <ump to the test. and perform the iteration.

The continue statement causes the current iteration of a loop to stop and causes the next iteration of the loop to &egin immediately. $ike a &reak. continue should &e protected &y an if statement. It is wriiten simply as continue* The following code processes all characters except digits! for(<54*<FT%T8$*<66) ) c5getchar()* if(( c 3 /41 )@@(cF51M1)) continue* AB continue transfers control to &egin next iteration BA ??????????? ??????????? + continue transfer control to the &eginning of the next iteration. whereas break terminate the loop. The comma o!erator

The comma has two uses. The most common. is as a parameter separator for data types and function parameter lists. Sere is an example! main() ) char tring1T"4U. tring"TU5C%ut&ack Nu&C* AB data types BA strncpy( tring1. string". K)* + The other use is as a series operator which can &e seen in use with the for keyword. 8n example of the syntax is shown &elow. for(i54*iFn*i66) ) for(<54*<F5n*<66) ) sum5sum6i* + + The $oto statement The goto statement is used to alter the normal sequence of program execution &y transferring control to some other part of the program. It can &e written as goto la&el1* ????? ????? la&el1! ????? :here la&el is an identifier that is used to locate target statement to which control is transferred. The la&el must &e in the same function as the goto statement that uses it. Vou cannot <ump &etween functions. The la&le must &e followed &y a colon. la&el can occur &efore or after goto. 9o two statements can have the same la&el. 2or example ! To print the num&ers up to 144 using goto statement. x54* loop ! printf('Qalue of x 5 GdDn(.x)* x66* if (xF5144) goto loop* %unctions 8 program is made up of one or more functions. with one of these &eing main(). 2unction is a self , contained &lock of program that performs a particular task. Weasons for using functions ! 1. 8voids rewriting the same code over and over. ". It is easier to write programs and keep track of what they are doing. Codes can &e checked independently and makes it error free for the correct execution of programs. %unction &e'inition The C code that descri&es what a function does is called the function definition. 8 function definition has the following form

Type ) +

function name( parameter list) Peclarations tatements*

;verything &efore the first &race comprises the header of the function definition and everything &etween the &races comprises the &ody of the function definition. The type of the function depends on the type of value that the function returns if any. The type (oid can &e used if a function does not return a value. 2unction name must not &e li&rary routine or operating system commands. Narameter list contains valid varia&le names separated &y commas. Narameters are identifiers used within the &ody of the function. The parameters in function definition are called formal parameters to emphasi-e their role as place holders for actual values that are passed to the function. when it is called. 8n example of a function definition main() ) message()* + AB header BA message() ) AB&odystarts hereBA printf (C;xample for function definitionDnC)* return* + The program will print the following output. Exam!le 'or 'unction de'inition message() is the function here. In all c programs. program execution &egins in main(). :hen program control encounters message(). the function is invoked and program control is passed to it. 8fter printing the message(). the program control passes &ack to the calling environment. which in a&ove example is main(). :hen main() runs out of function calls. the. program ends. The return statement The return statement is used for two purposes. %nce the return statement is executed the program control will &e immediately passed &ack to the calling environment. If the return statement contains an expression then the value of the expression is passed &ack to the calling environment as well. This value will &e converted. if necessary to the type of the function as specified in the function definition. If no type is explicitly declared. the type is implicitly 'int(. 8 return statement has one of the following forms! return* return expression* ome examples are return(#)* return(aB&)* The expression &eing returned can &e enclosed in parentheses. &ut itXs not necessary.

%unction Protot)!e 2unctions should &e declared &efore they are used. 89 I C provides for the new function declaration syntax called the function prototype. 8 function prototype tells the compiler the num&er and type of arguments that are to &e passed to the function and the type of the value that is to &e returned &y the function. 8n example is dou&le sqrt(dou&le)* This tells the compiler that sqrt() is a function that takes a single argument of type dou&le and returns a dou&le. The general form of function prototype.

type function_name(parameter type list);


Parameter Passin$ Mechanism Narameters are syntactically identifiers. and they are used within the &ody of the function. ometimes the parameters in a function definition are called formal parameters to emphasi-e their role as placeholders for actual values that are passed to the function when it is called. Ypon function invocation. the value of the argument correspond to a formal parameter is used within the &ody of executing function. Refore &eginning with the statements in the functions. it is necessary to declare the type of the arguments through type declaration statements. *+ Call ") (alue 2unctions are invoked &y writing their name and an appropriate list of arguments within parenthesis. Typically. these arguments are in the. parameter list of the function definition. 8ll arguments are passed Ccall7&y7valueC. :henever we called a function and passed something to it we have always passed the values of varia&les to the called function. This type of function calls are called Ccall7&y7valueC. The examples of call7&y7value are shown &elow! sum5cal sum( a. & )* f5fact(a)* If a varia&le is passed to a function. the stored value of that varia&le in that varia&le in the calling environment will not &e changed. Sere is .an example! ZincludeFstdio.h3 . int computeHsum(int m)* int main( void) ) int n5#. sum* printf(CGdDnC.n)* AB# is printed BA sum5computeHsum(n)* printf(CGdDnC.n)* AB# is printed BA printf(CGdDnC.sum)* ABJ is printed BA return 4* + int computeHsum(int n) ABsum the integers from 1 to nBA M ) int sum54* for (*n3%*77n) ABstored value of n is changedBA sum65n* return sum* + ;ven though n is passed to computeHsum() and the value of n in the &ody of that function is changed. the value of n in the calling environment remains unchanged. It is the value of n that is &eing passed. not n itself.

2+ Call ") re'erence In Ccall7&y7 referenceC. instead of passing the value of a varia&le. the location num&er (or the address) of the varia&le is passed to a function. This will &ecome Ccall7&y7referenceC. It is a way to pass address (reference) of varia&les to a function that then allows the &ody of the function to make changes to the value of the varia&les in the calling environment. Sere is .an example! ZincludeFstdio.h3 . int computeHsum(int Bn)* int main( void) ) int n5#. sum* printf(CGdDnC.n)* AB# is printed BA sum5computeHsum(@n)* printf(CGdDnC.n)* AB# is printed BA printf(CGdDnC.sum)* ABJ is printed BA return 4* + int computeHsum(int Bn) ABsum the integers from 1 to nBA M ) int sum54* for (*Bn3%*77Bn) ABstored value of n is changedBA sum65Bn* return sum* + Cate$or) o' 'unctions 8 function. depending on whether parameters or arguments are present or not and whether a value returned or not. may &elong to one of the following categories. 1. 2unctions with no arguments and no return values. ". 2unctions with arguments and no return values. #. 2unctions with arguments and return values. 2unctions with no arguments and no return values :hen a function has no arguments. it does not receive any data from the calling function. imilarly. it does not return any value* the calling function does not receive any data from the called function.

function() { function2(); }

No input

No output

void function2() { }

There is only transfer of control &ut not data. This function can only &e used as an independent statement. 2unctions with arguments and no return values

The calling function will read data from the terminal and pass it on to called function. This will work good as the calling function can check the validity of data. if necessary. &efore it is handed over to the called a function. The nature of data communication &etween the calling function and called function with arguments with no return values is shown &elow.

function() { int a,b; function2(a,b); }


;xample area(l.&.h)*

"a!ues as ar#uments

No return va!ues

void function2(int c, int d) { }

The arguments 1. &. h are called the formal parameters. The calling function can send values to these arguments using function calls. The function call area (#.=.>) would send the values #.=.> to the function area (l.&.h) and assign # to l. = to &. > to h. The values #.=.> are the actual parameters which &ecome the values of the formal arguments inside the called function. The actual and the formal arguments should match in num&er. and order. :hen a function call is made. only a copy of the values of actual arguments is passed into the called function. 2unctions with arguments and return values The previous category functions receive values from the calling function through arguments &ut do not send &ack any value. Wather it displays the result of calculations at the terminal. To ensure a higher degree of porta&ility &etween programs. a function should generally &e coded without involving any IA% operations. If the function returns a value. it can &e used in different ways in different programs. The nature of the two way data communication &etween the calling and the called function

function() { int a,b; function2(a,b); }

"a!ues as ar#uments

$eturn va!ues

t pe function2(int c, int d) { int resu!t; return resu!t; }

The following events occur* when a function call is executed (i) The function call transfers the control along with the copies of the values of actual parameters. (ii) The called function is executed line &y line until the return statement is encountered. 8t this point. the value is passed &ack to main() or calling function.

Recursion In C. it is possi&le for the function to call themselves. 8 function is called XrecursiveX if a statement within the &ody of a function calls the same function. ometimes called Xcircular definitionX. recursion is thus the process of defining something in terms of itself. 2or a clear understanding of recursive function we shall see an example for calculating value of an integer. main() ) int a.factorial* printf(CDn enter any num&erC)* scanf(CGdC.@a)*. factorial 5fact(a)* printf (Cfactorial value 5Gfctorial)* + fact (int x) ) int f 51.i* for(i5x*i35*i66 ) f5fBi* return f* + 8nd here is the output ;nter any num&er (# is given as input) 2actorial value 5J 9ow we will see the program using recursion main() ) int a.fact* printf(enter any num&erC)* scanf(CGd(.@a)* fact 5factHrec(a)* printf(CDnfactorial value 5GdC.fact)* + factHrec(int x) ) int f.i* if (x551) return 1* else f5xBfactHrec(x71)* return (f)* + :hen a recursive program is executed. the recursive function calls are not executed immediately. Wather. they are placed on a stack until the condition that terminates the recursion is encountered. The function calls are then executed in reverse order. as they are 'popped( off the stack. Thus. when evaluating a factorial recursively. the function calls will proceed in the following order. nI 5 nI B (n71)I (n71)I 5 (n71)B(n7")I (n7")I 5 (n7")B(n7#)I ?????????. "I 5 "B1I 1I 51

The actual values will then &e returned in the following reverse order 1I 5 1 "I 5 "B1I 5 "B1 5 " #I 5 #B"I 5 #B" 5 J ????????. ????????. nI 5 n B (n71)I This reversal in the order of execution is a characteristic of all functions that are executed recursively. The recursive function factHrec() is analy-ed as illustrated in the following ta&le.

%unction call factHrec(1) factHrec(") factHrec(#) factHrec(=)

,alue returned 1 "BfactHrec(1) or "B1 "BfactHrec(") or #B"B 1 "BfactHrec(#) or =B#B"B1

In the first run. when the value of x 5 1. it checks the if condition. if (x51) is satisfied and is returned through return statement. f 5xBfactHrec(x7l). o this &ecomes f 5"BfactHrec(1). :e know that factHrec( 1) is 1. so the expression reduces to (" B 1) or ". Wecursive functions can &e efficiently used to solve pro&lems where the solution is expressed in terms of successively applying the same solution to su&sets of the pro&lem. :hen we use recursive functions. we must haye an if statement. somewhere to force the function to return without recursive call &eing executed. %therwise. the function will never return.

Potrebbero piacerti anche