



















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
This is Class notes.I have written everything or every class topic in this notes.it will very helpfull for you.
Typology: Study notes
1 / 27
This page cannot be seen from the preview
Don't miss anything!
Unit 3
Conditional Program Execution / Decision Making
3 Introduction We have seen that a C program is a set of statements which are normally executed sequentially in the order in which they appear. However, in practice, we have a number of situations where we may have to change the order of execution of the statements based on certain conditions or repeat a group of statements until certain specified conditions are met. This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly. C language possesses such decision-making capabilities by supporting the following statements: 1.1 IF statement 1.2 IF-ELSE statement 1.3 Nesting of IF-ELSE statements 1.4 ELSE-IF ladder 1.5 SWITCH statement 1.6 GOTO statement 1.7 Conditional operator/ Ternary operator (? :) These statements are popularly known as decision-making statements.
3.1 IF Statement: Theif statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two way decision statement and is used in conjunction with an expression. It takes the following form: if (test expression) { statement block 1; } statement x;
The statement block 1 may be a single statement or a group of statements. If the test expression is true, the statement block 1 will be executed; otherwise the statement block 1 will be skipped and the control will jump to the statement-x. When the condition is true both the statement block 1 and the statement x are executed in sequence.
Flowchart
Program void main() { int age; printf(“\nEnter Age”); scanf(“%d”,&age); if(age>=18) printf(“\nYou are eligible to vote”); } Output Enter Age 20 You are eligible to vote Enter Age 10 No output
The second run of the program does not produced any message because the expression (age>=18) results to false.
3.2 IF-ELSE Statement: In the if-else construct, first the test expression is evaluated. If the expression is true, statement block 1 is executed and statement block 2 is skipped. Otherwise, if the expression is false, statement block 2 is executed and statement block 1 is ignored. In any case after the statement block 1 or 2 gets executed and finally the control will pass to statement x. Therefore, statement x is executed in every case. It takes the following form: if (test expression) { statement block1; } else { statement block 2; } statement x;
else { statement block 2; } } else { statement block x; } statement y;
If the condition 1 is false, the statement block x will be executed; otherwise it continues to perform second test. If the condition 2 is true the statement block 1 will be evaluated otherwise statement block 2 will be executed and then the control is transferred to statement y.
Flowchart
Program void main() { int A,B,C; printf(“\nEnter the numbers”); scanf(“%d%d%d”, &A,&B,&C); if(A>B) { if(A>C) printf(“A”); else printf(“C”); } else { if(B>C)
printf(“B”); else printf(“C”); }
3.4 ELSE-IF Ladder: There is another way of putting ifs together when multipath decisions are involved. A multipath decisions is a chain of ifs in which the statements associated with each else is an if. It takes the following general form:
This construct is known as the else if ladder. The conditions are evaluated from the top (of the ladder) downwards. As soon as true condition is found the statement associated with it is executed and the control is transferred to the statement-x (skipping the rest of the ladders). When all the conditions are false then the final else containing default statement will be executed.
Flowchart
Flowchart
Program void main() { char grade; printf(“Enter the grade of student”); scanf(“%c”,&grade); switch(grade) { case 'A': printf("\n Excellent"); break; case 'B': printf("\n Good"); break; case 'C': printf("\n Fair"); break; default: printf("\n Invalid Grade"); } }
3.6 GOTO Statement: So far we discussed ways of controlling the flow of execution based on certain specified conditions. C supports the goto statement to branch unconditionally from one point to another in the program. Although it may not be essential to use the goto statement in a highly structured language like C, there may be occasions when the use of goto might be desirable. The goto requires a label in order to identify the place where the branch is to be made. A label is any valid variable name and must be followed by colon. The label is placed immediately before the statement where the control is to be transferred. The general forms of goto and label statements are shown below:
goto label; label: ………… statement; ………… ………… lablel: ………… statement; goto label; a) Forward jump b) Backward jump
The label can be anywhere in the program either before or after the goto label; statement.
During running a program when a statement like goto begin; is met, the flow of control will jump to the statement immediately following the label begin:. This happens unconditionally. If the label is placed after the goto statement then it is called a forward jump and in case it is located before the goto statement, it is said to be a backward jump.
Such infinite loops should be avoided in programming.
a) Entry controlled loop: condition is tested before the start of the loop. b) Exit controlled loop: test is performed at the end of the loop.
The entry controlled loop is also known as pre-test loop and exit controlled loop is known as post-test loop. Iterative statements are used to repeat the execution of a list of statements, depending on the value of an integer expression. In this section, we will discuss all these statements.
3.9 While loop 3.10 Do-while loop 3.11 For loop
A looping process in general would include the following 4 steps:
3.9 While Loop It is entry controlled loop. The while loop is used to repeat one or more statements while a particular condition is true. In the while loop, the condition is tested before any of the statements in the statement block is executed. If the condition is true, only then the statements will be executed otherwise the control will jump to the immediate statement outside the while loop block.We must constantly update the condition of the while loop.
statement x; while (condition) { statement_block; } statement y;
Program to print numbers from 0 to 10 using while loop #include<stdio.h> int main() { int i = 0; while(i<=10) { printf(“\n %d”, i); i = i + 1; // condition updated } return 0; }
3.10 Do While Loop The do-while loop is similar to the while loop. The only difference is that in a do-while loop, the test condition is tested at the end of the loop. So it is known as exit controlled loop. The body of the loop gets executed at least one time (even if the condition is false). The major disadvantage of using a do while loop is that it always executes at least once, so even if the user enters some invalid data, the loop will execute. Do-while loops are widely used to print a list of options for a menu driven program. statement x; do { statement_block; } while (condition); statement y;
Look at the code given below which print first n numbers using a for loop.
Program #include<stdio.h> int main() { int i, n; printf(“\n Enter the value of n :”); scanf(“%d”, &n); for(i=0; i<= n; i++) { printf(“\n %d”, i); } return 0; }
3.12 Break statement The break statement is used to terminate the execution of the nearest enclosing loop in which it appears. When compiler encounters a break statement, the control passes to the statement that follows the loop in which the break statement appears. Its syntax is quite simple, just type keyword break followed with a semi-colon.
break; In switch statement if the break statement is missing then every case from the matched case label to the end of the switch, including the default, is executed.
Program int i; for(i=1; i<= 5; i++) { if (i==3) break; printf(“\t %d”, i); } Output 1 2
3.13 Continue Statement The continue statement can only appear in the body of a loop. When the compiler encounters a continue statement then the rest of the statements in the loop are skipped and the control is unconditionally transferred to the loop-continuation portion of the nearest enclosing loop. Its syntax is quite simple, just type keyword continue followed with a semi-colon. continue;
If placed within a for loop, the continue statement causes a branch to the code that updates the loop variable.
Program int i; for(i=1; i<= 5; i++) { if (i==3) continue; printf(“\t %d”, i); } Output
3.16 Terminology of functions
3.17 Function declaration
3.18 Function definition
return_data_type function_name(data_type variable1, data_type variable2,..) { …………. statements …………. return( variable); }
3.19 Function Call
function_name(variable1, variable2, …);
Program #include<stdio.h> int sum(int a, int b); // FUNCTION DECLARATION int main() { int num1, num2, total = 0; printf(“\n Enter the first number : “); scanf(“%d”, &num1); printf(“\n Enter the second number : “); scanf(“%d”, &num2); total = sum(num1, num2); // FUNCTION CALL printf(“\n Total = %d”, total); return 0; } // FUNCTION DEFNITION int sum ( int a, int b) // FUNCTION HEADER { // FUNCTION BODY return (a + b); }
3.20 Return statement
3.21 Passing parameters to the function
printf("\n The value of num before calling the function = %d", num); add(&num); printf("\n The value of num after calling the function = %d", num); return 0; } void add( int *n) { *n = *n + 10; printf("\n The value of num in the called function = %d", n); } The output of this program is: The value of num before calling the function = 2 The value of num in the called function = 20 The value of num after calling the function = 20
3.22 Recursive functions A recursive function is a function that calls itself to solve a smaller version of its task until a final call is made which does not require a call to itself. Every recursive solution has two major cases, they are base case , in which the problem is simple enough to be solved directly without making any further calls to the same function recursive case , in which first the problem at hand is divided into simpler sub parts. Second the function calls itself but with sub parts of the problem obtained in the first step. Third, the result is obtained by combining the solutions of simpler sub-parts.
Finding Factorial of a Number using Recursion
Base case is when n=1, because if n = 1, the result is known to be 1
Recursive case of the factorial function will call itself but with a smaller value of n, this case can be given as
factorial(n) = n X factorial (n-1)
#include<stdio.h> int Fact(int) { if(n==1) retrun 1; return (n * Fact(n-1)); } main() { int num;
scanf(“%d”, &num); printf(“\n Factorial of %d = %d”, num, Fact(num)); return 0; }
The Fibonacci series can be given as: 0 1 1 2 3 5 8 13 21 34 55…… That is, the third term of the series is the sum of the first and second terms. On similar grounds, fourth term is the sum of second and third terms, so on and so forth. Now we will design a recursive solution to find the nth term of the Fibonacci series. The general formula to do so can be given as
main() { int n; printf(“\n Enter the number of terms in the series : “); scanf(“%d”, &n); for(i=0;i<n;i++) printf(“\n Fibonacci (%d) = %d“, i, Fibonacci(i)); } int Fibonacci(int num) { if(num == 0 || num==1) return num; return ( Fibonacci (num - 1) + Fibonacci(num – 2)); }
3.23 Types of recursion Any recursive function can be characterized based on: whether the function calls itself directly or indirectly (direct or indirect recursion). whether any operation is pending at each recursive call (tail-recursive or not). the structure of the calling pattern (linear or tree-recursive).
3.23.1 Direct Recursion A function is said to be directly recursive if it explicitly calls itself. For example, consider the function given below.
int Func( int n) { if(n==0) retrun n; return (Func(n-1)); }