Computer Programming. Decision Making (2) Loops

Similar documents
DECISION CONTROL AND LOOPING STATEMENTS

Dept. of CSE, IIT KGP

Lecture 8. Daily Puzzle

Functions. Arash Rafiey. September 26, 2017

MODULE 2: Branching and Looping

Chapter 5: Control Structures

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

Note: If only one statement is to be followed by the if or else condition then there is no need of parenthesis.

CS1100 Introduction to Programming

Control Structure: Loop

Decision Making -Branching. Class Incharge: S. Sasirekha

BRANCHING if-else statements

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

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

CEN 134 Algorithms and Programming II Midterm I. April Duration: 90 minutes

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

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

COMP 208 Computers in Engineering

16.216: ECE Application Programming Fall 2011

A Look Back at Arithmetic Operators: the Increment and Decrement

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

Computer System and programming in C

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

I SEMESTER EXAM : : XI :COMPUTER SCIENCE : MAX MARK a) What is the difference between Hardware and Software? Give one example for each.

C: How to Program. Week /Mar/05

Chapter 2 - Introduction to C Programming

Precedence and Associativity Table. % specifiers in ANSI C: String Control Codes:

Introduction. C provides two styles of flow control:

LAB 5: REPETITION STRUCTURE(LOOP)

Loops / Repetition Statements

AMCAT Automata Coding Sample Questions And Answers

Module 4: Decision-making and forming loops

Copy: IF THE PROGRAM or OUTPUT is Copied, then both will have grade zero.

UIC. C Programming Primer. Bharathidasan University

Midterm Exam. CSCI 2132: Software Development. March 4, Marks. Question 1 (10) Question 2 (10) Question 3 (10) Question 4 (10) Question 5 (5)

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

INTRODUCTION TO COMPUTER SCIENCE - LAB

Chapter 3 Structured Program Development

Programming and Data Structure Tutorial sheet: 1 Topics: Data Handling, Operators and Expressions, Input and Output Operations.

Subject: Fundamental of Computer Programming 2068

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

Tutorial 7. Number Colour Black Brown Red Orange Yellow Green Blue Violet Gray White

H192 Midterm 1 Review. Tom Zajdel

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

ME 172. Lecture 2. Data Types and Modifier 3/7/2011. variables scanf() printf() Basic data types are. Modifiers. char int float double

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

Slides adopted from T. Ferguson Spring 2016

PROGRAMMING IN C LAB MANUAL FOR DIPLOMA IN ECE/EEE

Decision Making and Branching

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

LAB 4.1 Relational Operators and the if Statement

LAB 5: REPETITION STRUCTURE(LOOP)

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

UNIVERSITY OF WINDSOR Winter 2007 QUIZ # 1 Solution. Examiner:Ritu Chaturvedi Dated : Feb 7 th, Student Name: Student Number:

PDS Lab Section 16 Autumn Tutorial 3. C Programming Constructs

EECE.2160: ECE Application Programming Spring 2018

Introduction to C. Systems Programming Concepts

Control Statements. If Statement if statement tests a particular condition

Lecture 6. Statements

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

CS-211 Fall 2017 Test 1 Version Practice For Test on Oct. 2, Name:

Programming Language A

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

ASSIGNMENT CLASS-11 COMPUTER SCIENCE [C++]

DECISION MAKING STATEMENTS

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

Control Structure: Selection

Object Oriented Pragramming (22316)

SECTION A TRUE / FALSE QUESTIONS (10 MARKS) (INSTRUCTION: Please answer all 10 questions)

LOOPS. 1- Write a program that prompts user to enter an integer N and determines and prints the sum of cubes from 5 to N (i.e. sum of 5 3 to N 3 ).

Repetition Algorithms

CSCI 131, Midterm Exam 1 Review Questions This sheet is intended to help you prepare for the first exam in this course. The following topics have

Loops / Repetition Statements

Lecture 10. Daily Puzzle

Prepared by: Shraddha Modi

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

3 The L oop Control Structure

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

UNIVERSITY OF WINDSOR Fall 2006 QUIZ # 1. Examiner:Ritu Chaturvedi Dated : Oct 3rd, Student Name: Student Number:

Materials covered in this lecture are: A. Completing Ch. 2 Objectives: Example of 6 steps (RCMACT) for solving a problem.

ESC101N: Fundamentals of Computing End-sem st semester

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities

Flow Control. CSC215 Lecture

Quiz1 Fall 2007 October 2 nd, UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 1 Solution. Examiner:Ritu Chaturvedi Dated :October 2nd, 2007.

Lab 2: Structured Program Development in C

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

ALGORITHM 2-1 Solution for Exercise 4

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

EECE.2160: ECE Application Programming Fall 2017

Computer Programing. for Physicists [SCPY204] Class 02: 25 Jan 2018

C Programming Class I

C++ PROGRAMMING SKILLS Part 2 Programming Structures

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

CSCE Practice Midterm. Data Types

1.4 Control Structures: Selection. Department of CSE

CS 105 Lecture 5 Logical Operators; Switch Statement. Wed, Feb 16, 2011, 5:11 pm

Computers in Engineering. Moving From Fortran to C Part 2 Michael A. Hawker

Question Bank (SPA SEM II)

Transcription:

Computer Programming Decision Making (2) Loops

Topics The Conditional Execution of C Statements (review) Making a Decision (review) If Statement (review) Switch-case Repeating Statements while loop Examples

Conditional Execution of Statements (Review from last week) A Statement defines an action to be carried out. However, you may want to carry out the action on certain conditions. e.g. If b is not zero then compute a/b if D is not negative then find its square root

