3/13/2012. Writing Simple C Programs. ESc101: Decision making using if-else and switch statements. Writing Simple C Programs



Similar documents
Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

arrays C Programming Language - Arrays

Conditionals (with solutions)

Selection Statements

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Informatica e Sistemi in Tempo Reale

J a v a Quiz (Unit 3, Test 0 Practice)

Sources: On the Web: Slides will be available on:

Fundamentals of Programming

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

CS1010 Programming Methodology A beginning in problem solving in Computer Science. Aaron Tan 20 July 2015

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Lecture 2 Notes: Flow of Control

Chapter 5. Selection 5-1

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Fixture List 2018 FIFA World Cup Preliminary Competition

CS 241 Data Organization Coding Standards

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Conditional Statements Summer 2010 Margaret Reid-Miller

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Program Logic to Java GEEN163

Statements and Control Flow

Introduction to Java

Stacks. Linear data structures

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

So far we have considered only numeric processing, i.e. processing of numeric data represented

13 Classes & Objects with Constructors/Destructors

PIC 10A. Lecture 7: Graphics II and intro to the if statement

C++FA 5.1 PRACTICE MID-TERM EXAM

Example of a Java program

Cruise Line Agencies of Alaska. Cruise Ship Calendar for 2016 FOR PORT(S) = KTN AND SHIP(S) = ALL AND VOYAGES = ALL

CP Lab 2: Writing programs for simple arithmetic problems

VB.NET Programming Fundamentals

Binary Representation. Number Systems. Base 10, Base 2, Base 16. Positional Notation. Conversion of Any Base to Decimal.

Cruise Line Agencies of Alaska. Cruise Ship Calendar for 2016 FOR PORT(S) = KTN AND SHIP(S) = ALL AND VOYAGES = ALL

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Tutorial on C Language Programming

Chapter 8 Selection 8-1

JavaScript: Control Statements I

Part I. Multiple Choice Questions (2 points each):

Unit 6. Loop statements

While Loop. 6. Iteration

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

Oct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8

Basic Components of an LP:

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

EE 261 Introduction to Logic Circuits. Module #2 Number Systems

Accentuate the Negative: Homework Examples from ACE

Exercises for Design of Test Cases

AP Computer Science Java Subset

Chapter One Introduction to Programming

Using Microsoft Project 2000

Digital System Design Prof. D Roychoudhry Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Q&As: Microsoft Excel 2013: Chapter 2

Java Basics: Data Types, Variables, and Loops

Conditions & Boolean Expressions

Boolean Data Outline

Employee Central Payroll Time Sheet

Pemrograman Dasar. Basic Elements Of Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Digital Design. Assoc. Prof. Dr. Berna Örs Yalçın

Help on the Embedded Software Block

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

I PUC - Computer Science. Practical s Syllabus. Contents

1 Description of The Simpletron

U11 Boys Black March 21st Monday 6:00-7:30 p.m. Damien Training Field 2 March 24th Thursday 4:30-6:00 p.m. Damien Training Field 2 March 28th Monday 6

PA2: Word Cloud (100 Points)

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

Introduction to Programming II Winter, 2014 Assignment 2

KS2 Missing Digits Non-Calculator Level 3/4 Number of practice sheets: 9 MathSphere MathSphere

The C Programming Language course syllabus associate level

Visual Logic Instructions and Assignments

6. Control Structures

B.Sc.(Computer Science) and. B.Sc.(IT) Effective From July 2011

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

COMPUTER SCIENCE 1999 (Delhi Board)

Pseudo code Tutorial and Exercises Teacher s Version

Cruise Line Agencies of Alaska. Cruise Ship Calendar for 2012 FOR PORT(S) = KTN AND SHIP(S) = ALL AND VOYAGES = ALL

Computer Programming Tutorial

Chapter 3 Operators and Control Flow

Cruise Line Agencies of Alaska. Cruise Ship Calendar for 2013 FOR PORT(S) = KTN AND SHIP(S) = ALL AND VOYAGES = ALL

Siemens S7 Status Word

Object Oriented Software Design

CSI 333 Lecture 1 Number Systems

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

In this Chapter you ll learn:

Binary Representation

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

The programming language C. sws1 1

Variables, Constants, and Data Types

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

Transcription:

Writing Simple C Programs ESc101: Decision making using if- and switch statements Instructor: Krithika Venkataramani Semester 2, 2011-2012 Use standard files having predefined instructions stdio.h: has defined standard input and output instructions always needed for reading input /displaying output math.h: has specific math instructions such as square-root, power not needed if these instructions are not used #include<stdio.h> #include<math.h> main function has the program void main() --- 1 3 Writing Simple C Programs The content t of many of these slides are taken from the Lecture slides of Prof. Arnab Bhattacharya and Prof. R. K. Ghosh 2 Declare variables to use/process different data types int number; float real; char letter; Can assign a constant as initial value of the variables int number = 5; float real = 5.5; char letter = A ; Use printf for displaying output on monitor printf( \ninteger = %d", number); Integer = 5 %d is a place holder (format specifier) for displaying the value of the integer variable number \n :moves to a new line while displaying 4 1

