Presentation is loading. Please wait.

Presentation is loading. Please wait.

UNIT-3. Repetitive control structures – Pre-test and post-test loops, initialization and updation, event and counter controlled loops, while, do..while,

Similar presentations


Presentation on theme: "UNIT-3. Repetitive control structures – Pre-test and post-test loops, initialization and updation, event and counter controlled loops, while, do..while,"— Presentation transcript:

1 UNIT-3

2 Repetitive control structures – Pre-test and post-test loops, initialization and updation, event and counter controlled loops, while, do..while, for, break and continue statements, comma expression Functions – User-defined functions, Function definition, arguments, return value, prototype, arguments and parameters, inner-function communication. Standard functions – Math functions, Random numbers. Scope – local global. Parameter passing – Call by value and call by reference. Recursive functions – Definition, examples, advantages and disadvantages. Macros – Definition, examples, comparison with functions. Topics to be covered in UNIT-3

3 Concept of a loop  The real power of computers is in their ability to repeat an operation or a series of operations many times.  This repetition, called looping, is one of the basic structured programming concepts.  Each loop must have an expression that determines if the loop is done.  If it is not done, the loop repeats one more time; if it is done, the loop terminates.

4 Concept of a Loop

5 Pretest and Post-test Loops  We need to test for the end of a loop, but where should we check it—before or after each iteration? We can have either a pre- or a post-test terminating condition.  In a pretest loop, the condition is checked at the beginning of each iteration.  In a post-test loop, the condition is checked at the end of each iteration.

6 Pretest Loop In each iteration, the control expression is tested first. If it is true, the loop continues; otherwise, the loop is terminated. Post-test Loop In each iteration, the loop action(s) are executed. Then the control expression is tested. If it is true, a new iteration is started; otherwise, the loop terminates. Note

7 Pretest and Post-test Loops

8 Minimum Number of Iterations in Two Loops

9 Initialization and Updating  In addition to the loop control expression, two other processes, initialization and updating, are associated with almost all loops.  Loop Initialization  Loop Update  Control expression is used to decide whether the loop should be executed or terminated.  Initialization is place where you can assign some value to a variable.  Variable’s value can be updated by incrementing a value by some amount.

10 Loop Initialization and Updating

11 Event- and Counter-Controlled Loops  All the possible expressions that can be used in a loop limit test can be summarized into two general categories: 1. Event-controlled loops and 2. Counter-controlled loops.  In event-controlled loops, loop execution depends on the given condition.  In counter-controlled loops, loop execution depends on the counter variable value.

12 Event-controlled Loop Concept

13 Counter-controlled Loop Concept

14 Loop Comparisons

15 Loops in C  C has three loop statements: the while, the for, and the do…while. The first two are pretest loops, and the third is a post-test loop.  We can use all of them for event-controlled and counter-controlled loops. A looping process, in general, would include the following four steps:  Before a loop start, the loop control variable must be initialized; this should be done before the first execution of loop body.  Test for the specified condition for execution of the loop, known as loop control expression.  Executing the body of the loop, known as actions.  Updating the loop control variable for performing next condition checking.

16 C Loop Constructs

17 while  The "while" loop is a generalized looping structure that employs a variable or expression for testing the condition.  It is a repetition statement that allows an action to be repeated while some conditions remain true.  The body of while statement can be a single statement or compound statements.  It doesn’t perform even a single operation if condition fails.

18 The while Statement

19 Compound while Statement

20 Example 1: To print 1 to 10 natural numbers #include main() { int i; i=1; while (i<=10) { printf(“%d\n”,i); i++; }

21 Example 2: To print the reverse of the given number. void main() { int n, rem, rev = 0; printf("\n Enter a positive number: "); scanf("%d",&n); while(n != 0) { rem = n%10; rev = rev*10+rem; n = n/10; } printf("The reverese of %d is %d",n,rev); }

