# Unit 3 Decision making, Looping and Arrays

Size: px
Start display at page:

Transcription

1 Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions. This involves a kind of decision making to whether a particular condition has occurred or not and then direct to computer to execute certain statements accordingly. C language has such decision making capabilities by supporting the following statements: If Statement Switch statement These statements are popularly known as decision making statements. Since these statements control the flow of execution, they are also known as control statements. Decision making with if statement The if statement is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used in conjunction with an expression. It takes the following form: if(test expression) It allows the computer to evaluate the expression first then, depending on whether the value of the expression is true (or non-zero) or false (zero), it transfers the control to a particular statement. The if statement may be implemented in different forms depending on the complexity of conditions to be tested. The different forms are: 1. Simple if statement 2. if else statement 3. Nested if else statement Simple if statement The general form of a simple if statement is if(test expression) Statement-block; Statement-x; The statement-block may be a single statement or a group of statements. If the test expression is true, the statement-block will be executed; otherwise the statement-block will be skipped and the execution will jump to the statement-x. Example #include<stdio.h> #include<conio.h> V.P. & R.P.T.P. Science College, V V Nagar Page 1

2 void main() int age; clrscr(); printf( \n Enter your age : ); scanf( %d,&age); if ( age < 0 ) printf ( Negative age given ); if ( age > 0 ) printf ( Your age is %d,age); getch(); Input & Output: Enter your age: 30 Your age is 30 The if else statement The if else statement is an extension of the simple if statement. The general form is if(test expression) True-block statement(s); else False-block statement(s); Statement-x; If the test expression is true, then the true-block statement(s), immediately following the if statements are executed; otherwise, the false-block statement(s) are executed. In either case, either true-block or false-block will be executed, not both. Example: Write a C program to find maximum number from two integer numbers. #include<stdio.h> #include<conio.h> void main() int a, b; clrscr(); printf( Enter first number : ); scanf( %d,&a); printf( Enter second number : ); V.P. & R.P.T.P. Science College, V V Nagar Page 2

3 scanf( %d,&b); if ( a > b ) printf ( \n First number = %d is maximum,a); Else printf ( \n Second number = %d is maximum,b); getch(); Output: Enter first number: 54 Enter second number: 25 First number = 54 is maximum Nested if else statement One if else statement written inside another if else statement is known as nested if else statement. When a series of decisions are involved, we may have to use more than one if else statement in nested form as shown below: if(test condition-1) if(test condition-2) Statement-1; else Statement-2; else Statement-3; Statement-x; If the condition-1 is false, the statement-3 will be executed; otherwise it continues to perform the second test. If the condition-2 is true, the statement-1 will be executed; otherwise the statement-2 will be evaluated and then the control is transferred to the statement-x. Example: Write a C program to find maximum number from three integer numbers. #include<stdio.h> #include<conio.h> void main() int a, b, c; V.P. & R.P.T.P. Science College, V V Nagar Page 3

4 clrscr(); printf( Enter first number : ); scanf( %d,&a); printf( Enter second number : ); scanf( %d,&b); printf( Enter third number : ); scanf( %d,&c); if ( a > b && a > c) printf ( \n First number = %d is maximum,a); else if ( b > c ) printf ( \n Second number = %d is maximum,b); else printf ( \n Third number = %d is maximum,c); getch(); Output: Enter first number: 54 Enter second number: 99 Enter second number: 85 Second number = 99 is maximum Switch statement C has a built-in multi way decision statement known as a switch. The switch statement tests the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated, with that case is executed. The general form of the switch statement is as shown below: switch(expression) case value-1: block-1; break; V.P. & R.P.T.P. Science College, V V Nagar Page 4

5 case value-2: block-2; break; default: default-block; break; Statement-x; The expression is an integer expression or characters. Value-1, value-2 are constants or constant expressions and are known as case labels. Each of these values should be unique within a switch statement. block-1, block-2 are statement list and may contains zero or more statements. There is no need to put braces around these blocks. Note that case labels end with a colon (:). When the switch is executed, the value of the expression is successfully compared against the values value-1, value-2, if a case is found whose value matches with the value of the expression, then the block of statements that follows the case are executed. The break statement at the end of each block signal the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch. The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values. If not present, no action takes place if all matches fail and the control goes to the statement-x. Rules for switch statement The switch expression must be an integral type. Case labels must be constants or constant expressions. Case labels must be unique. No two labels can have the same value. Case labels must end with colon. The default label is optional. If present, it will be executed when the expression does not find a matching case labels. There can be at most one default label. The default may be placed anywhere but usually placed at the end. It is permitted to nest switch statements. Example: #include<stdio.h> #include<conio.h> void main() int a; clrscr(); printf( \n Enter any number : ); scanf( %d, &a); switch(a) V.P. & R.P.T.P. Science College, V V Nagar Page 5

