Lecture 6. Statements

Similar documents
Module 4: Decision-making and forming loops

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

Introduction. C provides two styles of flow control:

Introduction to C Programming

3 The L oop Control Structure

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

Flow Control. CSC215 Lecture

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

Unit 3 Decision making, Looping and Arrays

Lecture 3. More About C

REPETITION CONTROL STRUCTURE LOGO

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

MODULE 2: Branching and Looping

Lecture 5 Tao Wang 1

DECISION MAKING STATEMENTS

LECTURE NOTES ON PROGRAMMING FUNDAMENTAL USING C++ LANGUAGE

Programming for Electrical and Computer Engineers. Loops

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

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

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

COMP 208 Computers in Engineering

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

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

Dept. of CSE, IIT KGP

UIC. C Programming Primer. Bharathidasan University

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

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

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

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

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

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

Programming for Engineers Iteration

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

Decision Making -Branching. Class Incharge: S. Sasirekha

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

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

Chapter 8. More Control Statements

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

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

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Chapter 4. Flow of Control

Programming Language A

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

YOLOP Language Reference Manual

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

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

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

EC 413 Computer Organization

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

Informatica e Sistemi in Tempo Reale

Programming for Engineers Introduction to C

Fundamentals of Programming

Problem Solving and 'C' Programming

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

Computers Programming Course 7. Iulian Năstac

Chapter 5: Control Structures

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

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

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

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

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

CGS 3066: Spring 2015 JavaScript Reference

Fundamentals of Computer Programming Using C

1.4 Control Structures: Selection. Department of CSE

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

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

Structured Programming. Dr. Mohamed Khedr Lecture 9

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

Chapter 4 C Program Control

LECTURE 5 Control Structures Part 2

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

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

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

C: How to Program. Week /Mar/05

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

Full file at

STUDENT LESSON A12 Iterations

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

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

Control structures in C. Going beyond sequential

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

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

Lecture 2: C Programming Basic

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.

The following expression causes a divide by zero error:

DECISION CONTROL AND LOOPING STATEMENTS

QUIZ: What value is stored in a after this

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

Fundamental of Programming (C)

Tail recursion. Decision. Assignment. Iteration

UNIT- 3 Introduction to C++

CpSc 1111 Lab 4 Formatting and Flow Control

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

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

C Programming Basics

C++ PROGRAMMING SKILLS Part 2 Programming Structures

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

UEE1302 (1102) F10: Introduction to Computers and Programming

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

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

Transcription:

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 2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

switch Flow Chart of switch... case statement 23

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

The continue Statement continue 39

The continue Statement continue 40

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

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

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

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

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

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

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

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=7.07 48

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