22 do while  The “do while" loop is a repetition statement that allows an action to be done at least once and then condition is tested.  On reaching do statement, the program proceeds to evaluate the body of the loop first.  At the end of the loop, condition statement is evaluated.  If the condition is true, it evaluates the body of the loop once again.  This process continues up to the condition becomes false.

23 do…while Statement

24 Example 3: To print fibonacci sequence for the given number. #include main() { int a=0,b=1,c,i; i=1; printf("%d%d",a,b); do { c=a+b; i++; printf("%3d",c); a=b; b=c; }while(i<=10); }

25 Example 4: To print multiplication table for 5. #include void main() { inti = 1, n=5; do { printf(“ %d * %d = %d “, n, i, n*i); i = i + 1; } while ( i<= 5); }

26 //Program to print 5 4 3 2 1 using while and do…while

27

28 Pre- and Post-test Loops

29  A for loop is used when a loop is to be executed a known number of times.  We can do the same thing with a while loop, but the for loop is easier to read and more natural for counting loops. General form of the for is: for( initialization; test-condition; updation) { Body of the loop } for

30 for Statement

31 Compound for Statement

32 Comparing for and while Loops

33

34 A Simple Nested for Loop

35 We can write the for loop in the following ways: Option 1: for (k= 1; k< = 10 ;) { printf(“%d”, k); k = k + 1; } Here the increment is done within the body of the for loop and not in the for statement. Note that the semicolon after the condition is necessary. Option 2: int k = 1; for (; k< = 10; k++); { printf(“, k); } Here the initialization is done in the declaration statement itself, but still the semicolon before the condition is necessary.

36 Option 3: The infinite loop One of the most interesting uses of the for loop is the creation of the infinite loop. Since none of the three expressions that form the for loop are required, it is possible to make an endless loop by leaving the conditional expression empty. For example: for (; ;) printf(“The loop will run forever\n”); Actually the for (; ;) construct does not necessarily create an infinite loop because C’s break statement, when encountered anywhere inside the body of a loop, causes immediate termination of the loop. Program control then picks up the code following the loop, as shown here: for (; ;) { ch = getchar( );/* get a character */ if (ch = = ‘A’) break ; } printf (“you typed an A”); This loop will run until A is typed at the keyboard.

37 Option 3: For loop with no body A statement, as defined by the C syntax, may be empty. This means that the body of the for may also be empty. This fact can be used to improve the efficiency of certain algorithms as well as to create time delay loops. The following statement shows how to create a time delay loop using a for loop: for (t = 0; t < SOME _VALUE; t++);

38 Nested Comma Expression  The operator comma, is used to separate the more than one expressions.  A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the type and value of the right operand.  Thus, in a for statement, it is possible to place multiple expressions in the various parts.

39 Comparison of while and do…while

40

41 break  When a break statement is enclosed inside a block or loop, the loop is immediately exited and program continues with the next statement immediately following the loop.  When loop are nested break only exit from the inner loop containing it. The format of the break statement is:

42 Example 6: Program to demonstrate break statement. #include main() { int i; i=1; while(i<=10) { if(i==8) break; printf(“%d\t”,i); i=i+1; } printf(“\n Thanking You”); }

43 continue  When a continue statement is enclosed inside a block or loop, the loop is to be continued with the next iteration.  The continue statement tells the compiler, skip the following statements and continue with the next iteration.  The format of the continue statement is:

44 Example 5: Program to demonstrate continue statement. #include main() { int i; for(i=1;i<=5;i++) { if(i = = 3) continue; printf(" %d",i); }

45 45 FUNCTIONS IN C  A function is a self-contained block of code that carries out some specific and well-defined task.  In general, the purpose of a function is to receive zero or more pieces of data, operate on them, and return at most one piece of data.  C functions are classified into two categories 1. Library Functions 2. User Defined Functions

46 46 FUNCTIONS IN C (contd…) Library Functions:  These are the built in functions available in standard library of C.  The standard C library is collection of various types of functions which perform some standard and predefined tasks. Example:  abs (a) function gives the absolute value of a, available in  pow (x, y) function computes x power y. available in  printf () and scanf () performs I/O functions and etc..,

