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 1432/1433 – Term 1

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

HUMAN & COMPUTER Variables in any programming language such as the human names in any speaking language. They are reserved words in any speaking language that can not be used as human names, and they are keywords in any programming language that can not be used as variables. -3 -

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 B. Subtopics Declaring Initializing Declaring & Initializing Assigning Numbers only Text Integer age = 36 Character gender = ‘M’ Double (Long Float) degree = 36. 4 String name =“DMG” The three data types showing are not all of the data types in C 4

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 the program Syntax type variable_list ; C. Example B. int id; double dollar; char gender; double tall, width, weight; Data Types Numbers only Text Integer (int) Character (char) Double (double) String Array 5

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 program Syntax variable = expression ; C. Example id = 0750428; dollar = 3. 75; gender = ‘M’; Expression could be a number or an equation 6

1 c Variables – Declaring & Initializing A. Introduction 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 the program Syntax type variable = expression ; C. Example B. int id = 0750428; double dollar = 3. 75; char gender = ‘M’; Expression could be a number or an equation 7

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

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 9

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 statements X 1. 2. 3. 4. 5. Y e p y T #3 Z 1 #1 #2 number of variables X Y #3 e p y T Type 3 is the most common because it is compressed Z 2 #1 #2 10

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 20 e p y T 2 20 The memory stores the last value of each variable 11

HUMAN & COMPUTER Constants in one program such as the fixed information in a period of time. For example, the currency rate in a program can be defined as a constant and uses the same rate for the entire program, while the currency rate in a day can be written as a fixed information and uses the same rate to exchange money during the entire day. -12 -

3 Constants A. Introduction Store a value under a name The value of the constant can not be changed during a program = You can not assign a new value Constants require one stage only, which is defining; it has to be at the begging of the program Syntax #define name value C. Examples B. #define id 0750428 #define dollar 3. 75 13

4 Output Operations and Functions Function: is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code. A. Introduction B. The output functions will help you to display any text or any value of a variable on the screen The output functions in C language is written in the file stdio. h, so you have to refer to this file if you want to use any of its functions Syntax printf (format string); printf (format string, print list); 14

4 Output Operations and Functions C. Examples 1. Write a statement to display Hello… on the screen? use the function printf(“Hello…”); 2. display Hello… in 1 st line and good in 2 nd line? use the function printf with the operation n printf(“Hello…ngood”); 3. display the value of the variable age; (if age is integer)? use the function printf with the operation %d printf(“%d”, age); Each standalone line of code is called an statement 15

4 Output Operations and Functions C. Examples 4. display the value of the variable X; (if X is doublefloat)? printf(“%f”, X); 5. display the value of the variable Y; (if Y is character)? printf(“%c”, Y); 6. display My age is then the value of the variable AGE? printf(“My age is %d”, AGE); 7. display the variables age and GPA in one statement? printf(“I am %d years old, GPA: %f”, age, GPA); Texts between the two quotations will be displayed except with % or 16

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); 17

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 The input functions in C language is written in the file stdio. h, so you have to refer to this file if you want to use any of its functions Syntax scanf (format string, input list); 18

5 Input Operations and Functions C. Examples 1. 2. 3. 4. Write a statement to get the value for the variable X; (if X is integer)? use the operation %d scanf(“%d”, &X); get the value for the variable X; (if X is double)? use the operation %lf (Long Float) and not %f scanf(“%lf”, &X); get the value for the variable X; (if X is character)? use the operation %c scanf(“%c”, &X); get 3 characters from the user? scanf(“%c%c%c”, &first, &second, &third); 19

5 Input Operations and Functions C. Examples 5. Write the statements to get the values of 2 variables and display them (with the declarations)? int i; double d; printf("Enter an integer: "); scanf("%d", &i); printf("Enter a double: "); scanf("%lf", &d); printf("You entered %d and %fn", i, d); 20

5 Input Operations and Functions 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); 21

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. C. 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 */ Example 1. 2. 3. 4. 5. 6. 7. /* Name: Daniyal ID: 707997 */ double miles, kms; /* EXECUTABLE STATMENTS */ printf(“Enter the distance: “); // ask the user scanf(“%lf”, &miles); // get the miles 22

HUMAN & COMPUTER Functions Each employee may assign for more than one job, but each of them has to have at least one main job. Each program may have more than one function, but each of them has to have at least one main function. -23 -

7 Writing Program Structure A. Any group of statements needs to be inside a function. (you will learn later more about functions) B. Be Ready to Write a Program 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); 8. } you have to declare the variables at the beginning of any function 24

7 Writing Program Structure C. Example 25

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

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

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 28

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 29

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); } 30

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

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 32

P 2 Problem Analysis Design Outline Implementation Testing Maintenance Getting User ID Input The user’s ID Output Formula This program is useless because it has no Output 33

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 The arrow means to store the input value into the following variable 34

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) 35

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) 36

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

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 38

