Problem Solving and Program Design in C 5

Problem Solving and Program Design in C (5 th Edition) by Jeri R. Hanly and Elliot B. Koffman Chapter 2 (Input/Output Functions) © CPCS 202 12 -10 -1429

# CHAPTER 2 – Input/Output Functions 1. 2. 3. 4. 5. 6. 7. 8. 9. 1. Variables 2. Constants Output Operations and Functions 3. Input Operations and Functions 4. Using Comments Design / Algorithm Types Writing Program Structure Changing the Display Types of Errors Hello World Getting User ID Convert Miles to Kilometers Finding the Value of the Coins column shows the topics index. column shows the programs index. 2

1 Variables ( )ﻣﺘﻐﻴﺮ A. Introduction Store values in the memory under given names; these values can be changed The types of the possible values called Data Types Choose good names for the variables Data Types Variables are case sensitive Don’t use a Reserved Word Character B. Subtopics Declaring Initializing Declaring & Initializing Assigning Numbers only gender = ‘M’ Integer age = 36 Double Float degree = 36. 4 The three data types showing are not all of the data types in C 3

1 a Variables – Declaring A. Introduction Each variable needs to be declared before using it Declaring a variable reserves space in the memory Declaring variables has to be at the beginning of functions (before writing any statement) Data Syntax type variable_list ; C. Example B. int id; double dollar; char gender; double tall, width, weight; Types Numbers only Character (char) Integer (int) Double (double) 4

1 b Variables – Initializing A. Introduction B. The first value for a variable called initialing a variable You can not use a variable without initializing You can initial a variable at any place inside the function Syntax variable = expression ; C. Example id = 0750428; dollar = 3. 75; gender = ‘M’; Expression could be a number or an equation 5

1 c Variables – Declaring & Initializing A. Introduction B. You can save the space and the time by initializing a variable in the same time with declaring it Again, this has to be at the beginning of functions before writing any statement Syntax type variable = expression ; C. Example int id = 0750428; double dollar = 3. 75; char gender = ‘M’; Expression could be a number or an equation 6

1 d Variables – Assigning A. Introduction B. Changing the value of a variable called assigning a new value to the variable Syntax variable = expression ; C. Example id = 0750999; dollar = 3. 77; gender = ‘F’; Expression could be a number or an equation 7

1 Variables double dollar; char gender = ‘d’; id = 0750428; dollar = 3. 75; age = 21; dollar = 3. 77; Assigning int id, age; Initializing Declaring & Assigning C. Conclusion 8

2 Tracking Variables in the Memory A. Introduction You can track the values of each variable in a table B. Prototype You can show the effect of each statement on the memory or show only the effects on the variables. number of variables number of statements X 1. 2. 3. 4. 5. Y e p y T Z 1 #1 #2 #3 The memory stores the last value of each variable number of variables X Y #3 e p y T Z 2 #1 #2 9

2 Tracking Variables in the Memory C. Example Track the memory of the following program segment: 1. 2. 3. 4. 5. 6. 7. X Z Y Y Z Z X = = = = 10; 15. 5; X + Z; Y + 1; Y – 1. 5 + 5; Z / 2 + 5; Z % 3; # X 1. 10 2. Y Z 1 6. e p y T 7. 2 X Y Z 25. 5 15. 5 26. 5 30 3. 4. 5. 10 2 15. 5 26. 5 30. 0 20. 0 e p y T 2 20 10

3 Constants ( )ﺛﺎﺑﺖ A. Introduction B. Store a value under a name The value of the constant can’t be changed = You can’t assign a new value Constants require one stage only, which is defining; it has to be at the begging of the program before writing ant function Syntax #define name value C. Examples #define id 0750428 #define dollar 3. 75 11

4 Output Operations and Functions A. Introduction B. The output operations and functions will help you to display anything on the screen. You can display some text only, a value of a variable only, or both. In C language, you need to include the file stdio in order to use the function printf. Syntax printf (format string); printf (format string, print list); 12

4 Output Operations and Functions C. Examples 1. Display Hello… on the screen in C? use the function printf(“Hello…”); 2. Display Hello… in 1 st line and good in 2 nd line? use the operation n printf(“Hello…ngood”); 3. Display the value of the variable age; (if age is integer)? use the operation %d printf(“%d”, age); 13

