CS1100 Introduction to Programming

Similar documents
Introduction. C provides two styles of flow control:

MODULE 2: Branching and Looping

Loops / Repetition Statements

CS1100 Introduction to Programming

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Chapter 5: Control Structures

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

Control Structure: Loop

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Dept. of CSE, IIT KGP

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

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

(Refer Slide Time: 00:26)

DECISION CONTROL AND LOOPING STATEMENTS

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

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

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

ECE 2400 Computer Systems Programming Fall 2018 Topic 1: Introduction to C

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

Repetition Structures

Chapter 4. Flow of Control

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

Computer Programming. Decision Making (2) Loops

Flow Control. CSC215 Lecture

Programming for Engineers Iteration

C: How to Program. Week /Mar/05

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

Chapter 8 Statement-Level Control Structure

REPETITION CONTROL STRUCTURE LOGO

3 The L oop Control Structure

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

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

Computers Programming Course 7. Iulian Năstac

Chapter 2 - Introduction to C Programming

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

Add Subtract Multiply Divide

COMP 208 Computers in Engineering

Conditional Statement

V3 1/3/2015. Programming in C. Example 1. Example Ch 05 A 1. What if we want to process three different pairs of integers?

Chapter 13 Control Structures

Introduction to C Programming

Loops / Repetition Statements

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Problem Solving and 'C' Programming

C++ Programming: From Problem Analysis to Program Design, Third Edition

CS 199 Computer Programming. Spring 2018 Lecture 2 Problem Solving

Theory of control structures

Unit 3 Decision making, Looping and Arrays

Functions. Arash Rafiey. September 26, 2017

Looping Subtasks. We will examine some basic algorithms that use the while and if constructs. These subtasks include

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

Chapter 13. Control Structures

Chapter 8. Statement-Level Control Structures

Repetition and Loop Statements Chapter 5

Chapter 3 Structured Program Development

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

M1-R4: Programing and Problem Solving using C (JAN 2019)

Control Statements. If Statement if statement tests a particular condition

Module 4: Decision-making and forming loops

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

UIC. C Programming Primer. Bharathidasan University

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

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Structured Program Development

C++ Final Exam 2017/2018