47 47 FUNCTIONS IN C (contd…) User Defined Functions:  These functions are written by the programmer to perform some specific tasks.  Example: main (), sum (), fact (), show(), display() and etc.,  The main distinction between these two categories is that library functions are not required to be written by us whereas a user defined function has to be developed by the user at the time of writing a program. Note:  In C, a program is made of one or more functions, one and only one of which must be called main.  The execution of the program always starts with main, but it can call other functions to do some part of the job.

48 48 Advantages of User-defined Functions Modular Programming: It facilitates top down modular programming. Reduction of Source Code: The length of the source program can be reduced by using functions at appropriate places. Easier Debugging: It is easy to locate and isolate a faulty function for further investigation. Code Reusability: A program can be used to avoid rewriting the same sequence of code at two or more locations in a program. Function Sharing: Programming teams does a large percentage of programming. If the program is divided into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the complex program.

49 49 User-defined Functions  Like every other object in C, functions must be both declared and defined.  The function declaration or prototype gives the whole picture of the function that needs to be defined later.  The function definition contains the code for a function.  A function name is used three times in a C program: for declaration, in a call, and for definition.

50 50 The general form of a C user-defined function: return_type function_name (argument declaration) { //local declarations …… //statements …… return (expression); }

51 51 The general form of a C user-defined function (contd…) return-type:  Specifies the type of value that a function returns using the return statement.  It can be any valid data type.  If no data type is specified the function is assumed to return an integer result. function-name:  Must follow same rules of variable names in C.  No two functions have the same name in a C program. argument declaration:  It is a comma-separated list of variables that receive the values of the argument when function is called.  If there is no argument declaration the bracket consists of keyword void.

52 52  A function name is used three times in a C program: for declaration, in a call, and for definition. Function Declaration (or) Prototype:  The ANSI C standard expands the concept of forward function declaration.  This expanded declaration is called a function prototype. A function prototype performs two special tasks:  First it identifies the return type of the function so that the compile can generate the correct code for the return data.  Second, it specifies the type and number of arguments used by the function. Note: The prototype normally goes near the top of the program and must appear before any call is made to the function. User-defined Functions (Contd…)

53 53 The general form of the function prototype or declaration is: User-defined Functions (Contd…)

54 54 The Function Call:  The operand in a function is the function name.  The operator is the parameter lists (…), which contain the actual parameters. Example: void main () { sum (a, b); }  When the compiler encounters the function call,the control is transferred to the function sum().  The function is executed line by line and produces the output for the sum of two numbers and then control is transferred back to the main function. User-defined Functions (Contd…)

55 55 Function Definition: The function definition contains the code for a function. It is made up of two parts:  The function header and the function body, the compound statement is must. Function header consists of three parts:  the return type,  the function name, and  the formal parameter list.  Function body contains local declarations and function statement.  Variables can be declared inside function body.  Function can not be defined inside another function. User-defined Functions (Contd…)

56 56 Function Definition User-defined Functions (Contd…)

57 57 Category of User –Defined Functions: A function, depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories: Category 1: Functions with no arguments and no return values Category 2: Functions with no arguments and return values Category 3: Functions with arguments and no return values Category 4: Functions with arguments and return values User-defined Functions (Contd…)

58 58 1. Functions with no arguments and no return values:  This type of function has no arguments, meaning that it does not receive any data from the calling function.  Similarly function does not return any value. User-defined Functions (Contd…)  In the figure, the function greeting () do not receive any values from the function main () and it does not return any value to the function main ().  Observe the transfer of control between the functions indicated with arrows.

59 59 /*Example for Functions with no arguments and no return values to print addition of sum of two numbers*/ #include void sum(); /* function prototype */ void main() { sum (); /* function calling*/ } void sum ()/* Function Definition */ { int x, y, z; printf (“\n Enter the values of x and y: “); scanf (“%d%d”, &x, &y); z=x+y; printf (“\n The sum = %d”,z); } User-defined Functions (Contd…)

60 60 2. Functions with no arguments and return values:  Generally, there are two ways that a function terminates execution and returns to the caller.  When the last statement in the function has executed and conceptually the function’s ending ‘}’ is encountered.  Whenever it faces return statement. The return statement: It is the mechanism for returning a value from the called function to its caller. The general form of the return statement is: return expression; User-defined Functions (Contd…)