4 Output Operations and Functions C. Examples 4. Display the value of the variable X; (if X is doublefloat)? use the operation %f printf(“%f”, X); 5. Display the value of the variable Y; (if Y is character)? use the operation %c printf(“%c”, Y); Display My age is then the value of the variable AGE? printf(“My age is %d”, AGE); 6. 7. Display the variables age and GPA in one statement? printf(“I am %d years old, GPA: %f”, age, GPA); 14

4 Output Operations and Functions D. Conclusion The output operations and functions will help you to display text and/or the values of a group of variables on the screen. For examples: printf(“Enter the object mass in grams? ”); printf(“%c”, first_init); printf(“I am %d years old. ”, AGE); 15

5 Input Operations and Functions A. Introduction B. The input operations and functions will help you to get values for the variables from users. You need to ask the user to input a value using the output function, then you can use the input function to get the value from the user. In C language, you need to include the file stdio in order to use the function scanf. Syntax scanf (format string, input list); 16

5 Input Operations and Functions C. Examples 1. Get the value for the variable X; (if X is integer)? use the operation %d scanf(“%d”, &X); 2. Get the value for the variable X; (if X is doublefloat)? use the operation %lf (Long Float) and not %f scanf(“%lf”, &X); 3. Get the value for the variable X; (if X is character)? use the operation %c scanf(“%c”, &X); 17

5 Input Operations and Functions C. Examples Get 3 characters from the user? scanf(“%c%c%c”, &first, &second, &third); 4. D. Conclusion The input operations and functions will help you to get a value for a declared variable from the user. For examples: scanf(“%c%d”, &first_initial, &age); 18

6 Using Comments With your comments, it will easy to remember the job of each statement in your program. B. Comment Types in C language: A. Single-line: Start with the symbol // and end up with the end of the line Single-line or Multi-lines: Start with /* and end up with */ C. Example 1. /* Name: Daniyal 2. 3. 4. 5. 6. 7. ID: 707997 */ double miles, kms; /* EXECUTABLE STATMENTS */ printf(“Enter the distance: “); scanf(“%lf”, &miles); // ask the user // get the miles 19

7 Writing Program Structure A. Any group of statements needs to be inside a function B. Be Ready to Write a Program Note: you will learn later more about functions Hint: a function start with { and end up with } The main function will be executed first 1. /* First, include the header files for external functions, such as input/output functions */ 2. /* Second, define Constants */ 3. int main (void) 4. { 5. /* Start with declaring the variables */ 6. /* Then, write the other statements */ 7. return (0); } you have to declare the variables at the beginning of any function 8. 20

7 Writing Program Structure C. Example 21

P 1 Problem Analysis Design Outline Implementation Testing Maintenance Hello World We need a program that displays on the screen the text Hello World!! 22

P 1 Problem Analysis Design Outline Implementation Testing Maintenance Hello World Input Output the text “Hello World!!” Formula 23

P 1 Problem Analysis Design Outline Implementation Testing Maintenance Hello World 1. Display “Hello World!!” on the screen Algorithm helps programmers move from Input to Output using Formula 24

P 1 Problem Analysis Design Outline Implementation Testing Maintenance Hello World 1. 2. 3. 4. 5. 6. 7. 8. 9. #include <stdio. h> int main(void) { // 1. Display “Hello World!!” on the screen return(0); } Outline has the declaration of the functions and the variables ONLY 25

P 1 Problem Analysis Design Outline Implementation Testing Maintenance Hello World 1. 2. 3. 4. 5. 6. 7. 8. 9. #include <stdio. h> int main(void) { // 1. Display “Hello World!!” on the screen printf("Hello World!!n"); return(0); } 26

P 1 Problem Analysis Design Outline Implementation Testing Maintenance Hello World 27

P 2 Problem Analysis Design Outline Implementation Testing Maintenance Getting User ID Write a program that gets the ID value from the user This program is useless because it has no Output 28

P 2 Problem Analysis Design Outline Implementation Testing Maintenance Getting User ID Input ID Output Formula This program is useless because it has no Output 29

