94 Computer Programming Example: scanf(\"%d\", &n); where the variable n has been declared as an integer. The & is mandatory and stands for \"address of\". scanf(\"%d %d\", &a, &b); where a,b are integers. scanf(\"%f %d\", &a, &f); where a is a float and f is an integer The first argument to the scanf() function is a format string which contains FORMAT SPECIFIERS. Always the format string is defined within \" \" (double quotes). The control string consists of individual groups of characters, with one character group for each data input item. In its simplest form, each character group consists of a percent sign (%), followed by a set of conversion characters which indicate the type of the corresponding data item. These can be any of the following: %d stands for integer numbers %c stands for character %e stands for floating-point value with an exponent %f stands for float %i stands for signed decimal integer %u stands for unsigned decimal integer %s stands for string %o stands for octal %x stands for hexadecimal These all % characters are known as Modulus Operator 3.13 Summary Operators form expressions by joining individual constants, variables, array elements. C includes a large number of operators which fall into different categories. They are as follows: CU IDOL SELF LEARNING MATERIAL (SLM)
Operators and Expressions 95 1. Arithmetic operators 2. Assignment operators 3. Relational operators 4. Logical operators 5. Bit-wise operators 6. Conditional operators (ternary operators) 7. Increment/decrement operators 8. Special operators Type Conversion: When variables and constants of different types are combined in an expression then they are converted to same data type. The process of converting one predefined type into another is called type conversion or type casting. Type conversion in C can be classified into the following two types: (a) Implicit Type Conversion (b) Explicit Type Conversion Operators Precedence in C: Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. 3.14 Key Words/Abbreviations Operator: An operator is a symbol that tells the compiler to perform a certain mathematical or logical manipulation. Operand: Operands are the objects that are manipulated and operators are the symbols that represent specific actions. For example, in the expression. 5 + x. x and 5 are operands and + is an operator. All expressions have at least one operand. I/O functions: These functions are used to permit the transfer of information between the computer and the standard input/output device. The basic input/output functions are getchar, putchar, puts, scanf and printf. The first two functions, getchar and putchar, are used to transfer single characters. CU IDOL SELF LEARNING MATERIAL (SLM)
96 Computer Programming 3.15 Learning Activity 1. What do you mean by operators in C? Explain the types of operators in detail. ....................................................................................................................................... ....................................................................................................................................... 2. Write a note on type casting in C. ....................................................................................................................................... ....................................................................................................................................... 3. Write a program in C to swap between two numbers. ....................................................................................................................................... ....................................................................................................................................... 4. Write a program in C to find the area of triangle. ....................................................................................................................................... ....................................................................................................................................... 5. Write a program in C to calculate simple interest. ....................................................................................................................................... ....................................................................................................................................... 3.16 Unit End Questions (MCQ and Descriptive) A. Descriptive Type: Short Answer Type Questions 1. Explain different Arithmetic operators with example of each. 2. Describe the four relational operators included in C. With what type of operands can they be used? What type of expression is obtained? 3. Describe the two logical operators included in C. What is the purpose of each? With what type of operands can they be used? 4. How is the type of an assignment expression determined when the two operands are of different data types? CU IDOL SELF LEARNING MATERIAL (SLM)
Operators and Expressions 97 5. What are unary operators? How many operands are associated with a unary operator? State purpose of each. 6. Describe two different ways to utilize the increment and decrement operators. How do the two methods differ? 7. Explain conditional or ternary operators with suitable example. 8. Explain Bitwise operators and its types and comma operators with suitable example. 9. Describe Precedence and order of evaluation used in C Programming language. 10. Explain Statements and different types of statements in C programming language. 11. Describe Automatic and explicit type conversion with suitable example. 12. Explain Use of Formatted input and output functions with format specifers used. Illustrate with some suitable examples. B. Multiple Choice/Objective Type Questions 1. What is the output of this C code? int main() { int i = -5; int k = i %4; printf(“%d\\n”, k); } (a) Compile time error (b) -1 (c) 1 (d) None 2. What is the value of x in this C code? void main() { int x = 4 *5 / 2 + 9; } CU IDOL SELF LEARNING MATERIAL (SLM)
98 Computer Programming (a) 6.75 (b) 1.85 (c) 19 (d) 3 3. What is the output of this C code? void main() { int k = 8; int x = 0 == 1 && k++; printf(“%d%d\\n”, x, k); } (a) 0 9 (b) 0 8 (c) 1 9 (d) 1 8 4. When double is converted to float, then the value is? (a) Truncated (b) Rounded (c) Depends on the compiler (d) Depends on the standard 5. When do you need to use type-conversions? (a) The value to be stored is beyond the max limit (b) The value to be stored is in a form not supported by that data type (c) To reduce the memory in use, relevant to the value (d) All of the mentioned Answers: 1. (b), 2. (c), 3. (b), 4. (c), 5. (d) 3.17 References 1. http://download.nos.org/cca/cca11.pdf 2. https://www.programtopia.net/c-programming/docs/operators-expressions 3. https://fresh2refresh.com/c-programming/c-operators-expressions/ 4. https://faculty.psau.edu.sa/filedownload/doc-13-pdf- b790198028e7b75cde4173bc1c825c64-original.pdf 5. https://www.tenouk.com/download/pdf/Module3.pdf CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 99 UNIT 4 DECISION AND LOOP CONTROL STRUCTURE Structure: 4.0 Learning Objectives 4.1 Introduction 4.2 Control Statements for Decision Making 4.3 Branching: If Statement 4.4 Looping: While Loop 4.5 Jump Statements 4.6 Summary 4.7 Key Words/Abbreviations 4.8 Learning Activity 4.9 Unit End Questions (MCQ and Descriptive) 4.10 References 4.0 Learning Objectives After studying this unit, you will be able to: Define the concept of decision making Apply various decision making statements Differentiate between if-else and switch statement Explain the necessity of loop Describe various looping statements Analyze the nesting of loops Demonstrate the use of break and continue statements Elaborate go to statement CU IDOL SELF LEARNING MATERIAL (SLM)
100 Computer Programming 4.1 Introduction In any programming language, there is a need to perform different tasks based on the condition. For example, consider an online website, when you enter wrong id or password it displays error page and when you enter correct credentials then it displays welcome page. So there must be a logic in place that checks the condition (id and password) and if the condition returns true it performs a task (displaying welcome page) else it performs a different task (displaying error page). Using decision control statements we can control the flow of program in such a way so that it executes certain statements based on the outcome of a condition (i.e., true or false). 4.2 Control Statements for Decision Making Decision making is about selecting one option from the available options, which are more than one. While writing programs this concept is always going to play an important role. We have to provide the capabilities to program so that it can take decisions on its own, depending upon the various possible inputs from the user. Decision making is about deciding the order of execution of statements based on certain conditions or repeating a group of statements until certain specified conditions are met. We can perform different — different tasks based on the conditions. C language handles decision making in various ways as follows. Sequential Sequential means the program flow moves from one statement to the next, and then to the later and then to the one after and so on. It is the simplest form of structures, and it is not likely to be sequential structuring when developing complex programs. Selection (Decision) Selection structures make decisions and perform commands according to the desicion making. Selection structures involve “if statements” which are statements like “if this, then do that” and “if not this, then do that”. With “if statements”, we can also include “nested if statements”, which are “if statements” inside other “if statements”. Another form of selection structures is called a “switch statement”, CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 101 which is very powerful for certain situations, but not for others. “Switch statements” focus on the value of a particular variable and perform different “cases” accordingly. Repetition (Loops) Repetition structures are used when something needs to be repeated a certain number of times through the use of “loops”. A loop is simply a statement that completes iterations or cycles until a certain value is reached and then execution moves to the next executable statement. For instance, if you were to ask the user to enter ten values; to find the average of the numbers, you could write a loop that would continue letting the user enter numbers until ten numbers had been entered. 4.3 Branching: If Statement One-way decisions are handled with an \"if statement\" and they either do some particular thing or do nothing at all. The decision is based on a logical expression, which either evaluates to true or false. If the logical expression is evaluated to true, then the corresponding statement is executed; if the logical expression evaluates to false, control goes to the next executable statement. The form of a one-way decision statement is as follows: if ( test expression) { stmtT; //Block of code execute when condition is true } The stmtT can be a simple or compound statement. Simple involves 1 single statement. Compound involves 1 or more statements enclosed with curly braces { }. A compound statement is called a block statement. The if statement evaluates the test expression inside parenthesis. If test expression is evaluated to true (nonzero), statements inside the body of if is executed. If test expression is evaluated to false (0), statements inside the body of if is skipped. CU IDOL SELF LEARNING MATERIAL (SLM)
102 Computer Programming Flowchart of if Statement Fig. 4.1: Flowchart of if Statement Example: #include<stdio.h> void main() { int x =20; int y =22; if(x<y) { printf(\"Variable x is less than y\"); } getch( ); } CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 103 Output: Variable x is less than y 4.3.1 If-Else Statement Multi-way decision statements involve using \"if/else if\" statements, \"nested ifs\", or \"switch\" statements. They are all used to evaluate a logical expression that could have several possible values. \"if/else if\" statements are often used to choose between ranges of values. The if...else statement executes some code if the test expression is true (nonzero) and some other code if the test expression is false (0). Syntax of if...else if (testExpression) { // codes inside the body of if } else { // codes inside the body of else } If test expression is true, codes inside the body of if statement is executed and, codes inside the body of else statement is skipped. If test expression is false, codes inside the body of else statement is executed and, codes inside the body of if statement is skipped. CU IDOL SELF LEARNING MATERIAL (SLM)
104 Computer Programming Flowchart of if...else statement Test False expression Body of else True Body of if Statement just below if.. else Fig. 4.2: Flowchart of if... Else Statement Example : C if...else statement // Program to check whether an integer entered by the user is odd or even #include <stdio.h> void main() { int number; printf(\"Enter an integer: \"); scanf(\"%d\",&number); // True if remainder is 0 if( number%2 == 0 ) printf(\"%d is an even integer.\",number); else printf(\"%d is an odd integer.\",number); return 0; } CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 105 Output: Enter an integer: 7 7 is an odd integer. When user enters 7, the test expression ( number%2 == 0 ) is evaluated to false. Hence, the statement inside the body of else statement printf(\"%d is an odd integer\"); is executed and the statement inside the body of if is skipped. 4.3.2 Nested if...else statement (if...elseif....else Statement) The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The nested if...else statement allows you to check for multiple test expressions and execute different codes for more than two conditions. Syntax of nested if...else statement. if (testExpression1) { // statements to be executed if testExpression1 is true } else if(testExpression2) { // statements to be executed if testExpression1 is false and testExpression2 is true } else if (testExpression 3) { // statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true } . . else { CU IDOL SELF LEARNING MATERIAL (SLM)
106 Computer Programming // statements to be executed if all test expressions are false } The form of a multi-way decision using \"nested ifs\" is as follows: if (conditionA) { if (conditionB) stmtBT; else stmtBF; } else stmtAF; If conditionA is evaluated to true, then execution moves into the nested if and evaluates conditionB. If conditionA is evaluated to false, then stmtAF is executed. Example: C Nested if...else statement // Program to relate two integers using =, > or < #include <stdio.h> void main() { int number1, number2; printf(\"Enter two integers: \"); scanf(\"%d %d\", &number1, &number2); //checks if two integers are equal. if(number1 == number2) { CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 107 printf(\"Result: %d = %d\",number1,number2); } //checks if number1 is greater than number2. else if (number1 > number2) { printf(\"Result: %d > %d\", number1, number2); } // if both test expression is false else { printf(\"Result: %d < %d\",number1, number2); } getch( ); } Output: Enter two integers: 12 23 Result: 12 < 23 4.3.3 Switch Statement A switch statement is yet another option for writing code that deals with multi-way decisions. Switch case statementsare mostly used when we have a number of options (or choices) and we may need to perform a different task for each choice. The following are the feature of a switch construct: 1. Expression must be an integer expression. 2. Each case is labelled by an integer or character constant. 3. Cases and defaults may occur in any order. CU IDOL SELF LEARNING MATERIAL (SLM)
108 Computer Programming 4. Cases must all be different. 5. After the code for one case is done, execution falls through to the next, unless you take explicit action to escape. 6. The break statement causes an immediate exit from the switch. 7. Falling through cases is a mixed blessing. 8. Positive side is to have one code for multiple cases, redundancy avoided. 9. Negative side is to put break after each case. Switch statements offer an alternative to an \"else if\" structure which has multiple possible paths based on the value of a single expression. A revised form for a switch statement is as follows: switch (int expression) { case label - 1: stmt-list-1; break; case label - 2: stmt-list-2; break; case label - 3: stmt-list-3; break; . . . case label - n: stmt-list-n; break; CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 109 default: stmt-list; } During execution, the expression is evaluated. If the value of the expression matches label-1, then stmt-list-1 will be executed. If not, execution will move on to check label-2 and so on. If no labels match the expression, default will be executed. Inside each case and at the end of every statement list (except default) there must be a break statement, which terminates the innermost enclosing switch or loop statement. Here are some final notes about switch statements: the expression being tested must result in an integral value (int or single char), case labels must be integral constants (either literals or named constants), each label within a switch should be unique, and each stmt-list may contain 0 or more statements which do not need to enclosed with curly braces { }. switch_expression Equal Case 1 Case 1 code block Not Equal Equal Case 2 Not Equal Case 2 code block Case 3 Equal Not Equal Case 3 code block Default Default code block Next Statement after Switch Fig. 4.3: Flowchart of Switch Statement CU IDOL SELF LEARNING MATERIAL (SLM)
110 Computer Programming Example: void main() { int i=2; switch(i) { case1: printf(\"Case1 \"); break; case2: printf(\"Case2 \"); break; case3: printf(\"Case3 \"); break; case4: printf(\"Case4 \"); break; default: printf(\"Default \"); } getch( ); } Output: Case2 CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 111 4.4 Looping: While Loop Loops are used in programming to repeat a specific block of code A loop is a statement of code that does something over and over again until the logical expression of the loop evaluates to false. It is simply a way of repeating code over and over again until some particular value is reached. It can also be an effective way of making sure the user is inputting the correct type of input (data validation). The while loop is generally used for performing the same task, a fixed number of times. Syntax of while loop: while(test expression) { // C- statements, which requires repetition. // Increment (++) or Decrement (--) Operation. } The while loop evaluates the test expression. If the test expression is true (nonzero), codes inside the body of while loop is evaluated. The test expression is evaluated again. The process goes on until the test expression is false. When the test expression is false, the while loop is terminated Flowchart of while loop Fig. 4.4: Flowchart of While Loop CU IDOL SELF LEARNING MATERIAL (SLM)
112 Computer Programming Example: #include<stdio.h> #include<conio.h> void main() { int count=1; while(count <=5) { printf(\"%d \", count); count++; } getch(); } Output: 12345 Step 1: First counter variable count has initialized with value 1 and then it has been tested for the condition. Step 2: If condition holds true then the body of the while loop gets executed otherwise, control comes out of the loop. Step 3: Count value was incremented using ++ operator, then it has been tested again for the loop condition. It keeps happening until the condition returns to false. 4.4.1 Do.... While Loops A do while loop is another type of repetition statement. It is exactly the same as the while loop, except it does something and then evaluates the logical expression of the loop to determine what happens next. Normally with a while loop, a part of the logical expression in the loop must be initialized before execution of the loop. CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 113 A do while loop statements will be performed and then checks the test expression of the loop. do { // codes or statements } while (testExpression); The code block (loop body) inside the braces is executed once. Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This process goes on until the test expression is evaluated to 0 (false). When the test expression is false (nonzero), the do...while loop is terminated. The statement in the loop may be single or complex. Complex statements must be enclosed with curly braces { }. Let's look at a couple of examples of do while loops. Body of Loop true Test expression false Statement just below Loop Example: Fig. 4.5: Flowchart of do... While Loop Program to print first ten multiple of 5. #include<stdio.h> #include<conio.h> void main() CU IDOL SELF LEARNING MATERIAL (SLM)
114 Computer Programming { int a;i; a=5; i=1; do { printf(\"%d\\t\",a*i); i++; } while (i <= 10); getch(); } Output: 5 10 15 20 25 30 35 40 45 50 4.4.2 For Loop A for loop is another way to perform something that needs to be repeated in C++ (repetition). Most programmers like to use for loops because the code can be written in a more compact manner compared to the same loop written with a while or do while loop. A for loop is generally used when you know exactly how many times a section of code needs to be repeated. The general form of a for loop is as follows: for (expression1; expression2; expression3) stmt(s); where stmt(s) is a single or compound statement. This is one of the most frequently used loops in C programming. CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 115 The syntax of for loop looks like this – for (initialization; condition test; control flow) { //Code - C statements needs to be repeated } The control flow can be increment or decrement value of variable depending on requirements. Expression1 is used to initialize the loop; expression2 is used to determine whether or not the loop will continue; expression3 is evaluated at the end of each iteration or cycle. Note 1: Expression2 is tested before the stmt and expression3 is executed; it is possible that the body of the loop is never executed or tested. Note 2: Any or all of the 3 expressions in a for loop can be omitted, but the 2 semi-colons must remain. Like for( ; ; ) If expression1 is omitted, there is no initialization done in the loop, but you might not need any initialization for your program. Like : i=1; for ( ; i<=10;i++) If expression2 is omitted, there is no test section so you will essentially have an infinite loop. for(i=1; ; i++) If expression3 is omitted, there is no update as part of the for statement, but the update could be done as part of the statement in the body of the loop. for(i=1;i<=10; ) { printf(\"%d\",i); i++; } CU IDOL SELF LEARNING MATERIAL (SLM)
116 Computer Programming The for loop is commonly used when the number of iterations is known. In general, a for loop can be written as an equivalent to a while loop and vice versa. for (expression1; expression2; expression3) statement; is equivalent to... expression1; while (expression2) { Statements; expression3; } For Loop Flow Diagram Initialization For loop False condition True For loop code block Increment/Update Statements Statement after for loop code block Fig. 4.6: Flowchart of For Loop Example: … int i; for(i=1; i<=4; i++) CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 117 { printf(\"hello, World\"); } … Output: hello,World hello,World hello,World hello, World Step 1: First the counter variable gets initialized; here variable is I, which has been assigned by value 1. Step 2: Then variable has been tested for a given condition, if the condition results in true then C statements enclosed in loop body get executed by compiler, otherwise control skips the loop and continues with the next statements following loop. Step 3: After successful execution of loop's body, the counter variable is incremented or decremented, depending on the operation (++ or -). Various forms of for LOOP Here we use variable num in all the below examples: 1. Here instead of num++, We can usenum=num+1, which is the same as num++. for(num=10;num<20;num=num+1) 2. Initialization part can be skipped from loop as shown below, the counter variable is declared before the loop itself. int num=10; for(;num<20;num++) Must Note: Although we can skip init part but semicolon (;) before condition is must, without which you will get compilation error. CU IDOL SELF LEARNING MATERIAL (SLM)
118 Computer Programming 3. Like initialization, you can also skip the increment part as we did below. In this case semicolon (;) is must, after condition logic. The increment part is being done in for loop body itself. for(num=10;num<20;) { //Code num++; } 4. Below case is also possible, increment in body and init during declaration of counter variable. int num=10; for(;num<20;) { //Statements num++; } 5. Counter can be decremented also. In the below example the variable gets decremented each time the loop runs until the condition num>10 becomes false. for(num=20;num>10;num--) 4.4.3 Nested Loops Nested loops or nesting of loop is placing one loop into another loop to execute a program based on multiple conditions and checks. Here we have an example of nesting of for loop, likewise you can use nesting of various loops such as while, while do or for. Basic syntax is for nesting for loop is, for(initialization; condition; control flow) { CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 119 for(initialization; condition; control flow) { statement ; } } Example: Program to print half Pyramid of numbers #include<stdio.h> #include<conio.h> void main( ) { int i,j; for(i=1;i<5;i++) { printf(\"\\n\"); for(j=i;j>0;j--) { printf(\"%d\",j); } } getch(); } Output: 1 21 321 4321 54321 CU IDOL SELF LEARNING MATERIAL (SLM)
120 Computer Programming 4.4.4 Infinite Loops Infinite loop is a loop that never stops until you press ctrl-break on your keyboard. In order to avoid infinite loops, you need a statement(s) inside the body of the loop that changes some part of the logical expression. Example 1: #include<stdio.h> #include<conio.h> int main() { int a=6; while(a>=5) { printf(\"%d\",a); a++; } return0; } Infinite loop: a will always have value >=5 so the loop would never end. Example 2: #include<stdio.h> int main() { int x=5; while(x<=10) { printf(\"%d\",x); CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 121 x--; } return0; } Infinite loop: x value will keep decreasing because of - operator, hence it will always be <= 10. 4.5 Jump Statements It is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression. In such cases, Jumping statement break and continue are used. 4.5.1 Break Statements The break statement terminates the loop (for, while and do...while loop) immediately when it is encountered. The break statement is used with decision making statement such as if...else. Break statements are useful when you want your program-flow to come out of the switch body. Whenever a break statement is encountered in the switch body, the execution flow would directly come out of the switch. Syntax of break statement break; CU IDOL SELF LEARNING MATERIAL (SLM)
122 Computer Programming Flowchart of break statement Fig. 4.7: Flowchart of Break Statements Working of break statement: while (test Expression) { // codes If (condition for break) { break; } // codes } for (init, condition, update) CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 123 { // codes if (condition for break) { break; } // codes } You can also use characters in switch case. For example: void main() { char ch='b'; switch(ch) { case'd': printf(\"CaseD \"); break; case'b': printf(\"CaseB\"); break; case'c': printf(\"CaseC\"); break; case'z': printf(\"CaseZ \"); break; CU IDOL SELF LEARNING MATERIAL (SLM)
124 Computer Programming default: printf(\"Default \"); } getch( ); } Output: CaseB In addition to this, the break statement can also be used to terminate loops or to exit from a switch. It can be used within a while a do — while, a for or a switch statement. while(condition check) { statement-1; statement-2; if(some condition) { break; } statement-3; statement-4; } Jumps out of the loop, no matter how many cycles are left, loop is exited 4.5.2 Continue and goto Statements Continue Statement The continue statement skips some statements inside the loop. The continue statement is used with decision making statement such as if...else CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 125 Syntax of continue Statement continue; Flowchart of Continue Statement Fig. 4.8: Flowchart of Continue and goto statements Continue statement works following way: while (test Expression) { // codes If (condition for continue) { continue; } // codes } CU IDOL SELF LEARNING MATERIAL (SLM)
126 Computer Programming for (init, condition, update) { // codes if (condition for continue) { continue; } // codes } The continue statement can be used in for loop The continue allows you to continue the execution of a for or while loop from the beginning, making it possible to skip the rest of the statement in the loop after the continue statement. Example: #include <stdio.h> void main( ) { static int marks[5] = {90,80,76,89, -90}; int i, total = 0; for(i=0; i<5; i++) { if(marks[i] <0) { ptrint(\"negative marks not added \\n\"); continue; } total += marks[i] } CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 127 printf(\"total marks = %d \\n\", total); getch( ); } Goto Statement: A goto statement in C programming provides an unconditional jump from the 'goto' to a labelled statement in the same function. Syntax The syntax for a goto statement in C is as follows ? goto label; ... .. ... ... .. ... ... .. ... label: statement; Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement. The label is an identifier. When goto statement is encountered, control of the program jumps to label: and starts executing the code. Flow Diagram: label 1 statement 2 label 2 statement 2 go to label 3 statement 2 label 3 Fig. 4.9: Flowchart of goto Statement CU IDOL SELF LEARNING MATERIAL (SLM)
128 Computer Programming Example #include <stdio.h> void main () { /* local variable definition */ int a = 10; /* do loop execution */ LOOP: do { if( a == 15) { /* skip the iteration */ a = a + 1; goto LOOP; } printf(\"value of a: %d\\n\", a); a++; } while( a < 20 ); getch( ); } When the above code is compiled and executed, it produces the following result ? value of a: 10 value of a: 11 value of a: 12 value of a: 13 CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 129 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 4.6 Summary We generally follow a sequence in the program but at times we would just want to execute only selected statements. 1. This type of conditional processing is really useful to the programs. 2. It allows the programmers to build the programs that determine which statements of the code should be executed and which are to be ignored. Conditional statements The conditional statements help to jump from one part of a program to another depending if a particular condition is satisfied or not. The conditional statements are: 1. if statement: It is one of the simplest forms of decision control statements which is frequently used in decision making. 4. Switch case: This case statement is a multi-way decision statement which is a simpler version of the if-else block which evaluates only one variable. Control Structures: A loop is used for executing a block of statements repeatedly until a given condition returns false. 1. For loop 2. While loop 3. do..while loop Syntax of do-while loop CU IDOL SELF LEARNING MATERIAL (SLM)
130 Computer Programming Continue statement: The continue statement is used inside loops. When a continue statement is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration. Goto statement: The goto statement is rarely used because it makes program confusing, less readable and complex. Also, when this is used, the control of the program won’t be easy to trace, hence it makes testing and debugging difficult. 4.7 Key Words/Abbreviations 1. Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using it in a expression. In the Pre-Increment, value is first incremented and then used inside the expression. Syntax: a= ++x; Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets modified before using it in the expression. 2. Post-increment operator: A post-increment operator is used to increment the value of variable after executing expression completely in which post increment is used. In the Post-Increment, value is first used in a expression and then incremented. Syntax: a=x++; Here, suppose the value of ‘x’ is 10 then value of variable ‘b’ will be 10 because old value of ‘x’ is used. 4.8 Learning Activity 1. Write a program in C to whether the no. entered is even or odd. ...................................................................................................................................... ...................................................................................................................................... CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 131 2. Write a program in C to whether the no. entered is prime no. or not. ...................................................................................................................................... ...................................................................................................................................... 3. Write a program in C to display first 10 nos. ...................................................................................................................................... ...................................................................................................................................... 4. Write a program in C to display the following pattern ...................................................................................................................................... ...................................................................................................................................... * ** *** * * ** 4.9 Unit End Questions (MCQ and Descriptive) A. Descriptive Type: Short Answer Type Questions 1. Explain what are the different control structures available in C language. 2. Explain if, if-else and Nested if with syntax and demonstrate through suitable example. 3. What is meant by looping? Describe two different forms of looping. 4. Explain difference between for loop and while loop. 5. How is the execution of a while loop terminated? 6. Explain the for and while loop with continue statement. 7. Explain nesting of for loop with an example. 8. Explain nesting of if-else loop with an example. 9. Explain Infinite loop with an example. 10. Explain use of switch statement. Compare switch statement with if statement and state the advantages of switch statement. CU IDOL SELF LEARNING MATERIAL (SLM)
132 Computer Programming 11. How is break statement used in switch statement? 12. Explain use of continue statement with suitable example. 13. Explain Nested Loops with example. 14. Explain use of infinite loop with example. 15. Explain use of goto statement with suitable example. B. Multiple Choice/Objective Type Questions 1. The continue statement cannot be used with (a) for (b) while (c) do while (d) switch 2. Which keyword can be used for coming out of recursion? (a) return (b) break (c) exit (d) both A and B 3. goto can be used to jump from main to within a function? (a) True (b) False 4. Switch statement accepts. (a) Int (b) char (c) long (d) All of the above 5. Which loop is guaranteed to execute at least one time. (a) for (b) while (c) do while (d) None of the above Answers: 1. (d), 2. (a), 3. (b), 4. (d), 5. (c) CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 133 4.19 References 1. https://www.tutorialride.com/c-programming/decision-control-statements-in-c- programming.htm 2. https://beginnersbook.com/2014/01/c-if-statement/ 3. https://fresh2refresh.com/c-programming/c-decision-control/ 4. http://www.nhcue.edu.tw/~jinnliu/teaching/cs07/6%20Control%20Structures.pdf 5. http://www.nyu.edu/classes/jcf/CSCI-GA.2110-001/slides/session3/ControlStructures- LoopsConditionalsAndCaseStatements.pdf CU IDOL SELF LEARNING MATERIAL (SLM)
134 Computer Programming UNIT 5 ARRAYS Structure: 5.0 Learning Objectives 5.1 Introduction 5.2 One Dimensional Array 5.3 Two Dimensional Arrays 5.4 Summary 5.5 Key Words/Abbreviations 5.6 Learning Activity 5.7 Unit End Questions (MCQ and Descriptive) 5.8 References 5.0 Learning Objectives After studying this unit, you will be able to: Describe the concepts of arrays. Initializing a single dimensional array and accessing its elements with its memory allocation. Declaring and initializing a 2 dimenional array and accessing its elements with its memory allocation. Differentiate between one and two dimensional arrays CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays 135 5.1 Introduction The array is another kind of variable or user defined variable that is used extensively in C. An array is an identifier that refers to a collection of data items that all have the same name hence, Array is a collection of similar types of data items like collection of all integers, collection of all floats, collection of all characters. The individual data items are represented by their corresponding array-elements (index). Suppose that x is a 10-element array. The first element is referred to as x [0], the second as x[1], and so on. The last element will be x [9] Fig. 5.1: Array Structure Each member in the array (i.e., each individual data item) is referred to by specifying the array name followed by one or more subscripts (array index), with each subscript enclosed in square brackets. Each subscript must be expressed as a non-negative integer. In an n-element array, the array elements are: x [0], x [1] , x [2], . . . ,x [n - 1] as illustrated in the following diagram. The first element of the array is referred to using the notation x[0], the second element is referred to using the notation x[1] and so on. A declaration is a statement that provides a data type and an identifier for a variable. An identifier is a program component’s name. 5.2 One Dimensional Array When you declare an array, you declare a array that contains multiple similar type of data items; each data item is one element of the array. Each element has the same data type, and each CU IDOL SELF LEARNING MATERIAL (SLM)
136 Computer Programming element occupies an area in memory next to, or contiguous to, the others. All elements in a array will be stored in a contiguous allocation of a memory. 5.2.1 Array Declaration and Definition of Single Dimensional An array is declared in a similar manner as a variable, only difference being that each array name has to be specified by size. For one dimensional array, this is done by specifying a positive integer expression in square brackets as shown below: data-type array_name[ expression ] where data-type is the data type (int, float, char) of array elements, array_name is the array name and expression is a positive values integer constant that identifies the size of array. For example, int items[40]; the above statement declares an array named items of integer type with a capacity of 40 elements. char street_name[35]; the above example declares a 35-element array named street_name of character type. 5.2.2 Initializing an Array The following snippet places the data into array items of integer type with a capacity of 40 elements for(i=0;i<40;i++) { printf(“Enter the item”); scanf(“%d”, &items[i]); } The above for loop asks the user to enter the item 40 times. In the beginning, i=0 which causes the scanf statement to initialize the array element items [ 0 ] (first element of the array). This process continues till i=39 and that would initialize the last element of array: items [ 39 ]. Note that the scanf function includes an ampersand (&) in front of items[i], since single array element is being entered rather than an entire array. CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays 137 5.2.3 Accessing an Array Element The following snippet allows accessing an array element from array items of integer type with a capacity of 40 elements int value; printf(“\\n Values of array item:\\n “); for(i=0;i<40;i++) { value=items[i]; printf(“\\n %d”, value); } The above for loop extracts the 40 elements stored in array items one at a time in variable value and displays it in a printf() statement. Of course, the value variable can be eliminated and the array element could have been displayed directly in printf() statement as shown below: printf(“\\n %d”, items[i]); In some applications it may be desirable to assign initial values to the elements of an array. This requires that the array either be defined globally, or locally (within the function) as a static array. The following example explains the same: int items[]={1,6,3,9,2,4,8,0}; void main() { int i, value=0; printf(“\\n Values of array item:\\n “); for(i=0;i<8;i++) { value=items[i]; printf(“\\n %d”, value); } } CU IDOL SELF LEARNING MATERIAL (SLM)
138 Computer Programming Note that this version of the program does not require any input data. Execution of this program will generate the following output: Values of array item: 1 6 3 9 2 4 8 0 What Happens in Memory? Consider the array int arr[5]; here 5*2=10 bytes is immediately reserved in memory. Since this array is not initialized, the values present in the memory location would be garbage. This happens because the storage class for the array is auto, if it would have been static then the default initial value would be zero. This is depicted in the following diagram: arr elements: 4587 4125 8954 1478 1258 memory location: 5010 5012 5014 5016 5018 Fig. 5.2: Array in Memory Location after its Definition Remember one thing; all the array elements would always be present in contiguous memory locations. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array; probably on top of other data, or on the program itself. This will lead to unpredictable results and there will be no error message. In some cases the computer may just hang. CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays 139 5.3 Two Dimensional Arrays 5.3.1 Declaring Array Variables The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write something as follows: data-type array_name[expression][expression]; where data-type can be any valid C data type and array_name will be a valid C identifier. A two- dimensional array can be considered as a table which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows: Column 0 Column 1 Column2 Row 1 a[0][0] a[0][1] a[0][2] Row 2 a[1][0] a[1][1] a[1][2] Row 3 a[2][0] a[2][1] a[2][2] Fig. 5.3: Two-dimensional Array Thus, every element in the array a is identified by an element name of the forma [ i ][ j ], where ‘a’ is the name of the array, and ‘i’ and ‘j’ are the subscripts that uniquely identify each element in ‘a’. 5.3.2 Initialization of 2D Array Consider the following snippet to understand two-dimensional array initialization. int items[4][2] = { { 34, 56 }, { 12, 33 }, { 34, 80 }, { 12, 78 } }; The above snippet initializes a 4 by 2 two-dimensional array. the same array may be even initialized in the following manner: int items[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ; CU IDOL SELF LEARNING MATERIAL (SLM)
140 Computer Programming Of course, it is little difficult to understand so most of the programmers use the previous way to initialize the 2D array items. It is important to remember that while initializing a 2-D array it is necessary to mention the second (column) dimension, whereas the first dimension (row) is optional. That means the following declarations are valid int items[4][2] = { 34, 56, 12, 33, 34, 80, 12, 78 } ; int items[][2] = { 34, 56, 12, 33, 34, 80, 12, 78 } ; whereas the following declarations are not valid int items[4][] = { 34, 56, 12, 33, 34, 80, 12, 78 } ; Programmers need to take care of the order in which initial values are assigned to multidimensional array elements. The rule is that the last (rightmost) subscript increases most rapidly, and the first (leftmost) subscript increases least rapidly. Thus, the elements of a two- dimensional array will be assigned by rows; i.e., the elements of the first row will be assigned, then the elements of the second row, and so on. Hence the above declaration will have the initial assignment as follows: item[0][0] = 34 item[0][1] = 56 item[1][0] = 12 item[1][1] = 33 item[2][0] = 34 item[2][1] = 80 item[3][0] = 12 item[3][1] = 78 Fig. 5.4: Contents of the Array Items Observe that the first subscript ranges from 0 to 2, while the second one ranges from 0 to 3. The natural order in which the initial values are assigned can be altered by forming groups of initial values enclosed within braces (i.e., { ... }). Consider the following example: int items[4][2] = { { 34 }, { 12 }, { 34 }, { 12 } }; CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays 141 What happens in memory for 2D arrays? The arrangement of 2D array elements in rows and columns is only conceptual. The actual memory allocations for 2D array are same as one-dimensional array. i.e. continuous. Consider the array int a[3][2]={ 81, 29, 34, 47, 52, 46 }; Its arrangement is shown in the following diagram: a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[2][1] 52 46 arr elements: 81 29 34 47 memory location: 4781 4783 4785 4787 4789 4791 Fig. 5.5: 2D array in Memory An element of the above array can be accessed using the following code: int value = a[1][0]; printf(\"Value = %d\", a[1][0]); The above snippet would produce the following output: Value = 34 5.4 Summary An array is a group (or collection) of same data types. For example an int array holds the elements of int types while a float array holds the elements of float types. There are 2 types of C arrays. They are, 1. One dimensional array 2. Multi-dimensional array Two dimensional array Three dimensional array Four dimensional array etc… CU IDOL SELF LEARNING MATERIAL (SLM)
142 Computer Programming 5.5 Key Words/Abbreviations Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer – 1. Multi-dimensional arrays: C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. 2. Passing arrays to functions: You can pass to the function a pointer to an array by specifying the array's name without an index. 3. Return array from a function: C allows a function to return an array. 4. Pointer to an array: You can generate a pointer to the first element of an array by simply specifying the array name, without any index. 5.6 Learning Activity 1. Differentiate between one dimensional array and multi-dimensional array. ........................................................................................................................................ ........................................................................................................................................ 2. Write Program in C to take 5 values from the user and store them in an array. ........................................................................................................................................ ........................................................................................................................................ 3. Write Program in C find the average of n numbers using arrays. ........................................................................................................................................ ........................................................................................................................................ 5.7 Unit End Questions (MCQ and Descriptive) A. Descriptive Type: Short Answer Type Questions 1. What is an array? How is it declared? What happens in memory? 2. Explain the process of single dimension array definition and declaration. 3. How can you initialize a single and double dimension array? Explain with an example. CU IDOL SELF LEARNING MATERIAL (SLM)
Arrays 143 4. Differentiate between one dimensional and two dimensional array. 5. What is a two dimensional array? Explain how it can be initialized and how to access elements of an array. 6. Write a program in c to declare a single dimension array of 10 elements, Accept 10 elements from the user and store into array and display sum of all 10 elements of an array, sum of even elements separately, sum of odd elements separately. 7. Write a program in C to declare a single dimension array of 50 elements, Accept 50 elements from the user and store into array and display how many even elements, how many odd elements separately. 8. Write a program in C to declare a single dimension array of 10 elements, Accept 10 elements from the user and store into array and Arrange array elements in ascending order and display sorted order of elements also display minimum and maximum element from array. 9. Write a program in C to declare a matrix of 3×3, Accept all matrix elements from the user and store into matrix elements of two dimensional array and display matrix. B. Multiple Choice/Objective Type Questions 1. Which of these best describes an array? (a) A data structure that shows a hierarchical behaviour (b) Container of objects of similar types (c) Arrays are immutable once initialised (d) Array is not a data structure 2. How do you initialize an array in C? (a) int arr[3] = (1,2,3); (b) int arr(3) = {1,2,3}; (c) int arr[3] = {1,2,3}; (d) int arr(3) = (1,2,3); 3. An array elements are always stored in _______ memory locations. (a) Sequential (b) random (c) Sequential and random (d) None of the above CU IDOL SELF LEARNING MATERIAL (SLM)
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344