Syntax of for loop is as follows: for (inite; terme; updatee) { block of statements executed if terme is true;

CS1100 Introduction to Programming

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

11.3 Function Prototypes

Computer Programming I - Unit 5 Lecture page 1 of 14

Decision Making -Branching. Class Incharge: S. Sasirekha

Repetition Structures II

Chapter 3 Problem Solving and the Computer

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

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

LOOPS. Repetition using the while statement

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

LAB 5: REPETITION STRUCTURE(LOOP)

Computer System and programming in C

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Loops (while and for)

C Programming Class I

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

LESSON 6 FLOW OF CONTROL

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

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

DECISION MAKING STATEMENTS

Controls Structure for Repetition

Chapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware

SHARDA UNIVERSITY SCHOOL OF ENGINEERING & TECHNOLOGY Mid Term Examination, (Odd Term, ) SOLUTION

C Program Development and Debugging under Unix SEEM 3460

Chapter 13 Control Structures

CpSc 1111 Lab 4 Formatting and Flow Control

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way

UNIT- 3 Introduction to C++

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

Transcription:

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, PSK, NSN, DK, TAG CS&E, IIT M 1 Need for taking logical decisions during problem solving If (b 2 4ac) is negative, we should report that the quadratic has no real roots The if-else programming construct provides the facility to make logical decisions Syntax: if (condition) else evaluate this part if evaluate this part if 2 Conditions Specified using relational and equality operators Relational: >, <, >=, <= Equality: ==,!= Usage: for a, b values or variables a > b, a < b, a >= b, a <= b, a == b, a!= b A condition is satisfied or, if the relational operator, or equality is satisfied For a = 3 and b = 5: a < b, a <= b, and a!= b are a > b, a >= b, a == b are Completing the program if (discrim < 0) else printf( no real roots, only complex\n ); exit (1); Terminates execution and returns argument (1) root1 = ( coeff2 + sqrt(discrim))/denom; root2 = ( coeff2 sqrt(discrim))/denom; 3 4 Statements Statement: a logical unit of instruction/command Program : declarations and one or more statements assignment statement selection statement repetitive statements function calls etc. All statements are terminated by semicolon ( ; ) Note: In C, semi-colon is a statement terminator rather than a separator! Assignment statement General Form: variable = expression constant ; The declared type of the variable should match the type of the result of expression/constant Multiple Assignment: var1 = var2 = var3 = expression; var1 = (var2 = (var3 = expression)); Assignment operator associates right-to-left. 5 6 1

Compound Statements A group of declarations and statements collected into a single logical unit surrounded by braces a block or a compound statement scope of the variable declarations part of the program where they are applicable the compound statement variables come into existence just after declaration continue to exist till end of the block unrelated to variables of the same name outside the block block-structured fashion 7 An Example int i, j, k; i = 1; j = 2; k = 3; if ( expr ) int i, k; i = j; printf( i = %d\n, i); printf( i = %d\n, i); This i and k and the previously declared i and k are different. Not a good programming style. // output is 2 // output is 1 Note: No semicolon after A compound statement can appear wherever a single statement may appear 8 Selection Statements Three forms: single selection: if ( att < 85 ) grade = W ; double selection: if (marks < 40 ) passed = 0; /* = 0 */ else passed = 1; /* = 1 */ multiple selection: switch statement - to be discussed later no then reserved word If Statement if (<expression>) <stmt1> [ else <stmt2>] Semantics: expression evaluates to stmt1 will be executed expression evaluates to stmt2 will be executed Else part is optional expression is -- stmt1 is executed Otherwise the if statement has no effect optional 9 10 Sequence and Selection Flowcharts Sequence Structure If structure Single Entry Single Exit if - else structure 11 Grading Example Below 50: D; 50 to 59: C ; 60 to 75: B; 75 above: A int marks; char grade; if (marks <= 50) grade = D ; else if (marks <= 59) grade = C ; else if (marks <=75) grade = B ; else grade = A ; Note the semicolon before else! Unless braces are used, an else part goes with the nearest else-less if stmt 12 2

Caution in use of else Switch Statement if ( marks > 40) /* WRONG */ if ( marks > 75 ) printf( you got distinction ); else printf( Sorry you must repeat the course ); if ( marks > 40) /*RIGHT*/ if ( marks > 75 ) printf( you got distinction ); else printf( Sorry you must repeat the course ); A multi-way decision statement Syntax: switch ( expression ) case const-expr : statements; case const-expr : statements; [default: statements;] 13 14 Counting Evens and Odds int num, ecount = 0, ocount = 0; scanf ( %d, &num); while (num >= 0) switch (num%2) case 0: ecount++; break; case 1: ocount++; break; scanf ( %d, &num); Counts the number of even and odd integers in the input. Terminated by giving a negative number printf( Even: %d, Odd: %d\n, ecount, ocount); Fall Through Switch statement: Execution starts at the matching case and falls through the following case statements unless prevented explicitly by break statement Useful for specifying one action for several cases Break statement: Control passes to the first statement after switch A feature requiring exercise of caution 15 16 Switch Statement Flowchart Conditional Operator (?: ) case a case b case a action(s) case b action(s) break break Single Entry Single Exit Syntax (<expression>)? <stmt1>:<stmt2> Closely related to the if else statement if (<expression>) <stmt1> else <stat2> Only ternary operator in C case z case z action(s) break E.g.: (marks < 40)? passed = 0 : passed = 1; printf ( passed = %d\n, (marks<40)?0:1); default action(s) 17 18 3

Programming Problems Write a program to check if a given number is prime. Write a program to count the number of digits in a given number. Your answer should contain two parts, number of digits before and after the decimal. (Can you do this only with assignments to variables, and decisions?) Repetitive Statements A very important type of statement iterating or repeating a set of operations a very common requirement in algorithms C offers three iterative constructs the while construct the for construct the do while construct 19 20 The while Construct General form: while ( <expr> ) <statement> Semantics: repeat: Evaluate the expr If the expr is execute the statement else exit the loop expr expr must be modified in the loop or we have an infinite loop! body 21 Computing 2 n, n>=0, using while Construct Syntax while (condition) statement #include<stdio.h> main( ) int n, counter, value; printf ( Enter value for n: ); scanf ( %d, &n); value = 1; printf ( current value is %d \n, value); 22 Contd counter = 0; while (counter <= n) value = 2 * value; printf ( current value is %d \n, value); counter = counter + 1; Exercise: try this program and identify problems 23 Testing the Program Choose test cases: A few normal values: n = 2, 5, 8, 11 Boundary values: n = 0, 1 Invalid values: n = 1 Hand simulate the execution of the program On paper, draw a box for each variable and fill in the initial values (if any) Simulate exec. of the program one statement at a time For any assignment, write the new value of the variable in the LHS Check if the output is as expected in each test case 24 4

Hand Simulation #include<stdio.h> main( ) int n, counter, value; printf ( Enter value for n: ); scanf ( %d, &n); value = 1; printf ( current value is %d \n, value); n counter value 4 1 Current value is 1 25 Contd counter = 0; while (counter <= n) value = 2 * value; printf ( current value is %d \n, value); counter = counter + 1; condition T F n counter value 4 15 02 34 16 32 12 48 Current value is 1 Current value is 2 Current value is 4 Current value is 8 Current value is 16 Current value is 32 26 More on Loops Loop execution can be controlled in two ways: counter-controlled and sentinel-controlled. Counter loop runs till counter reaches its limit. Use it when the number of repetitions is known. Sentinel loop runs till a certain condition is encountered. For example a \n (newline) is read from the input. Use it when the number of repetitions is a property of the input and not of the problem being solved. Reversing a Number: Methodology Print the reverse of a given integer: E.g.: 234 à 432 Method: Till the number becomes zero, extract the last digit number modulo 10 make it the next digit of the result multiply the current result by 10 and add the new digit 27 28 Reversing a Number: Illustration x is the given number y is the number being computed x = 56342 y = 0 x = 5634 y = 0*10 + 2 = 2 x = 563 y = 2*10 + 4 = 24 x = 56 y = 24*10 + 3 = 243 x = 5 y = 243*10 + 6 = 2436 x = 0 y = 2436*10 + 5 = 24365 x = x/10 Termnation condition: Stop when x becomes zero y = y*10 + (x%10) 29 Reversing a Number: Program main( ) int x = 0, y = 0; printf ("input an integer :\n"); scanf ("%d", &x); while (x > 0) y = y*10 + ( x % 10 ); x = (x / 10); Remember integer division truncates the quotient printf ("The reversed number is %d \n", y); 30 5

Perfect Number Detection main ( ) int d=2, n, sum=1; scanf ( %d, &n); while (d <= (n/2)) if (n%d == 0) d++; sum += d; if (sum == n) printf ( %d is perfect\n, n); else printf ( %d is not perfect\n, n); Perfect number: sum of proper divisors adds up to the number d<n will also do, but would do unnecessary work Exercise: Modify to find 31 the first n perfect numbers 6