6 case 1 : printf( \n a is 1 ); break; case 2 : printf( \n a is 2 ); break; default : printf( \n Number other than 1 and 2 ); break; getch(); Looping When sequences of statements are executed repeatedly up to some condition then it is known as Program Loop. A loop consists mainly two parts: Body of loop This part contains the sequences of statements, which are to be executed repeatedly. Control statement: This part contains certain conditions, which indicates how many times we have to execute the body of loop. The control statement should be writing carefully otherwise it may possible your loop is executed infinite times which is known as Infinite Loop. Loop contains one or more variable, which control the execution of loop that is known as the Loop Counter. Loop is executed basically in following steps: 1. Setting and initialization of Loop Counter. 2. Test the condition. 3. Executing the body of loop. 4. Incrementing or decrementing the Loop Counter value. In above steps, 2 nd and 3 rd steps may be executed interchangeably that means either we can perform step 2 first or step 3 first. In general there are two types of loops: Entry Controlled loop and Exit controlled loop. Entry-controlled loop In entry-controlled loop we first check the condition and then the body of loop is executed. If at first time condition is false then the body of loop and not executed any time. In C programming language while loop and for loop is example of entry-controlled loop. V.P. & R.P.T.P. Science College, V V Nagar Page 6

7 Exit-controlled loop In exit-controlled loop we first execute the body of the loop and then check the condition and if condition is true then next again executed the body of the loop otherwise not. In exitcontrolled loop it is sure the body of loop is executed once. In C programming language dowhile loop is example of the exit-controlled loop. In C language we have three loops format: while loop for loop do-while loop While Loop while loop is entry-controlled loop, in which first condition is evaluated and if condition is true the body of loop is executed. After executing the body of loop the test condition is again evaluated and if it is true then again body of loop is executed. This process is going to V.P. & R.P.T.P. Science College, V V Nagar Page 7

8 continue up to your test condition is true. If the test condition is false on initial stage then body of loop is never executed. The format of while loop is: while(test condition) body of loop Body of loop has one or more statements. Here the curly bracket is not necessary if body of loop contains only one statement. Consider following example to print 10 numbers start from 1. void main( ) int i; i=1; // Initialization of Loop Counter while(i <= 10) // Test condition printf( I = %d\n,i); // Body of loop i++; // Increment of Loop counter Here above program print the number from First loop counter i is 1. Out test condition is i <=10 that means the value of i is less than or equal to 10. If test condition is true then we are getting the value of i. After printing the i value the value of i is incremented by 1 and again check the test condition. This process is continuing till test condition is true. V.P. & R.P.T.P. Science College, V V Nagar Page 8

9 do while loop As we known that while loop is entry-controlled loop in which test condition is evaluated first and if test condition is true then body of loop is executed. If test condition is false on first time then body of loop is never executed. But sometimes we have such a condition in which it is mandatory to execute the body of loop once whether test condition is true or false. At that time we have to use do-while loop. do-while loop is exit-controlled loop, in which first condition body of loop is executed first and then the test condition is evaluated and if the test condition is true then again body of loop is executed. This process is repeated continuously till test condition is true. Here the body of loop must be executed at least once. The format of do-while loop is: do body of loop while (test condition); Consider one example of do-while loop in which we have to read the data till the number is less than 100 and if number is greater than 100 then we have to terminate the loop. void main( ) int number; do printf( Enter any number : ); scanf( %d, &number); printf( You have Entered %d\n,number) while(number <=100) ; Here first body of loop is executed mean we are reading number and then test condition is evaluated (number is less than or equal to 100) if it is true then again we reading another number otherwise the loop is terminated. V.P. & R.P.T.P. Science College, V V Nagar Page 9