Conditions A conditional expression is executed only if the given condition is true. A condition is expressed as a logical expression. e.g. Verify if the value in variable X is even or not The value in variable X is even if it is divisible by 2 so the condition will be: X%2==0

Decision Making To carry out a statement conditionally, a decision should be made. Decision making in C is done by if-else statement if( condition ) [The statements carried out when condition is true] else [The statements carried out when condition is false]

Example Read an integer and check if it is positive and divisible by 5 or not. Print a proper message in each case #include<stdio.h> void main() int num; scanf( %d,&num); if( num % 5 ==0 && num >= 0 ) printf( The condition was true\n ); else printf( The condition was false\n );

Decision Making using Switch-Case If an integer or a character variable is tested against several constant values we can use switch-case statement for decision making. Example: The example below can be written with switch-case int num; scanf( %d,&num); if(num == 10) printf( Excellent \n ); else if(num == 9) printf( Very good \n ); else if(num == 8) printf( Good \n ); else if(num == 7) printf( Average \n ); else printf( Weak \n );

When Can We Use switch-case The variable should be integer or character Compare for equality only ( only ==, we cannot use!=,>, >=, <, or <= with switch-case) The condition is not a compound condition (AND, OR are not used to combine simple logical expressions )

Switch-Case Statements The structure of a switch-case statement is as below: switch(variable) case value1: [statements if variable==value1]; break; // exit switch-case case value2: [statements if variable==value2]; break; // exit switch-case default: [ statements if variable is not equal to any value given is cases]

Example #include<stdio.h> void main() int grade; scanf( %d,&grade); switch(grade) case 10: printf( Excellent\n ); break; case 9: printf( Very Good\n ); break; case 8: printf( Good\n ); break; case 7: printf( Average\n ); break; default: printf( Weak\n );

Break Statement Break statement makes the program exit the switch-case statement. Default part is the last part of switch-case, so we do not need a break in default part. If a case does not have a break statement, the next case is also executed. This can be used to OR two cases.

Example Using switch-case statement write a program to read an integer number greater than 1 and less than 10 and do the followings: If the number is 2,4, 6, or 8 print EVEN If the number is 3, 5, or 7 print PRIME If the number is 9 print ODD Otherwise print Out of Range

#include<stdio.h> void main() int num; scanf( %d,&num); switch(num) case 2: case 4: case 6: case 8: printf( EVEN\n ); break; case 9: printf( ODD\n ); break; case 3: case 5: case 7: printf( PRIME\n ); break; default: printf( Out of Range\n );

Default Default is executed when the variable does not have any of the values in case parts In fact it can be assumed as if non of the above values then.. Default part of switch-case statements is optional (same as else in if statements)

Repeating Statements In many cases same operations are repeated for different data. For example, finding average of a student is repeated for other students too. In these cases, we can use a statement called a loop The statements inside a loop are repeated until its condition becomes false. C uses three types of loops: While loop Do-while loop (will be discussed next week) For loop (will be discussed next week)

While Loop While loop repeats a group of C statements until its condition becomes false While loop has the following syntax: while(condition) [statements]; Condition is a logical expression Statements inside the while loop are called body of while loop If more than one statement is written inside body of a while loop, they should be put in

Example 1 Write a program to print all positive even integers less than 100. The output should be like: 2 4 6.. 96 98

#include<stdio.h> void main() int count; count = 2; while( count < 100 ) printf( %d\n, count); count = count + 2;

Example 2 Re-write the calculator example to find the results until -1 is entered as the value of both operands. (e.g. ends when -1 / -1 is entered) Calculator This example is a simple calculator which can perform four operations: +, -, *, / The program reads two numbers and a character. The character defines the operation. The character can be *, -, /, or + The program carries out the operation and prints the result

#include<stdio.h> void main() float num1, num2, result; char op; printf( Enter the expression:\n ); scanf( %f%c%f,&num1,&op,&num2); while( num1!= -1 num2!= -1 ) if( op == + ) result = num1+num2; printf( The result is %f\n, result); else if( op == - ) result = num1-num2; printf( The result is %f\n, result); else if( op == * ) result = num1*num2; printf( The result is %f\n, result);

else if( op == / ) if( num2!= 0 ) result = num1/num2; printf( The result is %f\n, result); else printf( Oops!!! Division by zero\n ); else /* if the operator is not one of the 4 valid operators*/ printf( Invalid operator entered!!! \n ); /* read next expression */ printf( Enter the expression:\n ); scanf( %f%c%f,&num1,&op,&num2); /* end of while loop is here */

Example 3 Write a C program to read three grades of each student and find his/her average. The first grade is midterm exam grade, the second grade is final exam grade, and the third grade is assignment grade. The weight of each grade is: Midterm 30% Assignment 25% Final 45% Repeat finding average for 20 students

#include<stdio.h> void main() float midterm, assignment, final, avg; int count; count = 0; while(count < 20) printf( Enter the midterm, assignment, and final grade \n ); scanf( %f%f%f, &midterm, &assignment, &final); avg=midterm *0.3+assignmenrt*0.25+final*0.45; printf( The average is %6.2f\n,avg); count=count+1;

Example 4 Write a C program to read a positive integer and find sum of all positive integers up to and including that number. Hint: Make sure that the number is positive

#include<stdio.h> void main() int num, sum; int count; count = 1; sum = 0; printf( Enter a positive integer \n ); scanf( %d, &num); if( num < 0 ) printf( You entered a negative number\n ); else while(count <= num) sum=sum+count; count=count+1; printf( The sum is %d \n,sum);

Summary Some statements in a C program are executed conditionally If the condition is a simple logical statement testing an integer or character variable using equality (==), switchcase statements can be used If parts of a program are repeated with different values, we can use a loop while loop repeats executing the statements until the condition becomes false

Questions?