61 61  In this category, there is no data transfer from the calling function to the called function. But, there is data transfer from called function to the calling function.  In the above Figure, observe that the function getQuantity () do not receive any value from the function main ().But, it accepts data from the keyboard, and returns the value to the calling function. Functions with no arguments and return values (Contd…)

62 62 /*Example for Functions with no arguments and return values to print addition of sum of two numbers*/ #include int sum();/* function prototype */ int main() { int c; c = sum(); /*function calling */ printf (“\n The sum = %d”, c); } int sum ()/* Function Definition */ { int x, y; printf (“\n Enter the values of x and y: “); scanf (“%d%d”, &x, &y); /* return value to the calling function */ return x+y; } User-defined Functions (Contd…)

63 63 3. Functions with arguments and no return values:  In this category there is data transfer from the calling function to the called function using parameters.  But, there is no data transfer from called function to the calling function. Local Variables:  Variables that are defined within a function are called local variables.  A local variable comes into existence when the function is entered and is destroyed upon exit. Function Arguments: The arguments that are supplied to function are in two categories 1. Actual Arguments/Parameters 2. Formal Arguments/Parameters User-defined Functions (Contd…)

64 64 Functions with arguments and no return values (Contd…) Actual Arguments/Parameters:  Actual parameters are the expressions in the calling functions.  These are the parameters present in the calling statement (function call). Formal Arguments/Parameters:  Formal parameters are the variables that are declared in the header of the function definition. Note: Actual and Formal parameters must match exactly in type, order, and number. Their names however, do not need to match. User-defined Functions (Contd…)

65 65 User-defined Functions (Contd…) Functions with arguments and no return values (Contd…) Observe from the above figure, the function printOne () receives one value from the function main (), display the value copy of a.

66 66 /*Example for Functions with arguments and no return values to print addition of sum of two numbers*/ #include void sum(int,int);/* function prototype */ void main () { int a, b; printf (“\n Enter the values of a and b: “); scanf (“%d%d”, &a, &b); sum (a, b); /*calling function */ } void sum (int x, int y)/* function definition */ { int z; z=x+y; printf (“\n The Sum =%d”, z); } User-defined Functions (Contd…)

67 67 Passing Parameters to Functions: There are two ways of passing parameters to the functions. 1. Call by valueand 2. Call by reference Call by value:  When a function is called with actual parameters, the values of actual parameters are copied into the formal parameters.  If the values of the formal parameters changes in the function, the values of the actual parameters are not changed.  This way of passing parameters is called call by value (pass by value).  In the below example, the values of the arguments to swap () 10 and 20 are copied into the parameters x and y.  Note that the values of x and y are swapped in the function.  But, the values of actual parameters remain same before swap and after swap. Note: In call by value any changes done on the formal parameter will not affect the actual parameters. User-defined Functions (Contd…)

68 68 4. Functions with arguments and return values:  In this category there is data transfer between the calling function and called function. User-defined Functions (Contd…) Observe from the above figure, the function sqrt() receive one value from the function main (), finds the square of the number and sends the result back to the calling function.

69 abs( ) function 1. abs( ) function in C returns the absolute value of an integer. 2. The absolute value of a number is always positive. 3. Only integer values are supported in C. 4. “stdlib.h” header file supports abs( ) function in C language. 5. Syntax for abs( ) function in C is given below. int abs ( int n );

70 #include int main() { int m = abs(200); int n = abs(-400); printf("Absolute value of m = %d\n", m); printf("Absolute value of n = %d \n",n); return 0; }

71 output Absolute value of m = 200 Absolute value of n = 400