10 for loop for loop is entry-controlled loop, in which first condition is evaluated and if condition is true the body of loop is executed. After executing the body of loop the test condition is again evaluated and if it is true then again body of loop is executed. This process is going to continue up to your test condition is true. If the test condition is false on initial stage then body of loop is never executed. The format of for loop is: for (initialization ; test-condition ; increment-decrement) body of loop In above format the first line contain initialization, test-condition, and increment-decrement portion that means in for loop initialization, condition and increment/decrement is done in only one line. First the loop counter is initialized. After initialization the test condition is evaluated and if it true then body of loop is executed and after execution of body of loop increment or decrement of loop counter is done. Again the test condition is evaluated and it is true then the same process is done again. This is continuing till the test condition is true. The flow chart of the for loop can be drawn in Fig. 5 Consider the example of for loop in which we are determining the factorial of given number. void main( ) int fact=1, n, i; n=5; // Let assume we are determining the factorial of 5 for ( i = 1 ; i < = n ; i++ ) fact = fact * i; printf( The factorial = %d\n, fact); Here the loop counter i is initialized by 1 at first time. Then test condition (The value of i is less than or equal to n ) is evaluated and if it is true then fact is multiplied with i and again assign to fact. After executing the body of loop the value of i is incremented by 1. Next again test condition is evaluated and if it is true then we are proceeding in same way. V.P. & R.P.T.P. Science College, V V Nagar Page 10

11 How for loop differs from other while loop: We have all initialization, condition and increment/decrement statement are only in one line. We can use multiple initialization or multiple increment/decrement statements by using the comma operator. For example, for ( i=1, j=10 ; i<=10 ; i++, j--) We can omit any section of all section. (That means we can omit initialization, condition, or increment/decrement section) For example, for( ; i< =10 ; ) // Initialization and incr/decrement section is omitted. for( ; ; ) // All sections are omitted Here the second loop has omitted all the sections means this loop is infinite loop since there is no any condition to check so it is always true and body of loop is executed continuously. DELAY (NULL) LOOP When we put the semicolon after for loop or while loop statement then body of loop is never executed that mean we are using useless loop. This loop is used to generate the delay and so it is known as delay loop or null loop. for( i =1 ; i<=10000 ; i++) ; Here we have put semicolon after the loop means this loop is executed but without body of loop. V.P. & R.P.T.P. Science College, V V Nagar Page 11

12 NESTED for LOOP When we put loop inside the loop it is known as the nested loop. The nesting is allowed up to 15 levels in ANSI C but many compilers allow more. Consider the example of nested loop. In which the we are using two loops one is outer loop and another is inner loop which is used to read marks and calculate the total of 4 student for( i = 1 ; i<=4 ; i++) t= 0; for(j=1; j< =6 ;j++) printf( Enter the marks for %d subject :,i); scanf( %d, & m); t= t + m; Here the outer loop is having the loop counter i and inner loop has loop counter j. First outer loop is counter i is initialized by 1 and if test condition (i< = 4) is true then next inner loop is executed in which the loop counter j is initialized by 1 and if test condition (j <=6 ) is true then the marks of students are read and total is calculated, then the loop counter j is incremented. This is continuing till the condition for the inner loop is true. When condition for inner loop is false the loop counter i for outer loop is incremented and again same process is done Jumps from loop As we know that loop is executed repeatedly till test condition is true. But sometimes it is necessary to skip the portion of loop or exit from the loop during its execution although test condition is true. For example, we are searching one desired number from list of 100 numbers. We are executing the loop for 100 times but as soon as we are getting our desired number we have to terminate the loop. break statement break statement is used to terminate the loop. When computer execute break statement the control automatically goes to next immediate statement after loop. We cannot transfer the control at any other place. When you put break in nested loop then the only one loop in which break statement is encounter is terminated. while(test condition) if(condition1) break; V.P. & R.P.T.P. Science College, V V Nagar Page 12

13 If the condition1 is true then computer encounter break statement and terminate the loop. void main( ) int n, a[100], i; // Read 100 array elements printf( Enter your number to be search : ); scanf( %d,&n); for( i = 0 ; i< 100 ; i++ ) if(a[i] = = n) printf( Your number is on position %d\n,i + 1); break; getch( ) ; Here when computer encounter your desired number then computer print the position of number and terminate the loop and go to next immediate statement getch( ). continue statement During loop operations, it may be necessary to skip the part of the body of the loop during certain condition. We are using continue statement to skip the portion of loop. For example we are determining the square root of any number and print it. But our condition is that if number is negative then we don t want to determine square root. At that time we can use continue statement to skip the body of loop for negative number. while(test condition) if(condition1) continue; Let s see the example of skipping negative number printing using continue. Here we are reading the number until number is not greater than If the number is negative then we have to not print it otherwise print it. V.P. & R.P.T.P. Science College, V V Nagar Page 13

