Introduction to Problem Solving and Programming Lecture 1

Introduction to Problem Solving and Programming Lecture 1 - Introduction and Review

Objectives Identify skills and personality traits of successful problem solving. Apply standard problem-solving techniques to aid in problem solving. Apply problem-solving techniques to programming activities. Generate potential solutions to problems. Formulate and successfully communicate the solutions to problems.

Lecture Outline Types of Problems Problem Solving Steps Problem Solving Strategies Algorithm Design Techniques Review Flowcharts Review C Language ◦ Basics (variables, data types, expressions, I/O, etc. ). ◦ Decisions (if statement and switch statement)

Types of Problems with Algorithmic Solutions Problems with Heuristic Solutions ◦ Problems that can be solved with a series of actions ◦ Balancing checkbook, baking a cake ◦ Alphabetizing 10, 000 names ◦ Problem solution requiring reasoning based on knowledge and experience, and a process of trial and error ◦ Solutions cannot be reached through a direct set of steps ◦ How to buy the best stock or expand the company ◦ Difficult to evaluate the solution

Types of Problems People are better at solving heuristic problems ◦ Artificial intelligence is the field of computer science that deals with heuristic problems Computers are better at solving complicated calculus problems or alphabetizing 10, 000 names ◦ This class deals with algorithmic solutions

Problem Solving Steps Identify or Define the problem Analyze the problem (inputs, outputs, formulas, constants) Design the Solution (flowchart, algorithm, pseudo-code) ◦ Identify alternative ways to solve the problem ◦ Select the best way to solve the problem from the list of alternative solutions ◦ List instructions that enable you to solve the problem using selected solution Implement (program code) Evaluate

Problem Solving Steps

Converting Miles to Kilometers 1. 2. 3. Problem: Your boss wants you to convert a list of miles to kilometers. Since you like programming, so you decide to write a program to do the job. Analysis • We need to get miles as input • We need to output kilometers • We know 1 mile = 1. 609 kilometers Design 1. Get distance in miles 2. Convert to kilometers 3. Display kilometers 8

4. Implementation 9

(1) Understanding the problem We need to read it till we understand every detail We need to dissect the problem into its component parts (e. g. problems and sub -problems) We need to remove any ambiguity, extra information We need to determine our knowns and our unknowns We need to be aware of any assumptions we are making.

Problem Analysis Chart

Problem Analysis Chart: Payroll Problem

Problem Solving Strategies Brute-force Divide and Conquer Greedy

Examples of Algorithm Design Techniques Brute-Force: ◦ Try all possibilities Divide and Conquer: 1. Divide: Break the given problem into sub problems of same type. 2. Conquer: Recursively solve these sub problems 3. Combine: Appropriately combine the answers Merge Sort is also a sorting algorithm. The algorithm divides the array in two halves, recursively sorts them and finally merges the two sorted halves.

Examples of Algorithm Design Techniques Greedy: ◦ Find the local optimal step at each stage. ◦ Not necessarily globally optimal. ◦ Example: ◦ With a goal of reaching the largest-sum, at each step, the greedy algorithm will choose what appears to be the optimal immediate choice, so it will choose 12 instead of 3 at the second step, and will not reach the best solution, which contains 99.

Review Flowcharts

Flowchart Symbols

Flowchart Symbols

Flowchart Symbols

Flowchart Symbols

Example: Payroll

Review C Language

C Program structure Function Header Function Body 23

Identifiers Declarations ◦ An identifier must consist only of letters, digits, and underscores. ◦ An identifier cannot begin with a digit. ◦ A C reserved word cannot be used as an identifier. ◦ A standard identifier should not be redefined. ◦ C compilers are case sensitive. (Rate, rate and RATE are viewed as different identifiers) Valid identifiers: letter 1, inches, KM_PER_MILE Invalid identifiers: 1 letter, Happy*trout, return 2 4

Giving a Value to a Variable 25

Output Function SYNTAX printf( format string , print list ) ; Printf(format string); Examples : Place holder printf(“That equals %f kilometers. n”, kms); printf(“enter the distance in miles> ”); printf( “Hello, World? n“); Escape sequence 26

Output Function 27