Writing Simple C Programs if- statements Use the appropriate format specifier for displaying different variable types using printf printf( \nreal number = %f", real); Real number = 5.500000 printf( \ncharacter = %c and Integer = %d", letter, number); Character = A and Integer = 5 Used in Decision making Example Algorithm: Find the minimum of two integers 1. Compare the two integers x and y 2. If x < y, then min = x 3. Otherwise, min = y To capture the above logic in C, if- statements are used Type Format Specifier char %c int %d unsigned int %u float %f, %g, %e double %lf if ( condition ) statements1 statements2 long double %Lf 5 Entire if- is a single statement 7 Writing Simple C Programs Use scanf for reading input from keyboard scanf requires & before the variable name Why it is required will be explained later Examples scanf( %d", &number); scanf( %f", &real); scanf( %c", &letter); Use appropriate format specifiers for different variable types Type Format Specifier char %c int %d unsigned int %u float %f, %g, %e double %lf long double %Lf 6 Program to find sum and minimum of two numbers # include <stdio.h> void main () int x, y; int min, sum; scanf (``%d'', &x); scanf (``%d'', &y); sum = x + y; if (x < y) min = x; min = y; printf (``Minimum is %d and Sum is %d\n'', min, sum); 8 2

Understanding if- statement Nested if- if ( condition ) statements1 statements2 Condition must evaluate to a boolean value When condition is true, if-statement is executed When condition is false, -statement is executed Any expression fits as a condition - part can be omitted if ( condition ) statements1 9 Else with more than one previous if is ambiguous if ((x + y) > 0) if (x < y) printf (``x is minimum ''); printf (``y is minimum ''); Rule: is associated with nearest if Indenting lines in program helps in understanding 11 Understanding if- statement Nested if- A block of statements may be used in if and part A block of statements is equivalent to a single statement if ( condition ) statement1 statement2 statement3 statement4 Use braces if intended otherwise if ((x + y) > 0) if (x < y) printf (``x is minimum ''); printf (``x + y is negative ''); 10 12 3

Testing more than two conditions Find minimum of two numbers or find equality Testing more than two conditions can be done using if if (x < 0) printf (`` Negative ''); if (x > 0) printf (`` Positive ''); # include <stdio.h> void main () int x, y; int min, sum; scanf (``%d'', &x); printf (`` Zero ''); is equivalent to if (x < 0) printf (`` Negative ''); if (x > 0) printf (`` Positive ''); printf (`` Zero ''); 13 scanf (``%d'', &y); if (x < y) min = x; printf (``Minimum is %d \n'', min); 15 Example Test for more than two conditions Find minimum of two numbers (cont.) Example Algorithm: Find the minimum of two integers or equality 1. Compare the two integers x and y 2. If x < y, then min = x 3. Otherwise, if y < x, then min = y 4. Otherwise, both numbers are equal if (y < x) min = y; printf (``Minimum is %d \n'', min); printf( \nboth numbers are equal ), 14 16 4

Sample program to find triangle type Lab 1 : Q1 sample solutions Please take the 3 sides of a triangle, and print whether the triangle is an equilateral, isosceles or scalene triangle. #include<stdio.h> void main() float side1, side2, side3; //declare variables to take the 3 sides of a triangle printf( Enter the three sides of a triangle: ); scanf( %f %f %f, &side1, &side2, &side3); if ( ((side1+side2)>side3) && ((side2+side3)>side1) && ((side1+side3)>side2) ) Take a character as input from the user. Check whether the character is an alphabet or not. Algorithm: 1. Input a character 2. If character is between a to z, or between A to Z, it is an alphabet 3. Otherwise, it is not an alphabet 17 19 Program to find type of triangle (cont.) if ( (side1==side2) && (side1==side3) ) printf( \nthe triangle is equilateral ); if ((side1!=side2) && (side2!=side3) && (side1!=side3)) printf( \nthe triangle is scalene ); printf( \nthe triangle is isosceles ); printf( \na triangle is not formed using these sides ); 18 Lab 1 sample solutions: Q1 #include<stdio.h> /* Q1. Author:rahule@cse.iitk.ac.in */ int main() char ip; printf("enter the character to be checked: "); scanf("%c",&ip); //checking if it is a Alphabet if( (ip>='a'&&ip<='z') (ip>='a'&&ip<='z') ) printf("the input character is an alphabet\n"); printf("the input character is NOT an alphabet\n"); 20 5

Lab 1: Q2 Sample Solutions Take as input 4 numbers. Print arithmetic mean & harmonic mean. Print the maximum of the two means. Algorithm 1. Input 4 real numbers: a, b, c, d 2. If any of the numbers is not positive, harmonic mean is not valid 3. Otherwise, 1/(harmonic mean) = ((1/a) + (1/b) + (1/c) + (1/d))/4 4. Arithmetic mean = (a+b+c+d)/4 5. If harmonic mean is valid and harmonic mean > arithmetic mean, max = harmonic mean 6. Otherwise, max = Arithmetic mean 21 Lab 1: Q2 Sample Solutions (cont.) flag = 1; harmonic_mean=4/(1/n1 + 1/n2 + 1/n3 + 1/n4); printf("harmonicmean: %f\n",harmonic_mean); //checking which one is maximum if((flag ==1)&&(arithmetic_mean= =harmonic_mean)) printf("harmonic Mean is equal to arithmetic meanr\n"); printf("maximum mean = %f",harmonic_mean); //prints Arithmetic mean is larger even if harmonic mean is not valid printf("arithmetic Mean is larger\n"); printf("maximum mean = %f",arithmetic_mean); 23 Lab 1: Q2 Sample Solutions /* Q2. Author:rahule@cse.iitk.ac.in */ #include<stdio.h> int main() float n1,n2,n3,n4,arithmetic_mean=0,harmonic_mean; int flag = 0; scanf("%f%f%f%f, &n1,&n2,&n3,&n4); //calculating the arithmetic mean arithmetic_mean=(n1+n2+n3+n4)/4; printf("arithmetic Mean: %f\n",arithmetic_mean); //calculating the harmonic mean if(n1 <= 0 n2 <= 0 n3 <= 0 n4 <= 0 ) printf("harmonic mean can not be calculated as atleast one number is not positive!\n"); 22 Q2 alternate sample solution using nested if- //calculating the harmonic mean if(n1 <= 0 n2 <= 0 n3 <= 0 n4 <= 0 ) printf("harmonic mean can not be calculated!\n"); harmonic_mean=4/(1/n1 + 1/n2 + 1/n3 + 1/n4); //printing the results printf("harmonicmean: %f\n",harmonic_mean); //checking which one is maximum if(arithmetic_mean>harmonic_mean) printf("arithmetic Mean is larger\n"); printf("harmonic Mean is equal to Arithmetic meanr\n"); 24 6

Lab 1: Q3 sample solution using if statement Lab 1: Q3 sample solution using if statement (cont.) Take a 5 digit integer as input from the user. Count the total number of zeroes in it and print the result. Algorithm: 1. Input the integer 2. Initialize zero_count to 0 3. Find the remainder of integer by dividing using 10 4. If remainder is zero, then increment zero_count by 1 5. Divide the integer by 10 6. Use the quotient as the new integer 7. Repeat Steps 3 to 5 an additional 4 times 8. Display zero_count //checking if the 3rd digit is zero if(n%10 == 0) count++; n=n/10; //checking if the 2nd digit is zero if(n%10 == 0) count++; n=n/10; // end of if condition for checking a 5 digit integer //printing the results printf("number of zeros: %d\n",count); 25 27 Lab 1: Q3 sample solution using if statement /*author:rahule@cse.iitk.ac.in*/ #include<stdio.h> int main() int n, count=0; printf("enter the FIVE DIGIT integer\n"); scanf("%d",&n); if ( ((n<=99999)&&(n>=10000)) ((n>=-99999)&&(n<=-10000)) ) //check for zeroes only if it is a 5 digit integer if(n%10 == 0) //checking if the 5th(last) digit is zero count++; n=n/10; //converting to a 4 digit integer if(n%10 == 0) // checking if 4 th digit of original integer is zero count++; n=n/10; //converting to a 3 digit integer 26 Consider if ( section == 1) printf (`` TB101 ''); if ( section == 2) printf (`` TB102 ''); if ( section == 12) printf (`` TB112 ''); printf (`` Wrong section ''); Multiple if- Multiple -if statements are better written using switch statements switch works only when the same variable is tested for equality against different constant values 28 7

Switch used for multi-way decision Switch statement switch (expression) case constant-expression1: statements; break; case constant-expression2: statements; break; default: statements; break; switch is useful when multiple l decisions i can be made depending on the value of the expression The expression must evaluate to a constant integer The case values are constant integers Characters are mapped to integers and can be used in switch Real numbers (float, double) cannot be used in switch default is executed when variable evaluates to none of the other values break brings the control out of the switch statement 29 Important: Without break, next case is also executed switch (x) case 0: printf (``0''); case 1: printf (``1''); default : printf (``2''); When x is 0, all of 0, 1 and 2 are printed When x is 1, both 1 and 2 are printed 31 Switch statement Switch statement without break Example switch ( section ) case 1: printf (`` TB101 ''); break ; case 2: printf (`` TB102 ''); break ; case 12: printf (`` TB112 ''); break ; default : printf (`` Wrong section ''); break ; switch case without break is useful when same statement needs to be executed for multiple cases Suppose there are two sections, 1 and 2, on Monday, two sections, 3 and 4, on Tuesday, and others on Wednesday Output the day based on input section switch ( section ) case 1: ; case 2: printf (`` Monday ''); break ; case 3: ; case 4: printf (`` Tuesday ''); break ; default : printf (`` Wednesday ''); break ; 30 32 8

break brings control out of switch statement Control is transferred to the case statement depending on the value of the expression Control is transferred to default case when the value of the expression does not match any of the case values Without break, the statements in the next case are also executed While break is not required for the last case (could be the default case), it is a good programming practice as its useful when additional cases are inserted Removing break is sometimes useful when the same statement needs to be executed for multiple cases 33 break not used when multiple cases need same statement /*display color name based on first character of color (small or capital letters)*/ scanf( %c, &color) switch (color) case w : case W : //for both w and W, White is displayed printf( White\n ); break; case r : case R : //for both r and R, Red is displayed printf( Red\n ); break; case g : case G : //for both g and G, Green is displayed printf( Green\n ); break; default : printf( Choose among known colors\n ); 35 switch used for multiple options in menu selection More on Switch statement ------ printf( Travel guide\n ); printf( A: Air/flight timings\n ); printf( T: Train timings\n ); printf( B: Bus timings\n ); printf( Enter your choice: ); scanf( %c, &character); switch (character) case A : air_display(); break; //Using a function to display flight times case T : train_display(); break; //using a function to display train times case B : bus_display(); break; //using a function to display bus times default : printf( No choice made ); ----- 34 The case values in switch are to be constant integers break brings execution out of the switch statement For the same statement s to be executed for multiple cases, put the statements in the last of these cases and leave the rest of the case values blank with no break switch (color) case w : case W : //for both w and W, White is displayed printf( White\n ); break; switch (color) case w W : printf( White\n ); break; //does not provide desired //result as w W = 1 and this case is equivalent to case 1 36 9

Sample program Energy bill using if ladder Write a program that takes as input a letter and displays if it is a vowel or consonant using a switch statement scanf( %c, &c); //error check to see if c is an alphabet or not switch (c) case a : case A : case e : case E : case I : case i : case o : case O : case u : case U : printf( \n It is a vowel ); break; default: printf( \nit is a consonant ); break; Algorithm 1. Input initial and final readings 2. Units consumed,c, = final reading initial reading 3. If c is between 0 and 100, bill = Rs. c*1.50 4. Otherwise, if c is between 100 and 200, bill = Rs. c*2.50 5. Otherwise, if c is between 200 and 500, bill = Rs. c*3.50 6. Display bill 37 39 Example: if ladder Write a program to calculate energy bill. Read the starting and ending meter reading. The charges are as follows No. of units consumed Rates in Rs. 200-500 3.50 100-200 2.50 0-100 1.50 Energy bill using if ladder int initial, final, consumed; float bill=0; printf( Enter initial and final readings: ); scanf( %d %d,&initial, &final); consumed = final initial; if ((consumed>0 &&(consumed<100)) bill = consumed*1.5; if ((consumed<200)&&(consumed>=100)) bill = consumed*2.5; if ((consumed<500)&&(consumed>=200)) bill = consumed*3.5; printf( \nconsumption is expected to be within 0 and 500 ) print( \nbill amount = %f,bill); 38 40 10

Energy bill using switch statement switch (consumed/100) case 0: bill = consumed*1.5; break; case 1: bill = consumed*2.5; break; case 2: case 3: case 4: case 5: if (consumed <= 500) bill = consumed*3.5; break; default: printf( \nunits consumed is between 0 and 500 ); 41 Day of the week using switch statement int day; printf( \nenter the day of the week from 1 to 7: ); scanf( %d, &day); switch(day) case 1: printf( Sunday ); break; case 2: printf( Monday ); break; case 3: printf( Tuesday ); break; case 4: printf( Wednesday ); break; case 5: printf( Thursday ); break; case 6: printf( Friday ); break; case 7: printf( Saturday ); break; default: printf( Week has only 7 days ); 43 Example using switch statement Display the name of day of the week Algorithm Input the day number of the week between 1 and 7 Depending on the day number, display the day of the week 1: Sunday 2: Monday 3: Tuesday 4: Wednesday 5: Thursday 6: Friday 7: Saturday 42 11