14 void main( ) int n=1; while(n<=1000) printf( Enter your number : ); scanf( %d, &n); if(n<0) continue; printf( Your number is %d\n, n); Method of Structured Programming Large program are difficult to understand. Hence the large programs are written using three logic structures: 1. Sequence 2. Selection 3. Iteration A sequence construct is a set of instructions serially performed without any looping. The normal flow of control is from top to bottom and from left to right unless there is an iteration construct. Thus the first instruction in the program is executed first, then control passes to the next instruction that sequence. A selection construct involves branching but the branches join before the exit point. The selection is required and the flow of control depends on the selection. For example, if statement, if else statement and switch statement in C language. An iteration construct contains loops in it but has only one exit point. This construct allows repeated execution of a set of codes without repeating codes in the program. It saves the trouble of writing the same codes again and again in the program. For example, while loop, do..while loop and for loop in C language. Array Array is a group of the related data items that share a common name. Individual elements of array are known as the elements of array. The number specified within the square bracket during the declaration of variable is known as the array size. The number given to each element is known as the index or subscript. V.P. & R.P.T.P. Science College, V V Nagar Page 14

15 For example, 20 is the size of the array since it is specified during the declaration of array. int a[20]; In C program the array index start from 0 and goes up to the (size of array 1). For example e.g. a[0] a[1] a[2]. Here the number given from 0, 1, 2, are known as the index One Dimensional Array An array with only one subscript is known as the one-dimensional array of singlesubscripted variable. One-dimensional array store the list of values. For example Here we have the array with the size of 5 that means it can store maximum 5 integer elements that means we can store 5 different integer values inside it. The subscript (index) or array is start with the 0 and up to 4 (size 1). When you declare the array your computer assign continuous memory location to it. In below case a has assigned 5 continuous memory locations. int a[5]; a[0] a[1] a[2] a[3] a[4] You can access each array elements by using its subscript: Suppose you want to access the first element of the array them you can use subscript 0 (a[0]), for second element 1 (a[1]), so on. If you want to read of print array element then you can do by scanf( %d,&a[0]); // read first element scanf( %d,&a[1]); // read second element. printf( %d,a[0]); // print first element printf( %d,a[1]); // print second element.. You can read/print the five elements by using only one scanf/printf statement as under with loop. for(i=0 ; i<5 ; i++) scanf( %d,&a[i]); // read 1 to 5 element as loop will increment printf( %d,a[i]); // print 1 to 5 element as loop will increment V.P. & R.P.T.P. Science College, V V Nagar Page 15

16 You can perform the calculation also by using the subscript. For example, below will determine the total of five elements: total = a[0] + a[1] + a[2] + a[3] + a[4]; If suppose we assign the values 5, 10, 15, 20, and 25 to each array elements respectively. a[0] = 5; a[1] = 10; a[2] = 15; a[3] = 20; a[4] = 25; Then each value is successively stored into the array as under inside memory: a[0] a[1] a[2] a[3] a[4] Then each value is successively stored into the array as under inside memory. If you give the subscript out of the given size then it will not generate any error message but it will give the unexpected output during execution. Declaration of Array Like any other variables, arrays must be declared before they are used. The general format of declaration of array is: datatype arrayname[size]; The datatype indicates whether your array is integer type, float type or any other type. arrayname is a name given to array, and size indicates the no. of elements in your array. For example, here array name is height of float type and it contains different 10 elements. Here the valid subscript range is 0-9. float height[10]; REPRESENTATION OF STRING USING ARRAY OF THE CHARACTER In C program the array of character represents the string. In string the size indicates your string contains how many maximum characters? For example, here we have the array of the character name which is known as string and here its size is 5 and you can store maximum 4 characters in your string because in string the last character is null character \0 or NULL. Suppose we are storing string Well in array name then it is stored as: char name[5]; V.P. & R.P.T.P. Science College, V V Nagar Page 16

