You are on page 1of 15

CHAPTER ~ DECISION MAKING AND BRANCHING

=> The order of execution of statements involves a kind of decision making to see whether a particular

condition has occurred or not and accordingly direct the computer to execute certain statements. C language supports such capabilities by supporting the following statements:- (A) IF statement (B) SWITCH statement (C) Conditional operator statement (D) GOTO statement. These statements are popularly known as Decision making statements and since these statements control the flow of execution of statements, they are also called as Control statements.
IF STATEMENT => The if statement is a powerful tool which is used to control the flow of execution of statements. It is

a two-way decision statement and is used in conjunction with an expression. [ SYNTAX:- if(test expression) ]. Here, the expression(relation or condition) is evaluated first and then depending on whether its value is TRUE(nonzero) or FALSE(zero), it transfers the control to a particular section of statements. This point of program has two paths to follow, one for true and another for false condition. The if statement may be implemented in different forms depending on the complexity of the conditions to be tested. They are:- (A) Simple if statement (B) if.else statement (C) Nested if.else statement (D) else if ladder. (A) Simple if statement:- The General Form of a Simple if statement is if(Test expression) { Statement Block; } Statement x; The statement block may be single statement or group of statements. If the test expression is true, the statement block is executed else the Statement Block is skipped and the execution will jump to statement x. This is often used for counting purposes. (B) IF.ELSE statement:- The General Form of if.else statement is if(Test expression) { True Statement Block; } else { False Statement Block; } Statement x; If the test expression is true, then the true block statements is executed otherwise the false block statements is executed. In any case, either the true block or the false block only is executed, not both. (C) Nested if.else statement:- The General Form of Nested if.else statement is if(Test expression-1) { if(Test expression-2) { Statement Block-1; } else { Statement Block-2; } else { Statement Block-3; } Statement x; When a series of decisions are involved, we use more than one if.else statement in nested form. If the test expression is false, statement block-3 will be executed otherwise test expression-2 will be evaluated. If true, statement block-1 will be executed else statement block-2 will be executed. (D) ELSE IF Ladder:- This way is required in putting ifs together when multipath decisions are involved. A multipath decision is a chain of ifs in which the statement associated with each else is an if.

The General Form of Else if Ladder statement is if(Test expression-1) { Statement Block-1; } else if(Test expression-2) { Statement Block-2; } else if(Test expression-3) { Statement Block-3; } .. else if(Test expression-n) { Statement Block-n; } else default statement; Statement x; The conditions are evaluated from top and as soon as a true condition is found, the statement associated with it is executed and control is transferred to statement x. when all conditions fail, the finel else containing the default statement is executed.
SWITCH STATEMENT

The Switch statement tests the value of a given variable(or expression) against a list of cases values and when a match is found, a block of statements associated with that case is executed. The General Form of a Switch statement is as follows:Switch(expression) { case value-1: Block-1; break; case value-2: Block-2; break; case value-n: Block-n; break; default: Block-x; break; } Statement x; The expression is an integer expression or characters(integral type). Value-n are constants or constant expressions(evaluable to an integral constant) and are known as case labels. Each of these values should be unique within a switch statement. Case labels should end with a colon(:). When a switch statement is executed , the value of the expression is compared against the values and for the matching case, the block of statements that follows within the switch statement is executed. The break statement is optional and signals the end of a particular case and causes an exit from the switch statement. If no match is found, then at most one default case label statement which may be placed anywhere in the block is executed. It is permitted to nest switch statements.
THE ? : OPERATOR

This operator is known as Conditional Operator and is useful in making two-way decisions. This operator is a combination of ? and : and takes 3 operands. The General Form of a Conditional Operator is as follows:<conditional expression>?expression-1: expression-2

The conditional expression is evaluated first. If the result is non-zero, expression-1 is executed and is returned as the value of the conditional expression else expression-2 is evaluated and its value is returned. The conditional operator can be nested for evaluating more complex assignment decisions. It makes the code more concise and efficient.
GOTO STATEMENT

The Goto statement is required to branch unconditionally from one point to another in a program. The Goto statement requires a label in order to identify the place where the branch is to be made. A label is any valid variable name followed by a colon(:). The label is placed immediately before the where the control is to be transferred. The label can be anywhere in the program either before or after the Goto label; statement. The General Form of a Goto and label statement is as follows:goto label; ! label: .. ! statements; .. ! .. label: ! .. statements; ! goto label; Review

CHAPTER ~ DECISION MAKING AND LOOPING In looping, a sequence of statements is executed until some conditions for the termination of the loop are satisfied. A program loop consists of two segments: Body of the loop and the Control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. A control structure is classified as Entry-controlled loop or Exitcontrolled loop. In entry-controlled loop, control conditions are tested before the loop execution whereas in exit-controlled loop, the test is performed at the end of the body loop. These are also known as pre-test and post-test loops respectively. Based on the nature of control variable and the kind of value assigned, the loops are classified as Counter-controlled loops and Sentinel-controlled loops. A Counter-controlled loop is also known as definite repetition loop. A control variable called as counter is initialized and the number of times of execution is a constant. A Sentinel-controlled loop is also known as indefinite repetition loop. A special value called sentinel value or sentinel variable is used to change the loop control expression from true to false. Here, the number of repetition is not known beforehand.
THE WHILE STATEMENT

The simplest of all is the while statement. The General Form of a While statement is as follows:While(test expression) { Body of the Loop; }

The While is an Entry-controlled loop statement. The test-expression is evaluated first and if the condition is true, then the body of the loop is executed. After execution, the test expression is evaluated again continuously until the condition becomes false and the control is transferred out of the loop.

Ex. while(n<=10){ This is a typical example of a counter-controlled loop and the variable n is called the counter or control variable. Ex. while(character!=Y){ Character=getchar(); This is a typical example of a sentinel-controlled loop and the character constant Y is called the sentinel value and the Character is referred as sentinel variable.
THE DO-WHILE STATEMENT

In some cases, it is necessary to execute the body of the loop before the test is performed. This situation can be tackled by using the Do-while statement. The General Form of a Do-while statement is as follows:do { Body of the Loop; } While(test expression); On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the test expression in the while statement is evaluated and if true, executes the body again. This continues as long as the condition is true. The Do while construct provides an Exit-controlled loop and hence the body is always executed at least once.
THE FOR LOOP

The For loop is another Entry controlled loop that provides a more concise loop control structure. The General Form of a For loop statement is as follows:For( initialization; test condition; increment/decrement ) { Body of the Loop; } Initialization of the control variables is done first using assignment statements and the variables are known as loop control variables. The value of the control variable is tested using the test condition which is a relational expression and if true, the body of the loop is executed. After the body is executed, the control variable is increment/decrement. The For statement allows for negative increments. Since the conditional test is always performed at the beginning of the loop, the body of the loop maynt be executed at all. More than one variable can be initialized at a time in the For statement. Similarily, the increment section may also have more than one part. Also the test condition may have compound relation and the testing need not be only limited only to the loop control variable. It is permissible to use expressions in the assignment statements of initialization and increment sections. It can also have one or more sections omitted but semicolons separating them must remain. We can set time delay loop using the null statement. Nesting of loops i.e. one For loop within another For loop is allowed in C. ANSI C allows up to 15 levels of nesting. Ex. for( int i=1; i<9; i++ ) { ---------

---------for( int j=10; j>0; j-- ) { --------} } * Use For loop if the counter-based control is necessary and Use While loop if the sentinel-based control is required. Jumping out An early exit from the loop can be accomplished using the Break statement or the Goto statementthe Break statement loop will exit only one loop. Since the Goto statement can transfer the control the control to any place in a program, it is useful to provide branching within a loop. Another feature of Goto is to exit from a deeply nested loop whenever an error occurs. Structured programming discourages the implementation of a unconditional branching using jump statements such as goto, break and continue. Skipping out During the loop operations, it may be necessary to skip a part of the body of the loop under certain conditions. This feature can be carried out using the Continue statement. It causes the loop to be continued with the next iteration after skipping any statements in between i.e the statements that follow the continue statement until the closing braces of the loop. The format of Continue statement is as follows: Continue; It causes the control to go to directly to the test condition and then to continue the iteration process.

Jumping out of the program: One can jump out of a program b using the library function Exit(). The Exit() takes an integer value as its argument as zero is used to indicate normal termination and a nonzero value to indicate termination due to some error or abnormal condition. The use of Exit() function requires the inclusion of the header file <stdlib.h>. Review

CHAPTER ~ ARRAYS In order to handle large volume of data, C has a powerful collection of datatypes known as Derived types. C supports such a derived datatype called as Array. An Array is a fixed-size sequenced collection of elements of the same datatype. When a collection of integers/real values is addressed to, it is referred as an Array whereas when a collection of characters is addressed, it is referred as a String. ONE DIMENSIONAL ARRAYS A list of items that can be given one variable name using only one subscript and such a variableis called as a single-subscripted variable or One Dimensional Array. The subscripts of an array can be integer constants or expressions that yield integers. C performs no bounds checking and it should be ensured that the array indices are within the declared limits. The General Form of an Array declaration is as follows: <datatype><variable_name>[size]; The datatype specifies the type of element that will be contained in the array and the size indicates the maximum number of elements that can be stored inside the array. Any reference to the arrays outside the declared limits would not necessarily cause an error. The size should be a numeric constant or a symbolic constant. When the compiler sees a character string, it terminates it with an additional Null character. When declaring character arrays, we must allow one extra element space for the Null character/terminator. Initialization of One dimensional array:After an array is declared, its elements must be initialized else they contain Garbage Value. An array can be initialized at either of the following stages:y At Compile time. y At Run time. Compile time initialization We can initialize the elements of an array in a similar manner as the ordinary variables when they are declared. The General Form of an Array initialization is as follows: <Datatype><Array_name>[size] = { list_of_values }; The values in the list are separated by commas. Before initialization, the array elements contain Garbage Values. If the number of values in the list is less than the number of elements, then only that many elements will be initialized and the remaining elements are automatically set to zero if the array type is Numeric and NULL if the array type is Char. The size may be omitted if all the elements are initialized. However, if we have more initializers than the declared size, the compiler reports an error. Run time initialization An array can be initialized explicitly at the run time. This approach is usually applicable for initializing large arrays and arrays having no pre-defined values. This run time assignment can be done using the Scanf() or the Getchar() used repeatedly using the For loop or any other decision making loop. TWO DIMENSIONAL ARRAYS Apart from the One Dimensional Array, there can be situations when we are required to store a table of values. C allows us to define such tables of data items by using the Two-Dimensional Array.

The General Form of an Two Dimensional Array declaration is as follows: <Datatype><Array_name>[Row_size][Coloumn_size]; C places each size in its own set of brackets. Two dimensional arrays are stored in memory similar to the manner in which the One dimensional array but the rows being placed one after another. The elements of all rows within the two dimensional array are stored contiguously in increasing memory locations. Each dimension of the array is indexed from zero to its maximum size minus one; the first index selects the row and the second index selects the column within that row. The row size is optional. MULTI DIMENSIONAL ARRAYS C allows array of three or more dimensions. The General Form of an Two Dimensional Array declaration is as follows: <Datatype><Array_name>[Size1][Size2][Size3][SizeN]; Where Size(i) is the size of the ith dimension. A three dimensional array can be represented as a series of two dimensional array and in a similar manner any multi dimensional array can be represented as series of lower dimension array. ANSI C doesnt specify any limit for array dimension. Most compilers permit seven to ten dimensions. DYNAMIC ARRAYS So far the arrays have been created at compile time. This process of allocating memory space at compile time is known as Static Memory Allocation and the arrays that receive static memory allocation are called Static Arrays. In C, it is possible to allocate memory to arrays at runtime. This process of memory allocation at runtime is known as Dynamic Memory Allocation and the arrays created at runtime are called as Dynamic Arrays. This effectively postpones the array definition to run time. Dynamic arrays are created using variables known as Pointer Variables and Memory Management Functions i.e. Malloc, Calloc and Realloc. These functions are include in the header file <stdlib.h>. NOTE:Some important aspects regarding the application of arrays is as follows:y Using pointers for accessing arrays. y Passing arrays as function parameters. y Arrays as member of structures. y Using structure type data as array elements. y Arrays as dynamic data structures. y Manipulating character arrays and strings. Review

CHAPTER ~ CHARACTER ARRAYS AND STRINGS Like arrays, a String is a sequence of characters that is treated as a single data item. Any group of characters (Except double quote sign) defined between double quotation marks is a String Constant. If still we want to include a double quote in the string to be printed, then we may use it with a backlash. The varied operations that can be operated upon strings are as follows:y Reading and writing strings. y Combining strings together. y Copying one string to another. y Comparing strings for equality. y Extracting a portion of the string. DECLARATION AND INITIALIZATION C doesnt support strings as a datatype. However the strings are represented as character arrays. A string variable is any valid C variable name and is always declared as an array of characters. The General Form of an String variable declaration is as follows: Char <String_name>[Size]; The size determines the number of characters in the string. When the compiler assigns a character string to a character array, it automatically supplies a NULL character (\0) at the end of the string marking the end of the string. Therefore should be equal to the maximum number of characters in the string plus one. Like numeric arrays, the character array/string can be initialized during the declaration. An array name/string name cannot be placed onto the left of the assignment operator. The string is a variable-length structure and is stored in a fixed-length character array. READING STRINGS Using the Scanf function The scanf function, powered by the %s format specification can be used to read a string of characters. Ex. Char address [10]; Scanf(%s, address); By using the scanf function in this manner, we can handle inputting a string of characters. The disadvantage of this method is that the scanf function terminates on encountering a whitespace. A whitespace include blanks, tabs, carriage returns, form feeds and new lines. Apart from this, the scanf function automatically terminates the string that is read with a null character. Unlike scanf calls in character arrays, the ampersand(&) is not required before the variable. The problem to catch the whitespaces can be tackled by using the following type:Scanf(%[^\n], address); The format specification used here is known as the EDIT SET CONVERSION CODE %[.] which can be used to read a line containing a variety of characters, including whitespaces. We can also specify the field width using the form %ws in the scanf statement for reading a specified number of characters from the input string. By specifying the field width, the number of significant characters can be defined helping in easy usage.

Using getchar() and gets In order to input single character, we can use the Getchar() function. In order to input a string of characters, the Getchar() can be used repeatedly using the For loop or any other decision making loop to input the string variable. This can tackle the problem of reading whitespaces. Another convenient method of reading a string of text containing whitespaces is by using library function Gets() available in the header file <stdio.h>. The function takes one string as parameter and is called as:gets(<string_name>) ; where string_name is a string variable declared properly. It reads characters into the string from the keyboard until a newline character is encountered and then appends/adds a null character to the string. WRITING STRINGS Using the Scanf function The printf function, powered by the %s format specification can be used to write a string of characters. Ex. printf(%s, address); This would print the whole string on the output console. We can also specify the precision with which the string can be displayed. Ex. %9.4s indicates that the first four characters are to be printed in a field width of 9 columns placed at the last. The Printf() on UNIX supports another feature that allows for variable field width or precision. Ex. printf(%*.*s, w, d, str); Prints the first D characters of the string in the field width of W. Using putchar() and puts In order to print a single character, we can use the Putchar() function. In order to print a string of characters, the Putchar() can be used repeatedly using the For loop or any other decision making loop to print the string variable. It requires only one parameter. Another convenient method of writing a string of text is by using library function Puts() available in the header file <stdio.h>. The function takes one string as parameter and is called as:puts(<string_name>) ; Where String_name is a string variable declared properly. It writes characters from the string onto the output console until a null character is encountered. ARITHEMATIC OPERATIONS ON CHARACTERS Whenever a character constant or character variable is used in an expression, it is automatically converted into an integer value by the system which depends upon the local character set of the system. To write a character as an integer, we need to change only the format specification in the O/P function, i.e. char name=r; Printf(%d, name); It will display the numeric value of r i.e. 114. It is also possible to perform arithmetic operations on the character constants and variables. We can also use character constants in relational expressions.

The C library supports a function that converts a string of digits into their integer values. The function takes the form:int x; x = atoi(<String_name>); The process of combining of two strings together is known as Concatenation. STRING-HANDLING FUNCTIONS The C library supports a large number of string-handling functions that can be used to carry out many of the string manipulations required. In order to operate with these, we need to include the header file <string.h>. They are as follows:Strcat() Function The strcat() function joins/concatenates two strings together. It takes the following form:strcat(<string_name1>,<string_name2>); Where String_name1 and String_name2 are character arrays. When the function strcat() is executed, String_name2 is appended to String_name1. This process is carried out by removing the null character at the end of the String_name1 and placing String_name2 from there. The String_name2 remains unchanged. One should make sure that the size of String_name1(to which String_name2 is appended) is large enough to hold the final string. This function may also append a string constant to a string variable. C language permits nesting of strcat() function. Strcmp() Function The strcmp() function compares two strings identified by the arguments and has a value 0 if they are equal. If they are not equal, it contains the value which is equal to the numeric difference between the first non-matching characters in the strings. It takes the following form:strcat(<string_name1>,<string_name2>); Where String_name1 and String_name2 are String variables or String constants. If the value is Positive, then the String_name2 is alphabetically above the String_name1. If the value is Negative, then the String_name1 is alphabetically above the String_name2. Strcpy() Function The strcpy() function works similar to the String-Assignment Operator. It takes the following form:strcpy(<string_name1>,<string_name2>); Where String_name1 and String_name2 are String variable and String variable /String constants respectively. It assigns the contents of String_name2 into the String_name1. The size of String_name1 (to which String_name2 is copied) is large enough to hold the final string. Strlen() Function The strlen() function counts and returns the number of characters in a string. It takes the following form:Int num = strlen(<string_name>); Where num is an integer variable which receives the value of the length of the string. The String_name can be a String variable or String constant. The counting ends on encountering the first null character. NOTE:Some important aspects regarding the application of strings/char. arrays is as follows:y Manipulating strings using pointers. y Using strings as function parameters.

CHAPTER ~ USER DEFINED FUNCTIONS ELEMENTS OF USER-DEFINED FUNCTION In order to make use of a user-defined function, three elements need to be established beforehand which are related to any user-defined function. They are as follows:Function Definition. Function Call. Function Declaration. The Function Definition is an independent program that is specially written to implement the requirements of a function. In order to use this function, we need to invoke it at a required place in the program. This action is also referred as Function Call. The function that calls a function is referred to as the Calling Function. The calling function should declare any function that is to be used later in the program. This is known as the Function Declaration or Function Prototype. FUNCTION DEFINITION A Function Definition, also known as Function Implementation shall include the following elements: Function Name.  Function Type.  List of parameters.  Local variable Declaration.  Function Statements.  Return Statement. All these elements can be grouped into two parts: Function Header ( First Three Elements ).  Function Body ( Last Three Elements). The General Format of a Function Definition is as follows: <Function_Return_Type> <Function_Name>(<Parameter_List>) { Local Variable Declaration; Executable Statement_1; Executable Statement_2; .. .. Return Statement; } The First line <Function_Return_Type> <Function_Name>(<Parameter_List>) is known as Function Header and the statements within the opening and closing braces constitute the Function Body, which is a compound statement.

FUNCTION HEADER The function header consists of three parts: the function type (also known as return type), the function name and the formal parameter list. No semicolon is needed to execute the end of function header.  Function_Return_Type & Function_Name The function type specifies the type of value (ex. int, float, char) that the function is expected to return to the program calling the function. If the return type is not explicitly specified, It is assumed by default to be of int type. If the function is not required to return any value, then the return type is specified as Void. The function name is any valid C identifier and should follow the rules of variable name.  Parameter_List The parameter list declares the variables that will receive the data sent by the calling program. They serve as input data to the function to carry out a specified task. As they represent actual input values, they are also referred as Formal Parameters. These parameters can also be used to send values to the calling program. These parameters are also known as Arguments. The parameter list contains declaration of variables separated by commas and surrounded by parentheses. A function need not always receive values from the calling function and have a void parameter list. FUNCTION BODY The function body contains the declarations and the statements necessary for performing the required task. The body enclosed in braces, contains three parts given as follows:-

 Local declarations that specify the variables needed by the function.  Function statements that perform the task of the function.  A return statement that returns the value evaluated by the function.
NOTE:(a) When a function reaches a return statement, the control is transferred back to the calling function/program. In absence of a return statement, the closing brace acts as a return type. (b) A local variable is a variable that is defined inside a function and used without having any role in the communication between the functions. The scope of a variable is local to a block/function only in which has been declared.

RETURN VALUES & ITS TYPES If any value is sent back to the calling function, it is done through only by the return statement. The called function can return only one value per call. The return statement can take one of the following forms:return; OR return(expression); The first form doesnt return any value but only transfers the control from the called function to the calling function. A function can have more than one return value executed based on certain conditions. When a function returns a value, it is automatically cast to the function type whatever the value it may be. FUNCTION CALL A function can be called using the function name followed by a list of actual parameters (arguments) enclosed within the parenthesis. When the compiler encounters a function call, the control is transferred to the called function. The values sent are assigned to the parameters in the function definition which are of local scope to the called function. The called function is then executed line by

line and a value returned when the return statement is encountered. A function call is a postfix expression. NOTE:(a) If the Actual parameters are more than the Formal parameters, the extra actual arguments will be discarded. (b) If the Actual parameters are less than the Formal parameters, the unmatched Formal arguments will be initialized to Garbage Value. FUNCTION DECLARATION Like variables, all functions in a C program must be declared before being invoked. A Function Declaration consists of four parts. They are as follows: Function Type.  Function Name.  Parameter List.  Terminating Semicolon. The General Format of a Function Declaration is as follows: <Function Type> <Function Name> (Parameter List);

CHAPTER ~ STRUCTURE AND UNIONS In Real-life scenario, the data that needs to be resolved is more complex and varied than the fundamental facilities provided in C language. To handle this, C language supports a constructed data type known as Structures, a mechanism for packing data of different datatypes. A structure is a convenient tool for handling a group of logically related data items. STRUCTURE DEFINITION The General Format of a Structure Definition is as follows: struct <structure_tag_name> { <datatype 1> <variable 1>; <datatype 2> <variable 2>; . ; . ; <datatype N> <variable N>; }; While a structure is defined, following points should be taken care of: The structure template should be terminated with a semicolon. In spite of entire definition being considered as a statement, each member is declared independently for its name and type. The <structure_tag_name> can be used to structure variables of its type. STRUCTURE VARIABLE DECLARATION After defining a structure format, a structure variable can be declared similar to declaration of variables of any other datatypes. The structure variable declaration takes the following form: struct <structure_tag_name> <list_of_variables>; The elements included above are: The keyword struct. The structure tag name. List of variable names separated by commas. A terminating semicolon. The members of a structure themselves are not variables. They do not occupy any memory until they are associated with the structure variables. When the compiler comes across a declaration statement, it reserves memory space for the structure variables. It is also allowed to combine both the structure definition and variables declaration in one statement. ACCESSING STRUCTURE MEMBERS The structure members can be accessed in variety of ways. The link between a member and a variable is established using the member operator . which is also known as the Dot Operator or Period Operator. The structure variable name with a period and the member name is used like any ordinary variable. STRUCTURE INITIALIZATION Like any other fundamental datatype, a structure variable can be initialized at compile time. Ex. (1) struct student { int a; Float b; } student1 = { 40, 34.69};

struct student { int a; Float b; }; Struct student student1={ 40, 34.69}; Struct student student2={ 49, 96.43}; (3) struct student { int a; Float b; }; Void main() { Struct student student1={ 40, 34.69}; Struct student student2={ 49, 96.43}; } C language doesnt permit the initialization of individual structure members within the structure template. The initialization must be done only in the declaration of the actual variables. The compile time initialization of the structure variable must have the following elements:

(2)

You might also like