Lecture 6. Statements

Size: px
Start display at page:

Download "Lecture 6. Statements"

Transcription

1 Lecture 6 Statements 1

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

3 Statements A statement is a complete direction instructing the computer to carry out some task. Statements represent the lowest-level building blocks of a program. Each statement represents a computational step which has a certain side-effect. (A side-effect can be thought of as a change in the program state, such as the value of a variable changing because of an assignment.) 3

4 Statements Statements enable the program to serve a specific purpose (e.g., sort a list of names). In C++, statements are usually written one per line, although some statements span multiple lines. C++ statements always end with a semicolon (except for preprocessor directives such as #define and #include). 4

5 Statements Examples int a, b=5; // is a declaration statement witch defines // variables a and b; b is initialized with 5 a=b+12 ; // is an assignment statement; it instructs the // computer to add value of variable b and 12 ++a; a + 5; // and to assign the result to the variable a // this has a side-effect // useless statement! Obs. The last example represents a useless statement, because it has no side-effect (a is added to 5 and the result is just discarded). 5

6 Statements and White Space Whitespace (tabs, spaces, and newlines) is generally ignored in statements. The next assignment statement could be written as or as or as a=b+12; a = b + 12 ; a = b + 12; This last variation is perfectly legal but is not recommended. Whitespace can be used to make your programs more readable and easier to maintain. DO use whitespace judiciously to make your code clearer. 6

7 Null Statements The simplest statement is the null statement which consists of just a semicolon: ; // null statement Although the null statement has no side-effect, we will see that it is necessary sometimes. 7

8 Compound Statements A compound statement is also called a block A compound statement is a group of two or more C/C++ statements enclosed in braces. Example for a block: { printf( HELLO WORLD! ); printf( \n ); printf( HELLO WORLD, AGAIN! ); A block can be used anywhere a single statement can be used. The enclosing braces can be positioned in different ways but it's a good idea to place braces on their own lines, making the beginning and end of blocks clearly visible. 8

9 Compound Statements DO put block braces on their own lines. This makes the code easier to read. DO line up block braces so that it's easy to find the beginning and end of a block. DON'T spread a single statement across multiple lines if there's no need to do so. Limit statements to one line if possible. 9

10 Compound Statements Compound statements are useful in two ways: they allow us to put multiple statements in places where otherwise only single statements are allowed they allow us to introduce a new scope in the program A scope is a part of the program text within which a variable remains defined. 10

11 Using compound statements Compound Statements #include <stdio.h> int main(void) { int a, b; { a = 2; b = 5; printf("a = %d\n, a ); printf( b = %d\n, b ); int c ; c = a * b; printf( c = %d\n, c ); printf( c = %d\n, c ); return 0; // Outside the compound statement, these // variables are not defined, so the line 16 will // produces an error message like Undefined // symbol 'c' in function main() 11

12 if The form of an if statement is as follows: if (expression) statement; If expression evaluates to true, statement is executed. If expression evaluates to false, statement is not executed. In either case, execution then passes to whatever code follows the if statement. You could say that execution of statement depends on the result of expression. Note that both the line if (expression) and the line statement; are considered to comprise the complete if statement; they are not separate statements. 12

13 if Flowchart of if statement if (expression) statement; 13

14 if EXAMPLE - Write a C program to print the number entered by user only if the number entered is negative. #include <stdio.h> int main() { int num; printf("enter a number to check.\n"); scanf("%d",&num); if(num<0) /* checking whether number is less than 0 or not. */ { printf("number = %d\n",num); /*If test condition is true, statement above will be executed, otherwise it will not be executed */ printf("the if statement in C programming is easy."); return 0; 14

15 if An if statement can control the execution of multiple statements through the use of a compound statement, or block. Therefore, you could write an if statement as follows: if (expression) { statement_1; statement_2; /* additional code goes here */ statement_n; 15

16 if DO indent statements within a block to make them easier to read. This includes the statements within a block in an if statement. DON'T make the mistake of putting a semicolon at the end of an if statement. An if statement should end with the conditional statement that follows it. In the following, statement1 executes whether or not x equals 2, because each line is evaluated as a separate statement, not together as intended: if( x == 2); /* semicolon does not belong! */ statement1; 16

17 if Using if statements: #include <stdio.h> int main(void) { int x, y; /* Input the two values to be tested */ printf("\ninput an integer value for x: ); scanf( %d, &x); printf("\ninput an integer value for y: ); scanf( %d, &y); /* Test values and print result */ if (x == y) printf("x is equal to y\n ); if (x > y) printf("x is greater than y\n ); if (x < y) printf("x is smaller than y\n ); return 0; 17

18 The else clause if - else A variant form of the if statement allows us to specify two alternative statements: one which is executed if a condition is satisfied and one which is executed if the condition is not satisfied. This is called the if-else statement and has the general form: if (expression) else statement1; statement2; If expression evaluates to true, statement1 is executed. If expression evaluates to false, statement2 is executed. Both statement1 and statement2 can be compound statements or blocks. 18

19 if - else Flowchart of if...else statement 19

20 If - else Using if else statements #include <stdio.h> int main(void) { int x, y; /* Input the two values to be tested */ printf("\ninput an integer value for x: ); scanf( %d, &x); printf("\ninput an integer value for y: ); printf( %d,y); /* Test values and print result */ if (x == y) printf("x is equal to y\n ); else if (x > y) printf("x is greater than y\n"); else printf("x is smaller than y\n ); return 0; 20

21 Using nested if else statements if - else #include <stdio.h> int main(void) { char ch; printf("input a character: ); scanf( %c, &ch); if (ch >= '0' && ch <= '9') printf( The character is a digit ); else if (ch >= 'A' && ch <= 'Z') printf( The character is an upper letter ); else if (ch >= 'a' && ch <= 'z') printf("the character is a lower letter ); else printf("the character is a special character ); return 0; 21

22 switch The switch statement provides a way of choosing between a set of alternatives, based on the value of an expression. The general form of the switch statement is: switch (expression) { case constant_1:... statements; case constant_n: default: statements; statements; First expression (called the switch tag) is evaluated, and the outcome is compared to each of the numeric constants (called case labels), in the order they appear, until a match is found. The statements following the matching case are then executed. Each case may be followed by zero or more statements (not just one statement). Execution continues until either a break statement is encountered or all intervening statements until the end of the switch statement are executed. The final default case is optional and is exercised if none of the earlier cases provide a match. 22

23 switch Flow Chart of switch... case statement 23

24 switch Exemple - Write a program that asks user an arithmetic operator('+','-','*' or '/') and two operands and perform the corresponding calculation on the operands. #include <stdio.h> int main(void) { float x, y, result; char op; printf("input two reals: ); scanf( %f%f, &x, &y); printf("specify the arithmetic operation (+, -, * or x, /): ); fflush(stdin); scanf( %c, &op); switch (op) { case '+': result = x + y; break; case '-': case 'x': case '*': case '/': default: result = x - y; break; result = x * y; break; result = x / y; break; printf("unknown operator: %c\, op); printf("the result of %c operation is: %f, op, result); return 0; 24

25 switch The above statement, for example, may be written as: if (op == '+') result = x + y; else if (op == '-') result = x - y; else if (op == 'x' op == '*') result = x * y; else if (op == '/') result = x / y; else printf("unknown operator: %c \n, op ); 25

26 for The for statement is a C++ programming construct that executes a block of one or more statements a certain number of times. It is sometimes called the for loop because program execution typically loops through the statement more than once. A for statement has the following structure: for ( initial; condition; increment ) statement; initial, condition, and increment are all C++ expressions, and statement is a single or compound C++ statement. When a for statement is encountered during program execution, the following events occur: Note: Note that statement never executes if condition is false the first time it's evaluated. 26

27 for The flowchart to describe the working of for loop in C programming. for ( initial; condition; increment ) statement; #include <stdio.h> int main() { int n, count, sum=0; printf("enter the value of n.\n"); scanf("%d",&n); for(count=1;count<=n;++count) { sum+=count; printf("sum=%d",sum); return 0; 27

28 for You can also "count by" a value other than 1, as in this example: for (count = 0; count < 1000; count += 5) You can omit the initialization expression if the test variable has been initialized previously in your program. (You still must use the semicolon separator as shown, however.) count = 1; for ( ; count < 1000; count++){ The initialization expression doesn't need to be an actual initialization; it can be any valid C++ expression. Whatever it is, it is executed once when the for statement is first reached. For example, the following prints the statement Now begin for...: count = 1; for (printf( Now begin for ); count < 1000; count++) { You can also omit the increment expression, performing the updating in the body of the for statement. Again, the semicolon must be included. To print the numbers from 0 to 99, for example, you could write for (count = 0; count < 100; ) { count++; You can also omit all expressions, as in this example: for ( ; ; ) { 28

29 for The test expression that terminates the loop can be any C++ expression. For example, the following for statement prints only lower letters: char ch; scanf( %c, &ch); for (; ch >= a && ch <= z ; ch++) printf( %c, ch); By using the comma operator, you can make each part of a for statement perform multiple duties. for (i = 0, j = 100; i < j; i++, j--) printf( %d\t%d\n, i, j); 29

30 Nesting for statements for #include <stdio.h> int main(void) { int rows, cols, i, j; printf("input number of rows: ); scanf( %d, &rows); printf("input number of cols: ); scanf( %d, &cols); for ( i = rows; i > 0 ; i--) { for( j = cols; j >0 ; j--) printf(" * ); putchar('\n ); return 0; 30

31 while The while statement, also called the while loop, executes a block of statements as long as a specified condition is true. The while statement has the following form: while (condition) statement; condition is any C++ expression, and statement (called the loop body) is a single or compound C++ statement. When program execution reaches a while statement, the following events occur: 1. The expression condition is evaluated. 2. If condition evaluates to false (that is, zero), the while statement terminates, and execution passes to the first statement following statement. 3. If condition evaluates to true (that is, nonzero), the C statement(s) in statement are executed. 4. Execution returns to step 1. 31

32 while while (condition) statement; //test expression //body of while loop 32

33 while A simple while statement. int main(void) { int count; /* Print the numbers 1 through 20 */ count = 1; while(count <= 20) { printf( %d\n, count); count++; return 0; 33

34 while A while statement is essentially a for statement without the initialization and increment components. Thus, for ( ; condition ; ) is equivalent to while (condition) 34

35 do...while The do...while loop executes a block of statements as long as a specified condition is true. The do...while loop tests the condition at the end of the loop rather than at the beginning, as is done by the for loop and the while loop. The structure of the do...while loop is as follows: do statement while (condition); condition is any C expression, and statement is a single or compound C statement. When program execution reaches a do...while statement, the following events occur: 1. The statements in statement are executed. 2. condition is evaluated. If it's true, execution returns to step 1. If it's false, the loop terminates. 35

36 while do statement while (condition) ; // body of while loop // test expression 36

37 do...while A simple do while statement. int main(void) { int count; /* Print the numbers 1 through 20 */ count = 1; do { printf( %d\n, count); count++; while(count <= 20); return 0; Obs.The statements associated with a do...while loop are always executed at least once. This is because the test condition is evaluated at the end of the loop. 37

38 The continue Statement continue The continue statement terminates the current iteration of a loop and instead jumps to the next iteration. It applies to the loop immediately enclosing the continue statement. It is an error to use the continue statement outside a loop. In while and do loops, the next iteration commences from the loop condition. In a for loop, the next iteration commences from the loop s third expression. 38

39 The continue Statement continue 39

40 The continue Statement continue 40

41 continue For example, a loop which repeatedly reads in a number, processes it but ignores negative numbers, and terminates when the number is zero, may be expressed as: do { scanf( %d, &num); if (num < 0) continue; // process num here... while (num!= 0); This is equivalent to: do { printf( %d, num); if (num >= 0) { // process num here... while (num!= 0); 41

42 continue When the continue statement appears inside nested loops, it applies to the loop immediately enclosing it, and not to the outer loops. For example, in the following set of nested loops, the continue applies to the for loop, and not the while loop: while (more) { for (i = 0; i < n; ++i) { printf(" %d, num); if (num < 0) continue; // causes a jump to: ++i // process num here... //etc... 42

43 continue The continue Statement example Write a C program to find the product of 4 integers entered by a user. If user enters 0 skip it. # include <stdio.h> int main() { int i,num,product; for(i=1,product=1;i<=4;++i) { printf("enter num%d:",i); scanf("%d",&num); if(num==0) continue; / *In this program, when num equals to zero, it skips the statement product*=num and continue the loop. */ product*=num; printf("product=%d",product); return 0; OUTPUT: Enter num1:3 Enter num2:0 Enter num3:-5 Enter num4:2 product=-30 43

44 break A break statement may appear inside a loop (while, do, or for) or a switch statement. It causes a jump out of these constructs, and hence terminates them. Like the continue statement, a break statement only applies to the loop or switch immediately enclosing it. It is an error to use the break statement outside a loop or a switch. 44

45 break A break statement may appear inside a loop (while, do, or for) or a switch statement. It causes a jump out of these constructs, and hence terminates them. 45

46 break For example, suppose we wish to read in a user password, but would like to allow the user a limited number of attempts: for (i = 0; i < attempts; ++i) { printf( "Please enter your password: ); scanf( %s, password); if (Verify(password)) // check password for correctness break; // drop out of the loop printf("incorrect!\n ); 46

47 break Here we have assumed that there is a function called Verify which checks a password and returns true if it is correct and false otherwise. Rewriting the loop without a break statement is always possible by using an additional logical variable (verified) and adding it to the loop condition: verified = 0; for (i = 0; i < attempts &&!verified; ++i) { printf("please enter your password: ); scanf( %s, password); verified = Verify(password)); if (!verified) printf("incorrect!\n ); 47

48 Example of break statement break Write a C program to find average of maximum of n positive numbers entered by user. But, if the input is negative, display the average(excluding the average of negative input) and end the program. # include <stdio.h> int main() { float num,average,sum; int i, n; printf("maximum no. of inputs\n"); scanf("%d",&n); for(i=1;i<=n;++i) { printf("enter n%d: ",i); scanf("%f",&num); if(num<0.0) break; //for loop breaks if num<0.0 sum=sum+num; average=sum/(i-1); printf("average=%.2f",average); return 0; OUTPUT: Maximum no. of inputs 4 Enter n1: 1.5 Enter n2: 12.5 Enter n3: 7.2 Enter n4: -1 Average=

49 return The return statement enables a function to return a value to its caller. It has the general form: return expression; or return (expression); where expression denotes the value returned by the function. The type of this value should match the return type of the function. For a function whose return type is void, expression should be empty: return; The return value of main is what the program returns to the operating system when it completes its execution. 49

Module 4: Decision-making and forming loops

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

More information

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

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

More information

Introduction. C provides two styles of flow control:

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

More information

Introduction to C Programming

Introduction to C Programming 1 2 Introduction to C Programming 2.6 Decision Making: Equality and Relational Operators 2 Executable statements Perform actions (calculations, input/output of data) Perform decisions - May want to print

More information

3 The L oop Control Structure

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

More information

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE Department of Software The University of Babylon LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE By Collage of Information Technology, University of Babylon, Iraq Samaher_hussein@yahoo.com

More information

Flow Control. CSC215 Lecture

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

More information

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

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

More information

Unit 3 Decision making, Looping and Arrays

Unit 3 Decision making, Looping and Arrays 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.

More information

Lecture 3. More About C

Lecture 3. More About C Copyright 1996 David R. Hanson Computer Science 126, Fall 1996 3-1 Lecture 3. More About C Programming languages have their lingo Programming language Types are categories of values int, float, char Constants

More information

REPETITION CONTROL STRUCTURE LOGO

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

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

MODULE 2: Branching and Looping

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

More information

Lecture 5 Tao Wang 1

Lecture 5 Tao Wang 1 Lecture 5 Tao Wang 1 Objectives In this chapter, you will learn about: Selection criteria Relational operators Logical operators The if-else statement Nested if statements C++ for Engineers and Scientists,

More information

DECISION MAKING STATEMENTS

DECISION MAKING STATEMENTS DECISION MAKING STATEMENTS If, else if, switch case These statements allow the execution of selective statements based on certain decision criteria. C language provides the following statements: if statement

More information

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE Department of Software The University of Babylon LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE By Dr. Samaher Hussein Ali Collage of Information Technology, University of Babylon, Iraq Samaher_hussein@yahoo.com

More information

Programming for Electrical and Computer Engineers. Loops

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

More information

Use of scanf. scanf("%d", &number);

Use of scanf. scanf(%d, &number); Use of scanf We have now discussed how to print out formatted information to the screen, but this isn't nearly as useful unless we can read in information from the user. (This is one way we can make a

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

Chapter 2. Introduction to C language. Together Towards A Green Environment

Chapter 2. Introduction to C language. Together Towards A Green Environment Chapter 2 Introduction to C language Aim Aim of this chapter is to provide the fundamentals for basic program construction using C. Objectives To understand the basic information such as keywords, character

More information

COMP 208 Computers in Engineering

COMP 208 Computers in Engineering COMP 208 Computers in Engineering Lecture 14 Jun Wang School of Computer Science McGill University Fall 2007 COMP 208 - Lecture 14 1 Review: basics of C C is case sensitive 2 types of comments: /* */,

More information

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

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

More information

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

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

More information

Dept. of CSE, IIT KGP

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

More information

UIC. C Programming Primer. Bharathidasan University

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

More information

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

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,

More information

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control

ECE15: Introduction to Computer Programming Using the C Language. Lecture Unit 4: Flow of Control ECE15: Introduction to Computer Programming Using the C Language Lecture Unit 4: Flow of Control Outline of this Lecture Examples of Statements in C Conditional Statements The if-else Conditional Statement

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); } C Program Output #include main () { printf ( Hi everyone\n ); Hi everyone #include main () { printf ( Hi everyone\n ); #include and main are Keywords (or Reserved Words) Reserved Words

More information

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

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

More information

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

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

More information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function

More information

Decision Making -Branching. Class Incharge: S. Sasirekha

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

More information

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved. Chapter 4: Expressions Chapter 4 Expressions 1 Chapter 4: Expressions Operators Expressions are built from variables, constants, and operators. C has a rich collection of operators, including arithmetic

More information

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

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

More information

Chapter 8. More Control Statements

Chapter 8. More Control Statements Chapter 8. More Control Statements 8.1 for Statement The for statement allows the programmer to execute a block of code for a specified number of times. The general form of the for statement is: for (initial-statement;

More information

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur

Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur Programming and Data Structure Sudeshna Sarkar Dept. of Computer Science & Engineering. Indian Institute of Technology Kharagpur Shortcuts in Assignment Statements A+=C A=A+C A-=B A=A-B A*=D A=A*D A/=E

More information

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14 Statements Control Flow Statements Based on slides from K. N. King Bryn Mawr College CS246 Programming Paradigm So far, we ve used return statements and expression statements. Most of C s remaining statements

More information

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

COP 2000 Introduction to Computer Programming Mid-Term Exam Review he exam format will be different from the online quizzes. It will be written on the test paper with questions similar to those shown on the following pages. he exam will be closed book, but students can

More information

Chapter 4. Flow of Control

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

More information

Programming Language A

Programming Language A Programming Language A Takako Nemoto (JAIST) 22 October Takako Nemoto (JAIST) 22 October 1 / 28 From Homework 2 Homework 2 1 Write a program calculate something with at least two integer-valued inputs,

More information

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

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

More information

YOLOP Language Reference Manual

YOLOP Language Reference Manual YOLOP Language Reference Manual Sasha McIntosh, Jonathan Liu & Lisa Li sam2270, jl3516 and ll2768 1. Introduction YOLOP (Your Octothorpean Language for Optical Processing) is an image manipulation language

More information

Comments. Comments: /* This is a comment */

Comments. Comments: /* This is a comment */ 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

More information

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

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

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

EC 413 Computer Organization

EC 413 Computer Organization EC 413 Computer Organization C/C++ Language Review Prof. Michel A. Kinsy Programming Languages There are many programming languages available: Pascal, C, C++, Java, Ada, Perl and Python All of these languages

More information

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 5, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language

More information

Problem Solving and 'C' Programming

Problem Solving and 'C' Programming Problem Solving and 'C' Programming Targeted at: Entry Level Trainees Session 05: Selection and Control Structures 2007, Cognizant Technology Solutions. All Rights Reserved. The information contained herein

More information

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting Your factors.c and multtable.c files are due by Wednesday, 11:59 pm, to be submitted on the SoC handin page at http://handin.cs.clemson.edu.

More information

Computers Programming Course 7. Iulian Năstac

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

More information

Chapter 5: Control Structures

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

More information

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering 2013/2014 Programming Fundamentals for Engineers Lab Lab Session # 1 Introduction to C Language ALQUDS University Department of Computer Engineering Objective: Our objective for today s lab session is

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

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 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

More information

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017 Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The

More information

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators Formatted Input and Output The printf function The scanf function Arithmetic and Assignment Operators Simple Assignment Side Effect

More information

CGS 3066: Spring 2015 JavaScript Reference

CGS 3066: Spring 2015 JavaScript Reference CGS 3066: Spring 2015 JavaScript Reference Can also be used as a study guide. Only covers topics discussed in class. 1 Introduction JavaScript is a scripting language produced by Netscape for use within

More information

Fundamentals of Computer Programming Using C

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

More information

1.4 Control Structures: Selection. Department of CSE

1.4 Control Structures: Selection. Department of CSE 1.4 Control Structures: Selection 1 Department of CSE Objectives To understand how decisions are made in a computer To understand the relational operators To understand the logical operators and,or and

More information

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Autumn 2015 Lecture 3, Simple C programming M. Eriksson (with contributions from A. Maki and

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

Structured Programming. Dr. Mohamed Khedr Lecture 9

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

More information

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

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

More information

Chapter 4 C Program Control

Chapter 4 C Program Control 1 Chapter 4 C Program Control Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 4 C Program Control Outline 4.1 Introduction 4.2 The Essentials of Repetition

More information

LECTURE 5 Control Structures Part 2

LECTURE 5 Control Structures Part 2 LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

A control structure refers to the way in which the Programmer specifies the order of executing the statements

A control structure refers to the way in which the Programmer specifies the order of executing the statements Control Structures A control structure refers to the way in which the Programmer specifies the order of executing the statements The following approaches can be chosen depending on the problem statement:

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

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

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++;

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

STUDENT LESSON A12 Iterations

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

More information

Day06 A. Young W. Lim Wed. Young W. Lim Day06 A Wed 1 / 26

Day06 A. Young W. Lim Wed. Young W. Lim Day06 A Wed 1 / 26 Day06 A Young W. Lim 2017-09-20 Wed Young W. Lim Day06 A 2017-09-20 Wed 1 / 26 Outline 1 Based on 2 C Program Control Overview for, while, do... while break and continue Relational and Logical Operators

More information

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University Overview of C, Part 2 CSE 130: Introduction to Programming in C Stony Brook University Integer Arithmetic in C Addition, subtraction, and multiplication work as you would expect Division (/) returns the

More information

Control structures in C. Going beyond sequential

Control structures in C. Going beyond sequential Control structures in C Going beyond sequential Flow of control in a program Start (main) Program starts with the first statement in main Instructions proceed sequentially: One at a time Top to bottom

More information

Functions. (transfer of parameters, returned values, recursion, function pointers).

Functions. (transfer of parameters, returned values, recursion, function pointers). Functions (transfer of parameters, returned values, recursion, function pointers). A function is a named, independent section of C/C++ code that performs a specific task and optionally returns a value

More information

Iosif Ignat, Marius Joldoș Laboratory Guide 4. Statements. STATEMENTS in C

Iosif Ignat, Marius Joldoș Laboratory Guide 4. Statements. STATEMENTS in C STATEMENTS in C 1. Overview The learning objective of this lab is: To understand and proper use statements of C/C++ language, both the simple and structured ones: the expression statement, the empty statement,

More information

Lecture 2: C Programming Basic

Lecture 2: C Programming Basic ECE342 Introduction to Embedded Systems Lecture 2: C Programming Basic Ying Tang Electrical and Computer Engineering Rowan University 1 Facts about C C was developed in 1972 in order to write the UNIX

More information

At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details.

At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details. Objective of this lecture: At the end of this lecture you should be able to have a basic overview of fundamental structures in C and be ready to go into details. Fundamental Programming Structures in C

More information

The following expression causes a divide by zero error:

The following expression causes a divide by zero error: Chapter 2 - Test Questions These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct

More information

DECISION CONTROL AND LOOPING STATEMENTS

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

More information

QUIZ: What value is stored in a after this

QUIZ: What value is stored in a after this QUIZ: What value is stored in a after this statement is executed? Why? a = 23/7; QUIZ evaluates to 16. Lesson 4 Statements, Expressions, Operators Statement = complete instruction that directs the computer

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Tail recursion. Decision. Assignment. Iteration

Tail recursion. Decision. Assignment. Iteration Computer Programming Tail recursion. Decision. Assignment. Iteration Marius Minea marius@cs.upt.ro 7 October 2014 Two ways of writing recursion unsigned max(unsigned a, unsigned b) { return a > b? a :

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

CpSc 1111 Lab 4 Formatting and Flow Control

CpSc 1111 Lab 4 Formatting and Flow Control CpSc 1111 Lab 4 Formatting and Flow Control Overview By the end of the lab, you will be able to: use fscanf() to accept a character input from the user and print out the ASCII decimal, octal, and hexadecimal

More information

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock) C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 By the end of this lecture, you will be able to identify the

More information

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for C/Java Syntax 1 Lecture 02 Summary Keywords Variable Declarations Data Types Operators Statements if, switch, while, do-while, for Functions 2 1 By the end of this lecture, you will be able to identify

More information

C Programming Basics

C Programming Basics CSE 2421: Systems I Low-Level Programming and Computer Organization C Programming Basics Presentation B Read/Study: Reek 3.1-3.4, 4, and 5, Bryant 2.1.1-2.1.5 Gojko Babić 08/29/2017 C Programming Language

More information

C++ PROGRAMMING SKILLS Part 2 Programming Structures

C++ PROGRAMMING SKILLS Part 2 Programming Structures C++ PROGRAMMING SKILLS Part 2 Programming Structures If structure While structure Do While structure Comments, Increment & Decrement operators For statement Break & Continue statements Switch structure

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

UEE1302 (1102) F10: Introduction to Computers and Programming

UEE1302 (1102) F10: Introduction to Computers and Programming Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1302 (1102) F10: Introduction to Computers and Programming Programming Lecture 00 Programming by Example Introduction to C++ Origins,

More information

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

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

More information

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar Examples of Software Programming and Data Structure Lecture 2 Sudeshna Sarkar Read an integer and determine if it is a prime number. A Palindrome recognizer Read in airline route information as a matrix

More information