17 W name[0] e name[1] l name[2] l name[3] \0 name[4] As shown above all the characters of the string are stored in continuous memory location and the last character of your string is NULL character. Initialization of one dimensional array The general format of the initialization of array is: datatype arrayname[size]=list of values separated by comma; To initialize your array you have to give list of the values separated by comma in curly bracket. For example, int x[5] = 10, 20, 30, 40, 50; The array variable of size 5 x is initialized by five different values 10, 20, 30, 40 and 50 respectively that means X[0] = 10; X[1] = 20; X[2] = 30; X[3] = 40; X[4] = 50; You can initialize the character array or string by two ways. For example, char name[5] = W, e, l, l, \0 ; or char name[5] = Well ; You can initialize the array elements without specifying the size of array. For example, int x[ ] = 10, 20, 30, 40, 50; Here we have given the empty bracket and initialized by five variables that means by default the size is 5. Initialization of array has two drawbacks or limitation: 1. There is no any way to initialize selected array elements. 2. There is no any shortcut method to initialize the large no. of array elements. V.P. & R.P.T.P. Science College, V V Nagar Page 17

18 Two Dimensional Array Two-dimensional array can store the table of values. An array with two subscript is known as the two-dimensional array of double-subscripted variable. The two-dimensional array can be represented by the matrix in mathematics. The matrix elements can be represented by V ij where i value indicates the row number and j value indicated the column number. We can declare the two-dimensional array by using following format: datatype arrayname[row size][column size]; For example, in following declaration we have array x contains 2 rows and 2 columns. The array elements can be represented by following way: int x[2][2]; Column: 1 Column: 2 [0][0] [0][1] [1][0] [1][1] These array elements can be accessed by using the two subscript one for row and another for the column. For example, suppose we have to read the value of the two-dimensional array and print it. void main( ) int a[5][5]; // Declaration of array with the size = 5 int i, j; // read the array elements value for(i = 0 ; i < 5 ; i ++) for(j = 0 ; j < 5 ; j++) scanf( %d,&a[i][j]); // print the array elements value for(i = 0 ; i < 5 ; i ++) for(j = 0 ; j < 5 ; j++) printf( %d,a[i][j]); V.P. & R.P.T.P. Science College, V V Nagar Page 18

19 INITIALIZATION OF TWO-DIMENSIONAL ARRAY We can initialize two-dimensional array elements by following way: datatype arrayname[row size][column size] = list of values of 1 st row, list of values of 2 nd row, ; We can also initialize the array elements continuously as: datatype arrayname[row size][column size] = list of values ; Here the elements are initialized continuously from first row, then second row, and so on. For example int a[2][2] = 0,0, 1,1; OR int a[2][2] = 0,0,1,1; Here the first row elements are initialized by zero and second rows elements are initialized by 1. If you want to initialize the all the array elements with the zero then you can do by: int a[2][2]= 0 ; V.P. & R.P.T.P. Science College, V V Nagar Page 19

Prepared by: Shraddha Modi Introduction In looping, a sequence of statements are executed until some conditions for termination of the loop are satisfied. A program loop consist of two segments Body of

### Fundamentals of Computer Programming Using C

