PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

Similar documents
Dept. of CSE, IIT KGP

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

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

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

Unit 3 Decision making, Looping and Arrays

Control Structure: Loop

Conditional Statement

REPETITION CONTROL STRUCTURE LOGO

A Look Back at Arithmetic Operators: the Increment and Decrement

MODULE 2: Branching and Looping

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

Repetition Structures

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

CS1100 Introduction to Programming

Loops / Repetition Statements

Module 4: Decision-making and forming loops

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

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

Conditional Statement

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

Introduction. C provides two styles of flow control:

Chapter 13 Control Structures

Lecture 7 Tao Wang 1

Chapter 4: Making Decisions

DECISION MAKING STATEMENTS

Programming for Engineers Iteration

Chapter 4: Making Decisions

Chapter 4 C Program Control

Lecture 10. Daily Puzzle

COMP 208 Computers in Engineering

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

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

Chapter 2. Section 2.5 while Loop. CS 50 Hathairat Rattanasook

LECTURE 04 MAKING DECISIONS

Flow Chart. The diagrammatic representation shows a solution to a given problem.

Decision Making and Branching

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

Repetition and Loop Statements Chapter 5

PDS: CS Computer Sc & Engg: IIT Kharagpur 1. for Statement

Chapter 13. Control Structures

C Course. IIT Kanpur. Lecture 3 Aug 31, Rishi Kumar <rishik>, Final year BT-MT, CSE

Problem Solving and 'C' Programming

Control structures in C. Going beyond sequential

Computers Programming Course 7. Iulian Năstac

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

Chapter 5: Control Structures

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

Lecture 6. Statements

Repetition Structures II

Decision Making -Branching. Class Incharge: S. Sasirekha

Structured Programming. Dr. Mohamed Khedr Lecture 9

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

Why Is Repetition Needed?

Control Statements. If Statement if statement tests a particular condition

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Information Science 1

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS 1 ST INTERNAL ASSESMENT TEST (SCEME AND SOLUTIONS)

Government Polytechnic Muzaffarpur.

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Engineering 12 - Spring, 1999

Chapter 4 C Program Control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

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

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

LECTURE 5 Control Structures Part 2

& Technology. Expression? Statement-x. void main() int no; scanf("%d", &no); if(no%2==0) if(no%2!=0) Syllabus for 1. of execution of statements.

204111: Computer and Programming

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Chapter 13 Control Structures

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

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

Loops / Repetition Statements

Information Science 1

Fundamentals of Computer Programming Using C

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

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

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

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

Decision Making and Loops

Flow Control. CSC215 Lecture

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

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

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

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

CMPE Experiment 3 Selective Structures

Relational operators (1)

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

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

P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS DEPARTMENT OF SCIENCE AND HUMANITIES EVEN SEMESTER FEB 2017

Iteration. CSE / ENGR 142 Programming I. while loops. Chapter 5. Motivating Loops. Loop to Add 5 Numbers 1996 UW CSE H - 1

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 5. Aykut Erdem, Erkut Erdem, Fuat Akal

Transcription:

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 B x 2A 1 2 x 2A x 2A Roots are not real Print real roots x 1, x 2 Stop

There are three things in any programming: Sequence: A set of statements which would be executed one after another. Start Input A,B,C x B 2 4AC False x If 0 True B x 2A B x 2A 1 2 x 2A x 2A Roots are not real Print real roots x 1, x 2 Stop

Branching: Out of many paths, follow one path Start Input A,B,C x B 2 4AC False x If 0 True B x 2A B x 2A 1 2 x 2A x 2A Roots are not real Print real roots x 1, x 2 Stop

Iteration: Repeat a sequence for a number of times. Start count= 0; max= -1; Please enter +ve number [Yes] count<10? [No] [True] x<0? Read a number x from keyboard Print the maximum [False] [False] max>x? max=x Stop [True] count=count+1

