1 / 96

The do - while - loop

The do - while - loop. Another repetitive construct is the do - while - loop Its syntax is: do statement while (expression); Meaning of the construct It works in much the same way as the while-loop except that the body of the loop is executed at least once.

stops
Download Presentation

The do - while - loop

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The do - while - loop • Another repetitive construct is the do - while - loop • Its syntax is: • do • statement • while (expression); • Meaning of the construct • It works in much the same way as the while-loop except that the body of the loop is executed at least once. • Statement is executed once on entry into the loop and then as long as expression remains true. • We could write it as an equivalent while-loop as • statement • while (expression) • statement

  2. do - while - loop: example program • #include <math.h> • #include <stdio.h> • main() • { • int sum, n; • scanf("%d", &n); • sum = 0; • do { • sum += n % 10; • n /= 10; • } • while(n / 10 > 0); • printf("The sum of the digits is = %d\n", sum); • }

  3. The switch statement • It can be used in place of if-else ladder. The syntax of a switch statement is: switch expression case value--1: block--1 case value--2: block--2 ............ default: default--block • The evaluation of the switch statement is governed by the value of expression. This expression can either be an integer expression or a character variable. • The expression is evaluated and its value is matched to value--1, value--2, …. • Suppose it matches with value--2, then the execution starts from block--2 and continues all the way to default--block. • If it does not match with any value, then the execution starts from the default--block. • Each value--i must thus be either a constant integer or a constant character.

  4. Branching statements • Branching statements are those control statements that transfer the control of the program to another point. • The break statement: • It terminates the smallest enclosing while, do, for, switch statement. • Execution resumes at the statement following the terminated statement. • Example: • for (i=0; i<n, i++) • { • if (mark[i]<0){flag = 1; break;} • sum = sum+mark[i]; • } • if (flag==1) printf('error');

  5. The continue statement • It terminates the current iteration of nearest enclosing while, do, for, or switch statement. • In while and do, the execution resumes with loop control evaluation. • In for the execution resumes with the execution of expr3. • Example: • do • {read(ch); • if (ch == '\0') continue; • processcharacter(ch); • } • while(ch != ‘-');

  6. The goto statement • Used for transferring the control unconditionally to some statement. • Syntax: • goto label; • ...... • ...... • label : statement; • This is called forward jump. • Backward jump can also be used for iterative programs. • label: statement ; • ....... • ...... • goto label;

  7. The goto statement: cont'd. • goto statement can be used to come out of loops like while, for etc • while (cond) • { • ..... • for (....) • { • ...... • if (cond2) goto out_of_for_loop; • .... • } • out_of_for_loop: ..... • if (cond3) goto out_of_while_loop; • ...... • } • out_of_while_loop: • ......

  8. Example program to find the highest, lowest, range and average of given numbers. • main(){ • int count; • float value,high,low; • float sum,average,range; • count=sum=0; • printf("Enter numbers: "); • printf("negative no. to end /n"); • input: • scanf("%f", &value); • if (value < 0) goto output; • count++; • if (count == 1) high = low = value; • else if(value > high) high=value; • else if (value < low) low=value; • sum = sum + value; • goto input; • output: • average = sum / count; • range = high - low; • printf("Total values :%d / n",count); • printf("Highest:%f,Lowest:%f /n", high,low); • printf("Range:%f,Average:%f /n", range,average); • }

  9. Arrays • Often we need to identify a group of items with a common name. • For example, we may be interested in knowing the names of all students in a class. We would like to store these names in an attendance register and use this register for our reference. • We can associate with each student a unique identifier (his roll number) and can use this unique identifier to store/retrieve the information about the student. • Array in C has a similar construct. We can give a name to this group of names and store the names in the contiguous memory locations. • In other words, array contains related data items which share a common name. Individual data item in this array is referred to as element. • Example: We can store the names of 20 student is array name. The name of the 20 members of the group will be stored in name[0] to name[19]. • name is the name of the one-dimensionalarray and `19' is the subscript indicating the position of the element in the array starting from zero.

  10. Array elements • A subscripted variable or array element can be used just like any other variable in the program. The elements of the array reside in contiguous memory locations. The space taken by each element depends on the type of the element. • Examples: • marks[20] = 0; • sum = sum + marks[i]; • marks[10] = 2 * marks[i-1]; • Arrays should be declared before they can be used. array_typearray_typearray_name[size]; • Here array_type defines the type of the array elements. size tells the compiler the number of elements in the array so that the compiler can allocate the appropriate memory space for the array. • A common programming error is to try to access an array element by using a subscript larger than the size of array. It is called bound-violation.

  11. Examples of one dimensional arraysand their initialization • int marks[50]; • float temperature[10]; • char name[10]; • boolean flags[5]; • Initialization of array is similar to ordinary variables. • array_name[size] = list_of_values; • Every value in the list should be separated by a comma. • Example: • int marks[5] = {1,2,0,4,1}; • If the size of array is omitted in the initialization statement, the size is assume to be equal to the number of values listed. • int marks[ ] = {1,2,3,4}; • char name[ ] = {‘M','O','H','A','N‘}; • Marks and name will have sizes 4 & 5 respectively.

  12. Initializing selected elements of an array • There is no simple method to initialize selected array elements. This can be done by using assignment statements for individual selected elements. • Example: • marks[5] = 0; • marks[7] = 5; • for (i = 0;i <= 20;i++) marks[i] = i * 2; • for (i = 21;i <= 45;i++) marks[i] = 0; • There is a difference in the initialization done in the previous slides • and in this slide. The elements in the previous examples were • initialized during the compilation itself, while in the present case, • they will be initialized only during execution.

  13. Example program • Calculate the frequency of students getting various marks in a subject out of 100 marks. • main(){ • int i,j,numstudents,freq[101]; • for (i = 0;i <= 100;i++) freq[i] = 0; • printf("No.of students in class \ n"); • scanf("%d",&numstudents); • for (j = 0;j < numstudents;j++) • {printf("Marks of %dstudent \n",j+1); • scanf("%d",&i); • ++freq[i]; • } • for (i = 0;i <= 100;i++) • if(freq[i]) printf("Students with %d marks=%d\ n",i,freq[i]); • }

  14. Two dimensional arrays • An array of arrays. • Used to store table of values. • The table contains many rows and columns. • The declaration : • int thisarray[r][c]; • declares an array or table with r rows and c columns and a total of r * c elements where each element is of type integer. • Each element of the array has two subscripts denoting the row and column numbers of the element in the table.

  15. Storing and initializing 2-dimensional arrays • Stored in row--major order, i.e., elements of (i+1)th row will follow the elements of ith row. If we initialize a two dimensional array the values will be assigned in this order only. • int thisarray[3][2]={1,2,3,4,5,6}; • It will initialize • thisarray[0][0] = 1, thisarray[0][1] = 2, thisarray[1][0] = 3, thisarray[1][1] = 4, thisarray[2][0] = 5, thisarray[2][1] = 6 • Other way to initialize a 2--Dimensional array is by initializing each row separated by braces. • Example : Exactly same initialization by following statement. • int thisarray[3][2]={{1,2},{3,4},{5,6}}; • If a value is missing in the list of values for a row, it is initialized with 0. • int thisarray[3][2] = {{1},{3,4},5}; • will initialize thisarray[0][1] and thisarray[2][1] to 0

  16. Strings • A string is an array of characters terminated by null character • '\ 0'. • Constant String : A sequence of characters between a pair of double quotes: • "Very Good Boy", "Abraham Lincoln" etc. • A null character '\ 0' is assumed at the end of every string. • Commonly used to build readable and meaningful programs and passing on the messages about required inputs and generated output (either interactively or through files).

  17. String definitions • String variables are declared as an array. • char string_name[size]; • char myname[15]; • While allocating the space (size) to a character array it should be kept in mind that a null character (' \ 0 ') is always appended to the character array storing the string. • The string can be initialized using the usual form of initializing an array by listing the elements: • char myname[10] = {'A','.','K','.',‘J',‘a',‘i',‘n', ‘\ 0 ‘}; • char myname[10] = "A.K.Jain"; • If we do not specify the size during declaration and initialization, the size will automatically be set to the length of the string (including the null character). • char myname[ ] = "A.K.Jain" • will allocate 9 bytes to myname.

  18. Operations on strings • Reading and Writing Strings. • Comparing strings. • Copying one string to another. • Finding the length of a string. • Combining two or more strings. • Extracting substrings from a string.

  19. Reading strings • scanf() is used to read the input strings. • char myname[15]; • scanf ("%s", myname); • will read a maximum of 14 characters from the input and will store in array myname. The operation terminates at the first white space character (blank, tab, carriage return, new line etc.).

  20. Reading & writing a whole line of text • To read a complete line of text as a single string, a special format specifier of scanf is used: • scanf("%[^\n]s", str); • The above statement reads the entire text up to the newline character into the string str. • The [] in the format means that a string is to be read, and the ^\n inside means that the string may contain everything except a newline character. • A string can be written using printf() function and %s format. • The command • printf("%s", myname); • prints the string stored in array myname. • There are various formatting commands for printing strings.

  21. Character and integer • Converting a character string to its integer equivalent. • function atoi(string) • converts a string of digits to its numerical equivalent. • char number[6]="12345"; • int x; • x = atoi(number) ; • will store 12345 in integer variable x.

  22. Combining two strings • Assignment statement cannot be used to add two strings. • Generally, strcat() function is used to concatenate two strings. • strcat(string1,string2) will appendstring2 to string1 after removing the null character of the string1. • string2 can be either a constant string or a string variable. • Nesting of string concatenation is also possible by calling strcat function within strcat. • strcat(strcat(s1,s2),s3) • will first concatenate s1 and s2, and then s3 will be appended to it.

  23. Comparing two strings • The two strings s1 and s2 can be compared using the function • strcmp(). • strcmp(s1,s2) will compare the two strings s1 and s2, and will return a value 0 if both strings match or will return the numeric difference between the first characters (from left) of two strings where they differ. • Example: • strcmp("abcd","acbd") • will return a value 1. • The strings s1 or s2 can be either constant or variable.

  24. Finding the length of a string • strlen(s1) can be used to return the length of a string. • The length is counted from the first character of the string to the • first null character in the string. • Example: • n = strlen("My Dear Fellow"); • will return the value 14 in n. • The string s1 can be either a constant or a variable.

  25. Copying one string to another • strcpy(s1,s2) copies string s2tos1. • where s1 is a string variable. • string s2 can be either constant or variable. • size of s1 should be at least equal to the length of s2.

  26. Functions: introduction • Using a function, we `encapsulate' some useful piece of computation. We begin with an easy example. • C has no operator for exponentiation, that is, for taking power. Of course, whenever in a program we need exponentiation, we can write at that point the code which will do the job. However, it is far better to `encapsulate' the code for exponentiation in one place, and invoke the computation for exponentiation as and when needed in the main computational task • Function for exponentiation: We want to compute a^b, and output its value, where a ranges from 0 to 9, and b ranges from 0 to 9. • int i; • long result; • result = 1; • for( i = 1;i <= b; ++i ) • result *= a;

  27. Complete program • #include <stdio.h> • long power(int a,int b); • /*This program displays the value of power(x,y), where 0<=x<=9 and 0<=y<=9*/ • main() • {long power(int a, int b); • int i,j; • for (i=0; i<=9; ++i) • for (j=0; j<=9; ++j) • printf("%5d%5d%10d\n",i,j,power(i,j)); • } • long power(int a, int b) • {int i; • long result; • result=1; /* initialize result to 1 */ • for (i=1; i<=b; ++i) result *=a; • return result; • }

  28. Explanation • In general, a C program consists of instructions to the preprocessor, declarations, and function definitions. • Every program must have a function named as main. • A function has to be declared in the program text before its use is made in the text. • Declaration of power is given in the line: • long power(int m, int n); • long is the return type, that is, the type of what is returned by the function, here, a long integer.

  29. We use the term function prototype for the declaration of a function. The general form of function prototype is • return-type function-name(type param-1, type param-2, . . .., type param-n); • The general rule is: no function can be used before it is declared. • In our program, we use power in main, the definition of power comes after main. Hence the necessity of the declaration • long power(int m, int n); • Notice that the declaration provides the type information of m, n, and of what is being returned.

  30. Function definition • The general form of a function definition is this: • return-type function-name( type param-1, ...., type param-n) • declarations • statements • The definition of a function specifies what computation is being encapsulated. This is done in terms of parameters, and local variables. • The execution of any program begins by executing main. • Whenever a call is made to a function, the control passes to the function named in the call.

  31. What happens during execution • The first thing that happens is that the value of each argument is copied into the corresponding parameter. • Now, the statements in the function are executed one after another from the beginning of the function body. • Execution of a called function ends either when a return statement is executed, or when no more statements are there in the function body to execute. • Then the control passes back to the calling program, at the point just after where the call to the function was made. A function may return a value, which can be used by the calling program.

  32. Statement return • Execution of a return immediately passes control from the function body where the the return statement is, to the calling function. • In addition, a return statement can also return a value to the calling program. • The return statement has two forms: • return; • return expression; • In the first case, all that the statement does is to return control immediately to the calling program. • In the second case, besides returning control, the return statement returns to the calling program whatever value expression evaluates to. • It is called the return value of the function, or the function value.

  33. Example: function to find if a given number is prime • #include <stdio.h> • int is_prime(long m); • main() • { • long n; char s[2]; • do { • Printf(“do you want to continue\n?”) • Scanf(“%s”, &s); • If (s=“NO”) exit; • printf("input a number (less than 1 terminates program)\n"); • scanf("%d", &n); /* read in a number */ • if (n < 1) break; /* terminate ? */ • if (is_prime(n)) /* check whether n is prime */ • printf("%3d is prime\n", n); • else • printf("%3d is not prime\n", n); • } while (1); • int is_prime( long m) • {long i; • /* The following loop checks whether m is non-prime, i.e., it is divisible by an i, 2<=i<m .*/ • for (i = 2; i < m; ++i)if (m%i == 0) return 0; • return 1; • }

  34. The exit statement • Suppose that you have written a program in which, inside a function that is called from the main, you ask the user if he/she wishes to continue with the execution of the program. • If the answer is no, your program must stop executing. How do you take care of this? • You can return to main program from function and then exit. • Better way is to use statement exit() in C which stops the execution of the program. • So, we can give the following in our example above: • if (answer == NO) exit(); • The program would exit the moment user gives a negative answer.

  35. Functions of type void • We are used to functions in school mathematics evaluating to a value given their arguments. Examples are sin, cos, etc. on an argument, say x, sin(x) evaluates to a value. the value of the function. • However, there may be functions who do not return any value. • As an example, let us write a function lineof which takes a character as an argument, and prints a line containing a constant number of occurrences of the argument character. • The function is for performing an action, printing a line, and it has no value to return. Hence its return-type is void. • void lineof(char c) • { int i; • for (i = 1; i <= MAXLINE; ++i) printf("%c", c); • printf("\n"); • }

  36. Call-by-value • Recall that a function is written in terms of parameters or formal arguments. • When a function is called, arguments are specified in the call. • In general, an argument can be an expression. • Suppose a function f has n parameters, named as p1,p2, ...., pn. • Suppose a particular call to f is f(e1, ...., en) • As this call is made, the value of each ei is copied into pi, and then the execution of the function body begins. • This way of relating arguments to parameters is called call-by-value, and it is this scheme which C follows. • Valid calls: • power( i*i+2, 53 ) • is_prime(power(i,j) + power(j,i)+1)

  37. Internal and external variables • A variable can be internal or external. • All variables defined inside a function, and the parameters of the function, are internal variables. • A variable defined outside of any function is called an external variable. • In the internal/external terminology, all functions in C are external • because C does not allow defining a function inside another function.

  38. Scope • The scope of a name is the part of the program text within which the name can be used. • A program text can be broken into several files. • The scope of an external variable or a function is from the point at which it is declared to the end of the file containing the declaration. • The definition of a function or a variable is also taken as its declaration (but not the other way round). • Consider for example: • In file1: • .. • /* Next two lines occur outside any function */ • int x1,x2; • char c; • .. • int f1( int a, int b) • .. • The two lines after the comment define and declare external variables • x1, x2 and c. After that comes the definition and a declaration of the • function f1.

  39. Scope: cont'd. • Now suppose our program consists of two files: file1 and file2. If in file2, we want to use x1,x2,c and f1, we must declare these in file2. • When we want to simply declare as external variable but not define it, we use the keyword extern. In case of functions, we use function stototypes for the same purpose. • file2 will, therefore, look like: • : • extern int x1,x2; • extern char c; • : • int f1( int a, int b ); • : • :

  40. Blocks • To understand the scope of internal variables, we need to appreciate the notion of a block. • A block, or a compound statement is of the form • definitions of variables • statements • The body of a function is always a block. • Variables defined inside a block are internal variables; their scope is limited to the block in which they are defined. Such variables are also called local or automatic variables. • Parameters of a function are also internal or automatic variables, their scope is limited to the block which is the body of the function.

  41. Example • #include <stdio.h> • main(){ • int x=5; • int y=3; • void swap(int, int); • printf(“x=%d y=%d \n”, x,y); • swap(x,y); • printf(“x=%d y=%d \n”, x,y); • } • void swap(int x, int y) • {x=x+y; • y=x-y; • x=x-y; • printf(“x=%d y=%d \n”, x,y); • } • Output: • x=5 y=3 • x=3 y=5 • x=5 y=3

  42. Recursion • It is permitted in C for a function to call itself from within its own body. Such a function is called a recursive function. • A program that uses recursive functions is called a recursive program. • Recursion is a very powerful programming technique. Often it leads to short, elegant programs. • Example: • factorial(n) = n* factorial(n-1) for n>0; • factorial(0)=1 for n=0;

  43. C function for factorial • The factorial definition naturally leads to this function that returns the factorial of its argument:long factorial(int n){ if (n == 0) return 1; return n * factorial(n-1);}

  44. Notion of recursion `bottoming out' • If we call factorial with argument 4, then a call factorial(3) is made, which in turn leads to factorial(2), and so on, until the call factorial(0) is made -- which does not invoke any further call to factorial. • This is where the recursion ends, or the recursion bottoms out. • If your recursive program is correct, the recursion will always bottom out for every input.

  45. Many copies of function exist simultaneously • Suppose we make a call to factorial with m as its argument. Let us assume that m > 0. As the body of the function is executed, we come upon the statement return n * factorial(n-1); • Here n has the value m. To execute the statement, the expressionn * factorial(n-1) • needs to be evaluated, where n has the value m. • Thus a call is made to factorial with an argument whose value is m-1. • The old call is not yet over; it will be over after this second call is over, the expression evaluated, and the result returned. • Remember n being a parameter, n is an automatic variable, therefore, each call has its own copy of n. • For the time being, it is easy to see that if the call with argument value (m-1) returns the correct value, that is, factorial(m-1), then the original call also returns the correct value.

  46. More examples • Multiplications through additions: • int mult(int a, int b){ if (b == 0) return 0; return (a + mult(a, b-1));} • GCD of two non-negative integers: • int gcd(int u, int v) • { • if (v==0) return (u); • return gcd(v, u%v) • }

  47. Quiz Tomorrow

  48. Pointers • The notion of pointers is of central importance to C programming because appropriate use of pointers leads to efficient programming and certain kinds of computations that we want to do can be done only by using pointers. We need to understand the notion of address of variables,arrays, functions, etc. in order to understand what a pointer is, and how a pointer is used.

  49. Memory: a simplified view • The memory of a computer can be thought of as a linear arrangement of cells placed one after another. Each cell has a unique address. • For every variable, one or more consecutive cells are earmarked to store the value of the variable. The number of cells earmarked depends on the type of the variable. The address of the leftmost cells of the group of cells which are reserved to contain the value of the variable is the address of the variable.

  50. Access by address • So far, we have been using the name of a variable to accessit, for example, in x = y + 1;Since a variable also has an address, this address can also beused to access the variable.

More Related