CHARUTAR VIDYA MANDAL S SEMCOM Vallabh Vidyanagar Faculty Name: Ami D. Trivedi Class: FYBCA Subject: US01CBCA01 (Fundamentals of Computer Programming Using C) *UNIT 3 (Structured Programming, Library Functions

### REPETITION CONTROL STRUCTURE LOGO

CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

### SELECTION STATEMENTS:

UNIT-2 STATEMENTS A statement is a part of your program that can be executed. That is, a statement specifies an action. Statements generally contain expressions and end with a semicolon. Statements that

### Unit 5. Decision Making and Looping. School of Science and Technology INTRODUCTION

INTRODUCTION Decision Making and Looping Unit 5 In the previous lessons we have learned about the programming structure, decision making procedure, how to write statements, as well as different types of

### Introduction. C provides two styles of flow control:

Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

### CHAPTER 9 FLOW OF CONTROL

CHAPTER 9 FLOW OF CONTROL FLOW CONTROL In a program statement may be executed sequentially, selectively or iteratively. Every program language provides constructs to support sequence, selection or iteration.

### Computers Programming Course 7. Iulian Năstac

Computers Programming Course 7 Iulian Năstac Recap from previous course Operators in C Programming languages typically support a set of operators, which differ in the calling of syntax and/or the argument

### DELHI PUBLIC SCHOOL TAPI

Loops Chapter-1 There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed

### There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

### PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

PDS Lab Section 16 Autumn-2017 Tutorial 3 C Programming Constructs This flowchart shows how to find the roots of a Quadratic equation Ax 2 +Bx+C = 0 Start Input A,B,C x B 2 4AC False x If 0 True B x 2A

CS6202 - PROGRAMMING & DATA STRUCTURES UNIT I Part - A 1. W hat are Keywords? Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can be used only for their

### Flow Control. CSC215 Lecture

Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

### UIC. C Programming Primer. Bharathidasan University

C Programming Primer UIC C Programming Primer Bharathidasan University Contents Getting Started 02 Basic Concepts. 02 Variables, Data types and Constants...03 Control Statements and Loops 05 Expressions

### n Group of statements that are executed repeatedly while some condition remains true

Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,

### Decision Making and Loops

Decision Making and Loops Goals of this section Continue looking at decision structures - switch control structures -if-else-if control structures Introduce looping -while loop -do-while loop -simple for

### MODULE 2: Branching and Looping

MODULE 2: Branching and Looping I. Statements in C are of following types: 1. Simple statements: Statements that ends with semicolon 2. Compound statements: are also called as block. Statements written

### DECISION CONTROL AND LOOPING STATEMENTS

DECISION CONTROL AND LOOPING STATEMENTS DECISION CONTROL STATEMENTS Decision control statements are used to alter the flow of a sequence of instructions. These statements help to jump from one part of

All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

### Dept. of CSE, IIT KGP

Control Flow: Looping CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of Repeated Execution Loop: Group of

### Basics of Programming

Unit 2 Basics of Programming Problem Analysis When we are going to develop any solution to the problem, we must fully understand the nature of the problem and what we want the program to do. Without the

### INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

INTRODUCTION TO C++ PROGRAM CONTROL Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Repetition Statement for while do.. while break and continue

### Lecture 6. Statements

Lecture 6 Statements 1 Statements This chapter introduces the various forms of C++ statements for composing programs You will learn about Expressions Composed instructions Decision instructions Loop instructions

### Branching is deciding what actions to take and Looping is deciding how many times to take a certain action.

3.0 Control Statements in C Statements The statements of a C program control the flow of program execution. A statement is a command given to the computer that instructs the computer to take a specific

### Loops / Repetition Statements

Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

### Subject: PIC Chapter 2.

02 Decision making 2.1 Decision making and branching if statement (if, if-, -if ladder, nested if-) Switch case statement, break statement. (14M) 2.2 Decision making and looping while, do, do-while statements

### B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

### Government Polytechnic Muzaffarpur.

Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking

### CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart ANS. Flowchart:- A diagrametic reperesentation of program is known as flowchart Symbols Q-2) Explain basic structure of c language

### Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In

### 3 The L oop Control Structure

3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

### Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

### Module 4: Decision-making and forming loops

1 Module 4: Decision-making and forming loops 1. Introduction 2. Decision making 2.1. Simple if statement 2.2. The if else Statement 2.3. Nested if Statement 3. The switch case 4. Forming loops 4.1. The

### Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #16 Loops: Matrix Using Nested for Loop In this section, we will use the, for loop to code of the matrix problem.

### C library = Header files + Reserved words + main method

DAY 1: What are Libraries and Header files in C. Suppose you need to see an Atlas of a country in your college. What do you need to do? You will first go to the Library of your college and then to the

### C++ Programming Lecture 7 Control Structure I (Repetition) Part I

C++ Programming Lecture 7 Control Structure I (Repetition) Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department while Repetition Structure I Repetition structure Programmer

### MA 511: Computer Programming Lecture 3: Partha Sarathi Mandal

MA 511: Computer Programming Lecture 3: http://www.iitg.ernet.in/psm/indexing_ma511/y10/index.html Partha Sarathi Mandal psm@iitg.ernet.ac.in Dept. of Mathematics, IIT Guwahati Semester 1, 2010-11 Last

### IV Unit Second Part STRUCTURES

STRUCTURES IV Unit Second Part Structure is a very useful derived data type supported in c that allows grouping one or more variables of different data types with a single name. The general syntax of structure

### Loops. CSE 114, Computer Science 1 Stony Brook University

Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

### Multi-Dimensional arrays

Multi-Dimensional arrays An array having more then one dimension is known as multi dimensional arrays. Two dimensional array is also an example of multi dimensional array. One can specify as many dimensions

### Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps 1 True and False in C False is represented by any zero value The int expression having the

### UNIT 3 FUNCTIONS AND ARRAYS

UNIT 3 FUNCTIONS AND ARRAYS Functions Function definitions and Prototypes Calling Functions Accessing functions Passing arguments to a function - Storage Classes Scope rules Arrays Defining an array processing

### An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Data Structures Introduction An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type. Representation of a large number of homogeneous

### Lecture 10. Daily Puzzle

Lecture 10 Daily Puzzle Imagine there is a ditch, 10 feet wide, which is far too wide to jump. Using only eight narrow planks, each no more than 9 feet long, construct a bridge across the ditch. Daily

### Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Decision Making and Branching C language possesses such decision-making capabilities

### Decision making with if Statement : - Control Statements. Introduction: -

Control Statements Introduction: - Any C program if you consider, the set of statements are normally executed sequentially in the order in which they are written, and such programs have sequential structure

### How to declare an array in C?

Introduction An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type. Representation of a large number of homogeneous values.

### Multiple Choice Questions ( 1 mark)

Multiple Choice Questions ( 1 mark) Unit-1 1. is a step by step approach to solve any problem.. a) Process b) Programming Language c) Algorithm d) Compiler 2. The process of walking through a program s

