Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Basic of Programming language., Study notes of Programming Languages

This is Class notes.I have written everything or every class topic in this notes.it will very helpfull for you.

Typology: Study notes

2023/2024

Available from 12/12/2024

mohd-ashraf-3
mohd-ashraf-3 🇮🇳

7 documents

1 / 27

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
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.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b

Partial preview of the text

Download Basic of Programming language. and more Study notes Programming Languages in PDF only on Docsity!

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:

  1. Initialization of counter
  2. Test condition (check the value of counter)
  3. Body of loop
  4. Increment / Decrement (update counter)

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;

  • When a for loop is used, the loop variable is initialized only once.
  • With every iteration of the loop, the value of the loop variable is updated and the condition is checked. If the condition is true, the statement block of the loop is executed else, the statements comprising the statement block of the for loop are skipped and the control jumps to the immediate statement following the for loop body.
  • Updating the loop variable may include incrementing the loop variable, decrementing the loop variable or setting it to some other value like, i +=2, where i is the loop variable.

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

  • If a big program has to be developed without the use of any function (except main()), then there will be countless lines in the main().
  • All the libraries in C contain a set of functions that the programmers are free to use in their programs. These functions have been prewritten and pre-tested, so the programmers use them without worrying about their code details. This speeds up program development.

3.16 Terminology of functions

  • A function, f that uses another function g, is known as the calling function and g is known as the called function.
  • The inputs that the function takes are known as arguments
  • When a called function returns some result back to the calling function, it is said to return that result.
  • The calling function may or may not pass parameters to the called function. If the called function accepts arguments, the calling function will pass parameters, else not.
  • Main () is the function that is called by the operating system and therefore, it is supposed to return the result of its processing to the operating system.

3.17 Function declaration

  • Function declaration is a declaration statement that identifies a function with its name, a list of arguments that it accepts and the type of data it returns.
  • The general format for declaring a function that accepts some arguments and returns some value as result can be given as: return_data_type function_name(data_type variable1, data_type variable2,..);
  • No function can be declared within the body of another function. Example, float avg ( int a, int b);

3.18 Function definition

  • Function definition consists of a function header that identifies the function, followed by the body of the function containing the executable code for that function
  • When a function defined, space is allocated for that function in the memory.
  • The syntax of a function definition can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..) { …………. statements …………. return( variable); }

  • The no. and the order of arguments in the function header must be same as that given in function declaration statement.

3.19 Function Call

  • The function call statement invokes the function.
  • When a function is invoked the compiler jumps to the called function to execute the statements that are a part of that function.
  • Once the called function is executed, the program control passes back to the calling function.
  • Function call statement has the following syntax.

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

  • The return statement is used to terminate the execution of a function and return control to the calling function. When the return statement is encountered, the program execution resumes in the calling function at the point immediately following the function call.
  • By default, the return type of a function is int.
  • For functions that has no return statement, the control automatically returns to the calling function after the last statement of the called function is executed.

3.21 Passing parameters to the function

  • There are two ways in which arguments or parameters can be passed to the called function.
  • Call by value in which values of the variables are passed by the calling function to the called function.
  • Call by reference in which address of the variables are passed by the calling function to the called 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)); }