P 2 Problem Analysis Design Outline Implementation Testing Maintenance Getting User ID 1. Get the ID from the user_ID Put the value you get from the user into a variable called user_ID Number of variables = 1 This indicates that you need to declare 1 variable in the program This program is useless because it has no Output 30

P 2 Problem Analysis Design Outline Implementation Testing Maintenance Getting User ID 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. #include <stdio. h> int main(void) { int user_ID; // 1. Get the ID from the user return(0); } DON’T try to get a value from a user (scanf) without asking (printf) 31

P 2 Problem Analysis Design Outline Implementation Testing Maintenance Getting User ID 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. #include <stdio. h> int main(void) { int user_ID; // 1. Get the ID from the user printf("Please enter your user ID: "); scanf("%d", &user_ID); return(0); } DON’T try to get a value from a user (scanf) without asking (printf) 32

P 2 Problem Analysis Design Outline Implementation Testing Maintenance Getting User ID Try more than one test case in the testing step 33

P 3 Problem Analysis Design Outline Implementation Testing Maintenance Convert Miles to Kilometers Your summer surveying job requires you to study some maps that give distances in kilometers and some that use miles. You and your coworkers prefer to deal in metric measurements. Write a program that performs the necessary conversion. Each miles equal to 1. 609 kilometer. Miles Kilometer 34

P 3 Problem Analysis Design Outline Implementation Testing Maintenance Convert Miles to Kilometers Input Formula Miles Kilometers = Miles x 1. 609 Output Kilometers 1. 609 is a constant value, so it can be defined within the constants Algorithm helps programmers move from Input to Output using Formula 35

P 3 Problem Analysis Design Outline Implementation Testing Maintenance Convert Miles to Kilometers 1. Get the number of miles from the user miles 2. Convert miles to kilometers: kms = miles x 1. 609 3. Display the number of kilometers kms 1. 609 is a constant value, so it can be defined within the constants Algorithm helps programmers move from Input to Output using Formula 36

P 2 Problem Analysis Design Outline Implementation Testing Maintenance Convert Miles to Kilometers 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. /* Converts distances from miles to kilometers. */ #include <stdio. h> /* printf, scanf definitions */ #define KMS_PER_MILE 1. 609 /* conversion constant */ int main(void) { double miles, /* distance in miles kms; /* equivalent distance in kilometers */ */ /* 1. Get the number of miles from the user */ /* 2. Convert miles to kilometers */ /* 3. Display the number of kilometers */ return (0); } They are 2 variables in the Design, so 2 variables need to be declared 37

P 3 Problem Analysis Design Outline Implementation Testing Maintenance Convert Miles to Kilometers 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. #include <stdio. h> /* printf, scanf definitions */ #define KMS_PER_MILE 1. 609 /* conversion constant */ int main(void) { double miles, /* distance in miles kms; /* equivalent distance in kilometers */ */ /* 1. Get the number of miles from the user */ scanf("%lf", &miles); printf("The distance in miles is %f. n", miles); /* 2. Convert miles to kilometers */ kms = KMS_PER_MILE * miles; /* 3. Display the number of kilometers */ printf("That equals %f kilometers. n", kms); return (0); } The program has a mistake that may confuse users !!! 38

Problem Analysis Design Outline Implementation Testing Maintenance Test Case 2 Test Case 1 Convert Miles to Kilometers Test Case 3 P 3 The program has a mistake that may confuse users !!! 39

P 3 Problem Analysis Design Outline Implementation Testing Maintenance Convert Miles to Kilometers 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. /* Converts distances from miles to kilometers. */ #include <stdio. h> /* printf, scanf definitions */ #define KMS_PER_MILE 1. 609 /* conversion constant */ int main(void) { double miles, /* distance in miles kms; /* equivalent distance in kilometers */ */ /* 1. Get the number of miles from the user */ printf("Please enter the value of distance in miles : "); scanf("%lf", &miles); printf("The distance in miles is %f. n", miles); /* 2. Convert miles to kilometers */ kms = KMS_PER_MILE * miles; /* 3. Display the number of kilometers */ printf("That equals %f kilometers. n", kms); return (0); } 40