### Decision Making -Branching. Class Incharge: S. Sasirekha

Decision Making -Branching Class Incharge: S. Sasirekha Branching The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the

### A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

A First Book of ANSI C Fourth Edition Chapter 8 Arrays Objectives One-Dimensional Arrays Array Initialization Arrays as Function Arguments Case Study: Computing Averages and Standard Deviations Two-Dimensional

### UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

( Word to PDF Converter - Unregistered ) http://www.word-to-pdf-converter.net FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING INTRODUCTION TO C UNIT IV Overview of C Constants, Variables and Data Types

### C Programming Class I

C Programming Class I Generation of C Language Introduction to C 1. In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) 2. In 1970, Ken Thompson created a language

### ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 08: Control Statements Readings: Chapter 6 Control Statements and Their Types A control

### PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo 1. (a)what is an algorithm? Draw a flowchart to print N terms of Fibonacci

### Loops / Repetition Statements

Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

### Accelerating Information Technology Innovation

Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lección 03 Control Structures Agenda 1. Block Statements 2. Decision Statements 3. Loops 2 What are Control

### Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Code: DC-05 Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100 NOTE: There are 11 Questions in all. Question 1 is compulsory and carries 16 marks. Answer to Q. 1. must be written in the space

### 5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;

### Unit 7. Functions. Need of User Defined Functions

Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

### An array is a collection of similar elements that is all the elements in an array should have same data type. This means that an array can store

An array is a collection of similar elements that is all the elements in an array should have same data type. This means that an array can store either all integers, all floating point numbers, all characters,

### UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

### Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

### MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION

Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate

### MAHARASHTRA STATE BOARD OF TECHNICAL EDUCATION (Autonomous) (ISO/IEC Certified)

Important Instructions to examiners: 1) The answers should be examined by key words and not as word-to-word as given in the model answer scheme. 2) The model answer and the answer written by candidate

### Chapter 5: Control Structures

Chapter 5: Control Structures In this chapter you will learn about: Sequential structure Selection structure if if else switch Repetition Structure while do while for Continue and break statements S1 2017/18

### Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

### Computer Programming & Problem Solving ( CPPS )

Computer Programming & Problem Solving ( CPPS ) Chapter No 3 Sir Syed University of Engineering & Technology Computer Engineering Department University Road, Karachi-75300, PAKISTAN Muzammil Ahmad Khan

### Chapter 2: Functions and Control Structures

Chapter 2: Functions and Control Structures TRUE/FALSE 1. A function definition contains the lines of code that make up a function. T PTS: 1 REF: 75 2. Functions are placed within parentheses that follow

### Chapter 4. Flow of Control

Chapter 4. Flow of Control Byoung-Tak Zhang TA: Hanock Kwak Biointelligence Laboratory School of Computer Science and Engineering Seoul National Univertisy http://bi.snu.ac.kr Sequential flow of control

### Subject: Fundamental of Computer Programming 2068

Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find

### A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

A First Book of ANSI C Fourth Edition Chapter 8 Arrays One-Dimensional Arrays Array Initialization Objectives Arrays as Function Arguments Case Study: Computing Averages and Standard Deviations Two-Dimensional

### C: How to Program. Week /Apr/23

C: How to Program Week 9 2007/Apr/23 1 Review of Chapters 1~5 Chapter 1: Basic Concepts on Computer and Programming Chapter 2: printf and scanf (Relational Operators) keywords Chapter 3: if (if else )

### Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

### Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal

Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

### Lecture 7 Tao Wang 1

Lecture 7 Tao Wang 1 Objectives In this chapter, you will learn about: Interactive loop break and continue do-while for loop Common programming errors Scientists, Third Edition 2 while Loops while statement

### Programming Fundamentals

Programming Fundamentals Programming Fundamentals Instructor : Zuhair Qadir Lecture # 11 30th-November-2013 1 Programming Fundamentals Programming Fundamentals Lecture # 11 2 Switch Control substitute

### Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

Chapter 6 Loops 1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly execute some other statement (the loop body). In C, every loop

### CSCE150A. Introduction. While Loop. Compound Assignment. For Loop. Loop Design. Nested Loops. Do-While Loop. Programming Tips CSCE150A.

Chapter 5 While For 1 / 54 Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - s Stephen Scott (Adapted from Christopher M. Bourke) Fall 2009 While For 2 / 54 5.1 Repetition

### CSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

CSE101-Lec#18 Multidimensional Arrays Application of arrays Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Defining and processing 1D array 2D array Applications of arrays 1-D array A

### Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

### Structured Programming. Dr. Mohamed Khedr Lecture 9

Structured Programming Dr. Mohamed Khedr http://webmail.aast.edu/~khedr 1 Two Types of Loops count controlled loops repeat a specified number of times event-controlled loops some condition within the loop

### Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 5. Repetition in Programs. Notes. Notes. Notes. Lecture 05 - Loops

Computer Science & Engineering 150A Problem Solving Using Computers Lecture 05 - Loops Stephen Scott (Adapted from Christopher M. Bourke) 1 / 1 Fall 2009 cbourke@cse.unl.edu Chapter 5 5.1 Repetition in

### CS1100 Introduction to Programming

Decisions with Variables CS1100 Introduction to Programming Selection Statements Madhu Mutyam Department of Computer Science and Engineering Indian Institute of Technology Madras Course Material SD, SB,

### Programming for Electrical and Computer Engineers. Loops

Programming for Electrical and Computer Engineers Loops Dr. D. J. Jackson Lecture 6-1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly

### Chapter 3 Structured Program Development

1 Chapter 3 Structured Program Development Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 - Structured Program Development Outline 3.1 Introduction

Flow Control Comments Comments: /* This is a comment */ Use them! Comments should explain: special cases the use of functions (parameters, return values, purpose) special tricks or things that are not

### FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING UNIT IV INTRODUCTION TO C

FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING UNIT IV INTRODUCTION TO C Overview of C Constants, Variables and Data Types Operators and Expressions Managing Input and Output operators Decision Making

### What we have learned so far

What we have learned so far Straight forward statements Conditional statements (branching) Repeated statements (loop) Arrays One variable many data Problem: Read 10 numbers from the keyboard and store

### Chapter 3: Arrays and More C Functionality

Chapter 3: Arrays and More C Functionality Objectives: (a) Describe how an array is stored in memory. (b) Define a string, and describe how strings are stored. (c) Describe the implications of reading

### ARRAYS(II Unit Part II)

ARRAYS(II Unit Part II) Array: An array is a collection of two or more adjacent cells of similar type. Each cell in an array is called as array element. Each array should be identified with a meaningful

### CSI33 Data Structures

Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

### CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

### NWEN 241 Systems Programming Exercises (Set 1)

1. A null statement in C programming is valid but also mandatory in some cases, e.g. if (isalpha(c)) /* true = nonzero, false = zero */ ; /* empty is ok, but ; must be there */ else return(printf("you

### ENGR 1181 MATLAB 09: For Loops 2

ENGR 1181 MATLAB 09: For Loops Learning Objectives 1. Use more complex ways of setting the loop index. Construct nested loops in the following situations: a. For use with two dimensional arrays b. For

### STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

### CHAPTER : 9 FLOW OF CONTROL

CHAPTER 9 FLOW OF CONTROL Statements-Statements are the instructions given to the Computer to perform any kind of action. Null Statement-A null statement is useful in those case where syntax of the language

### Lecture 7: General Loops (Chapter 7)

CS 101: Computer Programming and Utilization Jul-Nov 2017 Umesh Bellur (cs101@cse.iitb.ac.in) Lecture 7: General Loops (Chapter 7) The Need for a More General Loop Read marks of students from the keyboard

### ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.