72 C – floor() function floor( ) function in C returns the nearest integer value which is less than or equal to the floating point argument passed to this function. “math.h” header file supports floor( ) function in C language. Syntax for floor( ) function in C is given below.

73 #include int main() { float i=5.1, j=5.9, k=-5.4, l=-6.9; printf("floor of %f is %f\n", i, floor(i)); printf("floor of %f is %f\n", j, floor(j)); printf("floor of %f is %f\n", k, floor(k)); printf("floor of %f is %f\n", l, floor(l)); return 0; }

74 Output: floor of 5.100000 is 5.000000 floor of 5.900000 is 5.000000 floor of -5.400000 is -6.000000 floor of -6.900000 is -7.000000

75 round( ) function round( ) function in C returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from ”.1 to.5”, it returns integer value less than the argument. If decimal value is from “.6 to.9″, it returns the integer value greater than the argument. “math.h” header file supports round( ) function in C language.

76 #include int main() { float i=5.4, j=5.6; printf("round of %f is %f\n", i, round(i)); printf("round of %f is %f\n", j, round(j)); return 0; }

77 output round of 5.400000 is 5.000000 round of 5.600000 is 6.000000

78 ceil( ) function ceil( ) function in C returns nearest integer value which is greater than or equal to the argument passed to this function. “math.h” header file supports ceil( ) function in C language.

79 #include int main() { float i=5.4, j=5.6; printf("ceil of %f is %f\n", i, ceil(i)); printf("ceil of %f is %f\n", j, ceil(j)); return 0; }

80 output ceil of 5.400000 is 6.000000 ceil of 5.600000 is 6.000000

81 trunc( ) function trunc( ) function in C truncates the decimal value from floating point value and returns integer value. “math.h” header file supports trunc( ) function in C language.

82 #include int main() { printf ("truncated value of 16.99 = %f\n", trunc (16.99) ); printf ("truncated value of 20.1 = %f\n", trunc (20.1) ); return 0; }

83 output truncated value of 16.99 = 16.000000 truncated value of 20.1 = 20.000000

84 isalpha() function isalpha( ) function in C language checks whether given character is alphabetic or not. Syntax for isalpha( ) function is given below. int isalpha ( int x );

85 #include int main() { char ch; printf("Enter any character\n"); scanf("%c", &ch); if ( isalpha ( ch ) ) printf ( "\nEntered character is alphabetic" ) ; else printf ( "\nEntered character is not alphabetic" ) ; }

86 output Enter any character t Entered character is alphabetic

87 isdigit() function isdigit( ) function in C language checks whether given character is digit or not. Syntax for isdigit( ) function is given below. int isdigit ( int x );

88 #include int main() { char ch; printf("Enter any character\n"); scanf("%c", &ch); if ( isdigit ( ch ) ) printf ( "\nEntered character is digit" ) ; else printf ( "\nEntered character is not digit" ) ; }

89 output Enter any character 200 Entered character is digit

90 1. isalnum( ) : checks whether character is alphanumeric isalnum( ) 2. isspace( ) : checks whether character is space isspace( ) 3. islower( ) :checks whether character is lower case islower( ) 4. isupper( ) : checks whether character is upper case isupper( ) 5. tolower( ) :checks whether character is alphabetic & converts to lower case tolower( ) 6. toupper( ) : checks whether character is alphabetic & converts to upper case toupper( )

91 Random Numbers: A random number is a number selected from a set in which all members have the same probability of being selected. Calling the random function several times generates a series of random numbers.

92 program to generate random numbers #include int main( ) { int c, n; printf("Ten random numbers in [1,100]\n"); for (c = 1; c <= 10; c++) { n = rand( )%100 + 1; printf("%d\n", n); } return 0; }

93 output Ten random numbers in [1,100] 84 87 78 16 94 36 87 93 50 22


Download ppt "UNIT-3. Repetitive control structures – Pre-test and post-test loops, initialization and updation, event and counter controlled loops, while, do..while,"

Similar presentations


Ads by Google