Problem Analysis Design Outline Implementation Testing Maintenance Test Case 2 Test Case 1 Convert Miles to Kilometers Test Case 3 P 3 41

P 4 Problem Analysis Design Outline Implementation Testing Maintenance Finding the Value of the Coins We need a program that calculates the number of coins in a save box, and it displays the number of the dollars and the changes in cents. USA Currency Coins: 1 quarter = 25 cents 1 dime = 10 cents 1 nickel = 5 cents 1 penny = 1 cent For example: 10 quarters + 8 dimes + 1 nickels + 10 pennies = (10 x 25) + (8 x 10) + (1 x 5) + (10 x 1) = 345 cents = 3 dollars and 45 cents Quiz: Show the Analysis & Design for this problem? 42

P 4 Problem Analysis Design Outline Implementation Testing Maintenance Finding the Value of the Coins Input Formula The count of quarters The count of dimes The count of nickels The count of pennies 1 quarter = 25 cents 1 dime = 10 cents 1 nickel = 5 cents 1 penny = 1 cent Output The value in dollars The changes in cents 43

P 4 Problem Analysis Design Outline Implementation Testing Maintenance Finding the Value of the Coins 1. Get the count of the quarters 2. Get the count of the dimes 3. Get the count of the nickels 4. Get the count of the pennies 5. Compute the total value in cents: total_cents = quarters x 25 + dimes x 10 + nickels x 5 + pennies x 1 6. Find the value in dollars and change: dollars = total_cents / 100 (without the float) change = total_cents % 100 7. Display the value in dollars 8. Display the change How many variables need to be declared? and what are their types? 44

P 4 Problem Analysis Design Implementation Outline Testing Maintenance Finding the Value of the Coins 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. /* Determines the value of a collecting of coins. */ #include <stdio. h> int main(void) { int pennies, nickels; int dimes, quarters; int change; int dollars; int total_cents; /* /* 1. 2. 3. 4. 5. 6. 7. 8. input - count of each coin type */ output - change amount */ output - dollar amount */ total cents */ Get the count of the quarters */ Get the count of the dimes */ Get the count of the nickels */ Get the count of the pennies */ Compute the total value in cents. */ Find the value in dollars and change. */ Display the value in dollars. */ Display the change. */ return(0); } /* /* /* 45

P 4 Problem Analysis Design Implementation Outline Testing Maintenance Finding the Value of the Coins 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. /* * Determines the value of a collecting of coins. */ #include <stdio. h> int main(void) { int pennies, nickels; int dimes, quarters; int change; int dollars; int total_cents; /* /* /* input- count of each coin type */ output- change amount */ output- dollar amount */ total cents */ /* 1. Get the count of the quarters */ printf("Number of quarters> "); scanf("%d", &quarters); /* 2. Get the count of the dimes */ printf("Number of dimes> "); scanf("%d", &dimes); 46

P 4 Problem Analysis Design Outline Implementation Testing Maintenance Finding the Value of the Coins 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. /* 3. Get the count of the nickels */ printf("Number of nickels> "); scanf("%d", &nickels); /* 4. Get the count of the pennies */ printf("Number of pennies> "); scanf("%d", &pennies); 1 dollar = 100 cents 1 quarter = 25 cents 1 dime = 10 cents 1 nickel = 5 cents 1 penny = 1 cent /* 5. Compute the total value in cents. */ total_cents = 25 * quarters + 10 * dimes + 5 * nickels + pennies; /* 6. Find the value in dollars and change. */ You need to declare “dollars” as dollars = total_cents / 100; integer to get the left value change = total_cents % 100; /* 7. Display the value in dollars. 8. Display the change. */ printf("n. Your coins are worth %d dollars and %d cents. n", dollars, change); 41. 42. 43. } return(0); 47

P 4 Problem Analysis Design Outline Implementation Testing Maintenance Finding the Value of the Coins 1 dollar = 100 cents 1 quarter = 25 cents 1 dime = 10 cents 1 nickel = 5 cents 1 penny = 1 cent 48