Branching Branching (also called decision ) allows different set of instructions to be executed depending on the outcome of logical test. [False] Logical test [True] Block 2 Block 1 The if-else statement is used to express decision. if (logical test) block 1 else Example [False] Print Hi old Fox! Start Read sex and age If (sex== F ) && age<21 Stop [True] Print You are a pretty woman ; # include<stdio.h> char sex; int age; main() { scanf( %c,&sex); scanf( %d,&age); if((sex== F )&&(age<21)) printf(// ); else printf(// );

If (condition 1) Nesting of if-else statement Block 1 if(condition 2) Block 2 if(condition n) else Block n else else Block 2 Block 1 Problem may arise if all if statement may not have else part! Dangling else problem. if (exp1) if(exp2) statement1; else statement2; if (exp1) if(exp2){ statement1; else statement2; Rule: An else clause is associated with the closest preceding unmatched if.

Switch : Multiple Branching switch (expression) { case const1: statement1 case const2: statement2 default: statement Switch statement is used to select a particular statement from a group of alternative statement(s). Note: Here, expression should evaluate to an int value const1, const2,. Are integer values only Example: int letter; switch(letter = getchar()) { case A : printf( First letter %c\n, letter); break; case Z : printf( Last letter %c\n, letter); break; default: printf( Your letter %c\n, letter); break; Note: The use of break statement

Conditional Operator?: Example interest = (balance>5000)? balance 0.15 : balance 0.10; This is equivalent to: if =(balance>5000) interest= balance 0.15; else interest= balance 0.10;

Looping In looping (also called iteration) a group of instructions that are executed repeatedly while some condition remains true. There are three ways to control a looping: Condition controlled Counter controlled Sentinel controlled

Example 1: Counter controlled Read 5 integers and display the value of their summation.

Example 2: Condition controlled Given an exam marks as input, display the appropriate message based on the rules below: If marks is greater than 49, display PASS, otherwise display FAIL However, for input outside the 0-100 range, display WRONG INPUT and prompt the user to input again until a valid input is entered.

Example 3: Sentinel controlled Read a number of positive integers and display the summation and average of these integers. A negative or zero input indicates the end of input process. Input Example: 30 16 42 9 Output Example: 88 29.33 Sentinel Value

While Statement The while statement is used to carry out looping operations, in which a group of statements is executed repeatedly, as long as some condition remains satisfied. while (condition) statement (s); Example 4: Syntax of while statement while (condition) { statement_1;... statement_n; while ( ) { printf ( Line no : d.\n,i); ; Note: The while-loop will not be entered if the loop-control expression evaluates to false (zero) even before the first iteration. break can be used to come out of the while loop.

Example 5: while statement with break float weight; int flag = 1; printf ("Enter your weight: "); scanf ("%f", &weight); while ( weight > 65.0 ) { printf ("Go, exercise, "); printf ("then come back. \n"); printf ("Do you want to continue?"); scanf ("%d", &flag); if (!flag) break;

Nested while Statement How would you print the following diagram? * * * * * * * * * * * * * * * repeat 3 times print a row of 5 stars repeat 5 times print * #define ROWS 3 #define COLS 5 row =1; while (row <= ROWS) { /* print a row of 5 * s */ row++; row=1; while (row <= ROWS) { col=1; while (col <= COLS) { printf ( * ); col++; printf( \n ); row++; outer loop inner loop

do-while Statement do statement while (expression) main () { int digit=0; do printf( %d\n,digit++); while (digit <= 9) ;

for Statement The for statement is the most commonly used looping structure in C. General syntax: for ( expr1; expr2; expr3) statement; expr1 (init) : initialize parameters expr2 (test): test condition, loop continues if satisfied expr3 (update): used to alter the value of the parameters after each iteration statement (body): body of the loop for (expr1;expr2;expr3) { statement Example int i; for (i=1; i < 100; i += 2;) { printf( %d\t,i);

The comma operator We can give several statements separated by commas in place of expression1, expression2, and expression3. Example for (fact=1, i=1; i<=10; i++) fact fact i; for (sum=0, i=1; i<=n; i++) sum sum i i; Specifying Infinite Loop while (1) { statements for (; ;) { statements do { statements while (1);

Break out of the loop { Example can be used with while do while for switch int main() { int fact, i; fact = 1; i = 1; The break Statement while ( i<=10 ) /* Run loop for 10 times */ { fact = fact * i; if ( fact > 100 ) { printf("factorial of %d above 100", i); break; /* break out of the while loop */ i++ ; return 1;

does not work with if else Causes immediate exit from a while, do/while, for or switch structure. Program execution continues with the first statement after the structure. The continue Statement Skips the remaining statements in the body of a while, for or do/while structure. Proceeds with the next iteration of the loop. while and do/while Loop-continuation test is evaluated immediately after the continue statement is executed. for structure expression3 is evaluated, then expression2 is evaluated.

Example /* a program segment to calculate 10! fact = 1; i = 1; while (1) { ; ; if( 10 ) continue; /* not done yet! Go to loop */ else break; /* Done! Break the loop

Tutorial Problems Problem 1 Draw the flowchart of the following C program # include <stdio.h> main() { int a, b, c; scanf( %d %d %d, &a, &b, &c); if && printf ( \n The largest number is %d, a ); if b && printf ( \n The largest number is %d, b ); if c && printf ( \n The largest number is %d, c ); Problem 2 Are the following two code fragments give same result? Code 1: if (section==16) printf( you are in section 16 ); Code 2: if (section=16) printf( you are in section 16 );

Problem 3 What will be the output of the following code segment? You should assume suitable values of the variables and then give your answer. z = 0; if(n>0) if(a>b) z=a; else z=b; printf( Yahoo! %d, z); Case 1: n = 5, a = 9, b = 6 Case 2: n = -5, a = 9, b = 6 Case 3 n = 5, a = 6, b = 9 Problem 4 Your program asks a user to type y or Y to select Yes and n or N to select No. Which of the following codes is correct to show the option selected by the user? Code 1 c = getchar(); if(c== y )&&(c== Y ) printf( Yes \n ); else printf( No \n ); Code 2 c = getchar(); if(c!= n ) (c!= N ) printf( Yes \n ); else printf( No \n );

Problem 5 Write simplified equivalent code for the following. x = ((a>10)&&(b<5))?a+b:0; marks>60? printf( passed \n ): printf( fail \n ); Problem 6 Write c-program to convert a grade given a marks. : 90 A:80 90 :70 80 :60 70 :50 60 :35 50 : 35 Problem 7 Which of the following nested if statements are logically equivalent to the flow chart below? a== F T d> T b> T x = b F x = a F c T F x= c (A) if(a==b)if(d>c) if(b>c)x=b; else if (c==a);else x=c; else x=a; (B) if(a==b)if(d>c) if(b>c)x=b; else if (c==a); x=c; else x=a; (C) if(a==b)if(d>c) D. Samanta, IIT if(b>c)x=b; else if (c!=a) x=c; else x=a; (D) if(a==b)if(d>c) if(b>c)x=b; else if (c!=a) x=c; else; else x=a; (E) None of the above.

Problem 8 How would you print the following Pascal triangle? * * * * * * * * * ******* Problem 9 Let n, i and sum be int variables. The user enters a positive value of n. Which of the following program segments prints the largest value of sum? sum = 0; i = 1; while (++i < n) sum += i; printf("%d", sum); sum = 0; i = 1; while (i++ < n) sum += i; printf("%d", sum); for (sum = 0, i = 1; i < n; i++) sum += i; printf("%d", sum); for (sum = 0, i = 1; i <= n; ++i) sum += i; printf("%d", sum);

Problem 10 Consider the program segment. int sum = 0; int i = 0; while (i < 5) { sum = sum + i; i++; printf( %d\n,sum); Suppose we replace the while loop in the segment above with a for loop. Which of the following for loops will result in the same value of sum printing out? A. for (int i = 0; i <= 5; i++) sum = sum + i; B. for (int i = 1; i <= 5; i++) sum = sum + i; C. for (int i = 1; i < 5; i++) sum = sum + i; D. for (int i = 2; i < 5; i++) sum = sum + i; E. for (int i = 1; i < 6; i++) sum = sum + i; Important links:

http://cse.iitkgp.ac.in/~dsamanta/courses/pds/index.html