P 3 Problem Analysis Design Outline Implementation Testing Maintenance Convert Miles to Kilometers Input Formula The distance in miles Kilometers = Miles x 1. 609 Output The distance in kilometers Algorithm helps programmers move from Input to Output using Formula 39

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 The arrow means to display the value of the following variable 40

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. /* 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); } 1. 609 is a constant value, so it can be defined within the constants They are 2 variables in the Design, so 2 variables need to be declared 41

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 !!! 42

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 !!! 43

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); /* 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); }

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

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 riyals and the changes in halala. SA Currency Coins: 1 riyal = 100 halala 1 half = 50 halala 1 quarter = 25 halala 1 ghirshan = 10 halala 1 ghirsh = 5 halala For example: 2 riyal + 10 half + 8 quarter + 1 ghirshan + 10 ghirsh = (2 x 100) + (10 x 50) + (8 x 25) + (1 x 10) + (10 x 5) = 960 halala = 9 riyals and 60 halala What are the Analysis and Design for this problem? 46

P 4 Problem Analysis Design Outline Implementation Testing Maintenance Finding the Value of the Coins Input Formula The count of (Riyal) The count of (Half) The count of (Quarter) The count of (Ghirshan) The count of (Ghirsh) 1 Riyal = 100 halala 1 Half = 50 halala 1 Quarter = 25 halala 1 Ghirshan = 10 halala 1 Ghirsh = 5 halala Output The value in riyals The change in halala 47

P 4 Problem Analysis Design Outline Implementation Testing Maintenance Finding the Value of the Coins 1. Get the count of the Riyal riyal 2. Get the count of the Half half 3. Get the count of the Quarter quarter 4. Get the count of the Ghirshan ghirshan 5. Get the count of the Ghirsh ghirsh 6. Compute the total value in Halala: total_halala = riyal x 100 + half x 50 + quarter x 25 + ghirshan x 10 + ghirsh x 5 7. Find the value in riyals and change: result_riyals = total_halala / 100 (integer only) result_change = total_halala % 100 8. Display the value in riyals result_riyals 9. Display the change result_change How many variables need to be declared? and what are their types? 48

P 4 Problem Analysis Design Outline Implementation Maintenance Testing 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 riyal, half, quarter, ghirshan, ghirsh; int result_change, result_riyals; int total_halala; /* /* /* 1. 2. 3. 4. 5. Get Get Get the the the count count of of of the the the (Riyal) */ (Half) */ (Quarter) */ (Ghirshan) */ (Ghirsh) */ /* 6. Compute the total value in halala */ /* 7. Find the value in riyals and change */ /* 8. Display the value in riyals */ /* 9. Display the change */ return(0); } /* input */ /* output */ /* process */

P 4 Problem Analysis Design Outline Implementation Maintenance Testing 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 riyal, half, quarter, ghirshan, ghirsh; int result_change, result_riyals; int total_halala; /* input */ /* output */ /* process */ /* 1 -5. Get the count of each type of the coins */ printf("Number of (Riyal): "); scanf("%d", &riyal); printf("Number of (Half): "); scanf("%d", &half); printf("Number of (Quarter): "); scanf("%d", &quarter); printf("Number of (Ghirshan): "); scanf("%d", &ghirshan); printf("Number of (Ghirsh): "); scanf("%d", &ghirsh);

P 4 Problem Analysis Design Outline Implementation Testing Maintenance Finding the Value of the Coins 1 Riyal = 100 halala 1 Half = 50 halala 1 Quarter = 25 halala 1 Ghirshan = 10 halala 1 Ghirsh = 5 halala 51

8 Changing the Display – A. Integer You can organize the display for integer variables. B. Formats: A. Value Format Displayed 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 52

8 Changing the Display – B. Double You can organize the display for double variables. B. Formats: A. Value Format Displayed 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 -3. 14159 %. 4 f -3. 1416 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 Hint: think about the displayed output first, then write the format 53

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 54

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 !!! 55

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

9 Types of Errors: Logic Error total_cents = 25* quarters + 1* 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 54 cents. Incorrect Output 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. Because the equation was not written right, the result was wrong Correct Output 57

10 Common Errors in In. /Out. Functions #include <stdio. h> int main (void) { int a=1, b=2, c=3; printf(“%d %d %d”, a, d, c); return(0); } SYNTAX ERROR: error C 2065: ‘d' : undeclared identifier #include <stdio. h> int main (void) { int d; scanf(“%d”, b); return(0); } SYNTAX ERROR: error C 2065: ‘b' : undeclared identifier #include <stdio. h> int main (void) { int a; printf(“%d”, a); return(0); } RUN-TIME ERROR: The variable ‘a’ is being used without being initialized 58

? 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 -59 we can declare any variable at anyplace inside a function

? Questions 3. Which statements have syntax errors: 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) -60 -

# 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. 61
- Slides: 61