Input Function SYNTAX scanf( format string , input list ) ; Examples : Place holder scanf(“%lf”, &miles); Ampersand 28

Input Function 29

Programming Examples: Example-1 Write a program to ask the user for the width and length of a piece of land then tell him how many orange trees he can grow on it. Given that each orange tree requires 4 m 2. 30

Programming Examples #include <stdio. h> # define one_tree_space 4 int main() { int length, width, area, no_of_tree; printf(“Enter length of the land> ”); scanf(“%d”, &length); printf(“Enter width of the land> ”); scanf(“%d”, &width); area = length * width; no_of_tree = area / one_tree_space; printf(“The available number of trees is %d treesn”, no_of_tree); return(0); } 31

Arithmetic Operators Division • • • the result of the division operator depends on the type of its operands if one or both operands has a floating point type, the result is a floating point type. Otherwise, the result is an integer type Examples 11 11. 0 / 4. 0 11 / 4. 0 15 / 3 16 / 3 /4 has value 2. 75 has value 5 32

Arithmetic Operators (+, -, *, /, %) Modulus the modulus operator % can only be used with integer type operands and always has an integer type result • its result is the integer type remainder of an integer division EXAMPLE 3%5=35%3=2 4%5=4 5%4=1 5%5=06%5=1 7%5=2 8%5=3 15 % 6 = 3 15 % 5 = 0 • 33

Relational and Equality Operators Most conditions that we use to perform comparisons will have one of these forms: ◦ ◦ variable relational-operator variable e. g. a < b relational-operator constant e. g. a > 3 equality-operator variable e. g. a = = b equality-operator constant e. g. a != 10 34

Relational and Equality Operators Operator Meaning Type < less than relational > greater than relational <= less than or equal to relational >= greater than or equal to relational == equal to equality != not equal to equality 35

Logical Operators logical expressions - expressions that use conditional statements and logical operators. ◦ && (and) A && B is true if and only if both A and B are true ◦ || (or) A || B is true if either A or B are true ◦ ! (not) !(condition) is true if condition is false, and false if condition is true This is called the logical complement or negation Example ◦ (salary < 1000) || (dependents > 5) ◦ (temperature > 30. 0) && (humidity > 90) ◦ !(temperature > 90. 0) 36

If-Else Syntax if ( Expression ) Statement. A else Statement. B NOTE: Statement. A and Statement. B each can be a single statement, a null statement, or a block. 3 7

Example: mail order Write a program to calculate the total price of a certain purchase. There is a discount and shipping cost: =The discount rate is 25% and the shipping is 10. 00 if purchase is over 100. =Otherwise, The discount rate is 15% and the shipping is 5. 00 pounds. 3 8

Note: These braces cannot be omitted if ( purchase > 100. 00 ) { discount. Rate =. 25 ; ship. Cost = 10. 00 ; } else { discount. Rate =. 15 ; ship. Cost = 5. 00 ; } total. Bill = purchase * (1. 0 - discount. Rate) + ship. Cost ;

Switch statement Used to select one of several alternatives l BASED on the value of a single variable. l This variable may be an int or a char but NOT a float ( or double). l 4 0

Example char grade ; printf(“Enter your letter grade: “); scanf(“%c”, &grade); switch ( grade ) { case ‘A’ : printf(“ Excellent Job”); break; case ‘B’ : printf ( “ Very Good “); break; case ‘C’ : printf(“ Not bad “); break; case ‘F’ : printf(“Failing”); break; default : printf(“ Wrong Input “); } 4 1

Example: Light bulbs Write a program to ask the user for the brightness of a light bulb (in Watts), and print out the expected lifetime: Brightness 25 40, 60 75, 100 otherwise Lifetime in hours 2500 1000 750 0

int bright ; printf(“Enter the bulb brightness: “); scanf(“%d”, &bright); switch ( bright ) { case 25 : printf(“ Expected Lifetime is 2500 hours”); break; case 40 : case 60 : printf ( “Expected Lifetime is 1000 hours “); break; case 75 : case 100 : printf(“Expected Lifetime is 750 hours “); break; default : printf(“Wrong Input “); }

Questions?
- Slides: 44