8 Changing the Display – A. Integer You can organize the display for integer variables. B. Formats: A. Value Format Displaye d Output C. Example: 1. 234 %4 d ▒ 234 %5 d ▒▒ 234 3. 234 %6 d ▒▒▒ 234 5. 234 %1 d 234 -234 %4 d -234 %5 d ▒-234 %6 d ▒▒-234 %2 d -234 2. 4. printf(“ X Yn”); printf(“-----n”); printf(“%4 d%4 dn”, 1, 2); printf(“%4 d%4 dn”, 13, 6); printf(“%4 d%4 dn”, 37, 513); Run: X Y ----1 2 13 6 37 513 49

8 Changing the Display – B. Double You can organize the display for double variables. B. Formats: A. Value Format Displaye d Output C. Example: 1. 3. 14159 %5. 2 f ▒ 3. 14159 %3. 2 f 3. 14159 %5. 3 f 3. 142 4. 3. 14159 %5. 1 f ▒▒ 3. 1 5. 0. 1234 %4. 2 f 0. 12 -0. 006 %8. 3 f ▒▒-0. 006 %4. 2 f -0. 01 -0. 006 %8. 5 f -0. 00600 2. 6. 7. double X, Y, Z; X = 10. 23; Y = 102. 235; Z = 20. 2; printf(“%6. 2 fn”, X); printf(“%6. 2 fn”, Y); printf(“%6. 2 fn”, Z); Run: 10. 23 102. 24 20. 20 %. 4 f -3. 1416 3. 14159 Hint: think about the displayed output first, then write the format 50

9 Types of Errors • The program will not run until the error fixed. • e. g. missing a semicolon. 1. Syntax Error 2. Run-time Error • Discovered while the program running. • e. g. dividing a number by zero • The result is not correct. • e. g. to find the sum of X and Y, the equation is X/Y 3. Logic Error 51

9 Types of Errors: Syntax Error. 1. A pop-up window will appear. CHOSE No to stop the program. 3. Fix the error . 2. Check the error message and the line number Sometimes the “error line number” shows a line after the real line !!! 52

9 Types of Errors: Run-Times Error Check the cause of the pop-up error message? 53

9 Types of Errors: Logic Error Number of quarters> 10 Number of dimes> 2 Number of nickels> 0 Number of pennies> 2 Your coins are worth 2 dollars and 54 cents. Incorrect Output total_cents = 25* quarters + 1* dimes + 5 * nickels + pennies total_cents = 25* quarters + 10* dimes + 5 * nickels + pennies Number of quarters> 10 Number of dimes> 2 Number of nickels> 0 Number of pennies> 2 Your coins are worth 2 dollars and 72 cents. Correct Output Because the equation was not written right, the result was wrong 54

? Questions 1. The main different between the variables and the constants in a program is: a) b) c) d) 2. the value of the constant can be changed during the program the value of the variable can be changed during the program there is no difference between them none of the above is a correct statement The codes at any function written in C language need to follow the following order: a) b) c) first, we write the executed statements. Then, we declare the variables first, we declare the variables. Then, we write the executed statements -55 we can declare any variable at anyplace inside a function

? Questions 3. Which of the following statements have a syntax error: X = 10; b) Y = 20 c) Z = 15. 5; d) Y = X + Z; e) Y = Y + 1; f) Z = Y – 1. 5 + 5; g) 23. 2 = Z; h) scanf(“%d”, x); i) printf(“%d”, x); j) scanf(“%f”, &z); k) printf(“%f”, z); a) -56 -

hw Evaluation Homework 1. Track the memory in Program 4 ? (You need to show the code, the output of one test case, and tracking the memory in ONE page only; you can choose any input values) HANDWRITING IN THE HOMEWORK IS NOT ACCEPTABLE -57 -

# CHAPTER 2 – Input/Output Functions 1. 2. 3. 4. 5. 6. 7. 8. 9. 1. Variables 2. Constants Output Operations and Functions 3. Input Operations and Functions 4. Using Comments Design / Algorithm Types Writing Program Structure Changing the Display Types of Errors Hello World Getting User ID Convert Miles to Kilometers Finding the Value of the Coins column shows the topics index. column shows the programs index. 58
- Slides: 58