1 / 54

Beginning Concepts for Problem Solving in C: variables, data types, operators, and formatted IO

Learn about data in programming, variables, constants, data types, operators, and writing C programs in ChIDE. Understand the importance of data types and practice basic C programming concepts. Enhance your problem-solving skills through hands-on exercises and examples.

wolff
Download Presentation

Beginning Concepts for Problem Solving in C: variables, data types, operators, and formatted IO

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Beginning Concepts for Problem Solving in C: variables, data types, operators, and formatted IO BJ Furman 30JAN2010

  2. The Plan for Today • The concept of data • Constants vs. variables • Variables • naming rules • data types • Operators and their precedence • Practice writing and executing C programs in ChIDE

  3. Learning Objectives Following completion of today’s lab, you should be able to: • List and explain the basic kinds of data • Distinguish between variables and constants • Declare integer, floating point, and character variables • List the basic data types used in C • Identify and explain commonly used operators in C • Use C operators correctly according to their placement in the hierarchy chart • Write and execute simple C programs in ChIDE • Set up and evaluate expressions and equations using variables, constants, operators, and hierarchy of operations

  4. What and Why? • Data => pieces of information we deal with in the problem solving process • Why is it important to know about data types? • Need to know about data types to effectively use a programming language • It’s all just bits the lowest level! • What would you rather work with… int i; float r; i = 3; r = cos(2*i*PI); • or… 00000010 10000000 00000000 00000110 10000010 10000000 01111111 11111100 11001010 00000001 00000000 00000000 etc.

  5. Kinds of Data (simplified view)  • The basic kinds of data that we will mostly use: • Numeric • Integers: • Real (floating point) numbers: • Character (are enclosed by single quotes in C) • All letters, numbers, and special symbols • Ex. ‘A’, ‘+’, ‘5’ • String (are enclosed by double quotes in C) • Are combinations of more than one character • Ex. “programming”, “ME 30” • Logical (also called ‘Boolean’ named after George Boole an English mathematician from the early 1800’s) • True or False (1 or 0)

  6. Kinds of Data - Practice If kind is ‘numeric’, then is it an integer or a floating point number?

  7. Constants and Variables • Constant • A data element that never changes in your program • 5, 62.37, 4.219E-6, “record_string”, ‘$’ • i = j + 7; /* which one is the constant? */ • first_letter = ‘a’; /* which one is the constant? */ • Variable • A data element that can take on different values • Its name represents a location (address) in memory  • i = j + 7; /* which are variables? */ • second_letter = ‘b’; /* which is the variable? */ • Values are ‘assigned’ using a single equal sign ( = ) • Read the statement: i = j + 7; NOTE!! Variables in C must be ‘declared’ before they can be used!

  8. Declaring Variables and Data Types • Variables must be declared before they can be used • Gives info to the compiler about: • How many bytes of memory to set aside  • How to interpret the bytes (data) • Example: int my_var; /* an integer variable my_var */ float sensor1; /* a float variable sensor1 */ char Letter01_a; /* a char variable Letter01_a */ • Two parts are needed in the declaration: • Data type designator (e.g., int), (note, a ‘reserved word’) • Identifier (i.e., a name: my_var), must be a valid identifier

  9. Variable Names • See the handout, ‘Notes on Variable Names’ • Sequence of lower and/or upper case letters, digits, and underscores • Case sensitive! ex: my_num is not the same as My_num • Initial character may not be a digit • May not use reserved words as identifiers  • Keep length to 31 or fewer characters • Make the first 8 characters unique • Avoid names used by run-time libraries (e.g., log, which is used in math.h) • Avoid using names beginning with underscores • Try to use lowercase letters for variable names, and UPPER CASE letters for macro names (e.g., #define PI 3.14159) • Choose names that are meaningful (e.g., light_level instead of just output)

  10. Variable Naming - Practice

  11. Data Types and Memory • Recall that declaring a variable • sets aside memory and • indicates the type of data that will be stored • Considerations in declarations • What kind of data will you be working with? • Just whole numbers? Fractions? Characters? • Is speed important? • Integer operations are fastest • How much memory is available? • Important for embedded systems and microcontrollers • What is the range of the data? • From 0 to n, or from –n to +n, etc. • What kind of precision do you need? • Precision  number of decimal places

  12. Data Types void Scalar Types Aggregate Types arrays structs unions Pointers Arithmetic Types enum Integral Types Floating Types float double long double unsigned signed char short int long long long Hierarchy of Data Types (adapted from Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3rd ed., Springer, New York.)

  13. Memory Allocation for Arithmetic Data Types (See the handout, “Notes on Data Types”)

  14. Declaration Practice • Declare the following variables: • A character variable named PORTA that will hold only non-negative numbers • A variable named up_down that will hold whole numbers ranging from -20,000 to 20,000 • A variable named heat that will hold values from -20.0 to 350.0 • A variable named max_read that needs 8 decimal digits of precision For each variable declared, comment on the number of bytes of memory needed and the data range it will cover

  15. Operators • Operator: a symbol (or combination of symbols) used to combine variables and constants to produce a value(Overland, B. (1995) C in plain English, MIS Press, New York.) • The variables and constants that get combined are called ‘operands’ • How the combining is carried out depends on the precedence and associativity of the operator • Example – identify the operator(s), operands, and results on each line: int i, j = 3; i = j + 7;

  16. Operator Precedenceand Associativity • All operators have the properties of precedence and associativity. • Precedence has to do with which operations take priority in groupings of operands around adjacent operators • Associativity has to do with which operations take priority when the operators in an expression have the same precedence • Use parentheses () to specify a particular grouping order and to make expressions more readable

  17. Operator Practice • Identify the operators, operands, and results on each line int i, count, mult, mult2=1, total_sum; float total_percentage; i = 1; mult = total_sum = i; count = i + 1; count = count + 1; total_percentage = total_sum / 100; /* a little tricky! */ mult1 = count * 17.23; count += 1; mult2 *= 2;

  18. Arithmetic with Mixed Data Types • Fundamentally, the computer is not able to arithmetically combine data of different types • Arithmetic with integers  integer results • int div_int = 8 / 5; /* what is div_int? */ • Arithmetic with floating point data  floating point results • float div_flt = 8.0 / 5.0; /* what is div_flt? */ • Arithmetic with integers and floating point values in the same expressions  ?? • int div_int = 8.0 / 5; /* what is div_int? */ • float div_flt = 8.0 / 5; /* what is div_flt? */

  19. Implicit Type Casting Higher • In binary operations (e.g., +, -, /, etc.) with operands of mixed data types, the resultant data type will take the higher order data type of the two operands1 Lower 1Cheng, Harry H. (2010). C for Engineers and Scientists: An Interpretive Approach, McGraw-Hill, New York.

  20. Expressions and Statements • Expression • Any combination of operators, numbers, and names that evaluates to a single value • 5 • j = 17 • j = i = 10 • i + j • Statement • A chunk of code that does something (executes) • Terminating an expression with a semicolon (;) turns it into a statement • We will cover other statements later

  21. Getting Started with Ch and ChIDE BJ Furman 11JUL2009

  22. What is Ch? • an embeddable C/C++ interpreter for cross-platform scripting, shell programming, 2D/3D plotting, numerical computing, and embedded scripting • Developed by Prof. H. Cheng at UC Davis • Interpreter vs. compiler • Executes expressions and statements immediately rather than having to construct a complete program and go through compile/link/execute/debug cycles • Superset of C • Supports all features of ISO 1990 C Standard (C90) and major features of C99 • Lots more features!

  23. More Information on Ch • See The Ch Language Environment, ver. 6.1 User’s Guide • Available from: http://www.softintegration.com

  24. Starting up Ch • Ch command shell and ChIDE • Ch command shell can be invoked from the Ch icon • Can interactively execute C programs, functions, statements, and expressions • ChIDE can be invoked from the ChIDE icon • Can easily access the Ch command shell from within ChIDE • Can easily invoke a 3rd party compiler (e.g., MS Visual C++ Express)

  25. Ch command shell

  26. ChIDE Click on the Ch icon to launch a Ch shell window

  27. Laboratory Exercises • Work individually unless not enough computers • Take turns at the keyboard if you have to work with a partner • Open ChIDE and launch a Ch shell window • Open a new window in ChIDE • File | New or Ctrl-N • Follow the instructions on the Lab Project #1 guide sheet • Fill out the worksheets • Complete the cover page • Description is especially important • In your own words, not plagiarized • Save your work on a personal storage device before you leave

  28. Formatted Output BJ Furman 16JUL2009

  29. Formatted Output • We use the printf function (stands for ‘print-formatted) to display text and numeric information to the screen • printf is available by including the Standard IO library, stdio.h (more on this later) • Ch already “knows” about printf, so it is not necessary to include stdio.h • Ex. Print a line of text printf("Hello ME 30!!");

  30. printf() – a closer look • General form: • printf(“control string”, arg1, arg2,…); • Control string • A string enclosed in double quotes that controls the conversion and formatting of zero or more arguments • Arguments are expressions that the function printf acts on • Inside the control string will often be conversion specifications and modifiers that specify how the data from the arguments is to be converted into displayable form • Escape sequences (a \ followed by a letter or combination of digits)) are also used to control the position of the cursor and/or provide literal representations of non-printing or special characters • Ex. Try this in ChIDE printf("printf example:\n 1+1=%d\n", 1+1);

  31. Conversion Specifications (partial list) Adapted from: http://www.eecs.umich.edu/~bartlett/printf.html

  32. Escape Sequences (partial list) http://msdn.microsoft.com/en-us/library/h21280bw(VS.80).aspx

  33. Conversion Specification Flags • Optional format modifiers that may come before the conversion character (Darnell & Margolis, 1996)

  34. Field Width Specification • Optional specification of minimum number of characters to output • Will pad to the right or left to fill specified width if data requires fewer characters • Default is pad on the left (i.e., RIGHT justify), but can specify right pad (i.e., LEFT justify) with the left adjustment flag (the minus sign)

  35. Precision Specification • Signified by a period followed by a decimal constant (e.g., %5.2f) • Floating point values • Specifies the number of digits to appear after the decimal point • Will round if actual value exceeds the specified precision • Integer values • Same meaning as field width specifier, but overrides it. Will pad the field with zeros on the left until the precision length is reached

  36. Short and Long Specifiers • Data conversions take place when arguments are passed to the printf function • Integers are converted to int • Floating point to double • To ensure arguments are cast back to their original types, use short and long specifiers

  37. Practice - operator precedence • On paper, determine output of: int i, j = 3; i = j + 7; i = j / 12 + 5; int k = (j + i * 3); printf(“%d, %d, %d”, i, j, k); • Output:

  38. Practice - operator precedence solution • Program Trace: int i, j = 3; /* j = 3 */ i = j + 7; /* i = 3+7 = 10 */ i = j / 12 + 5; /* i = (3/12)+5 = 9 */ int k = (j + i * 3); /* k=3+27=30 */ printf(“%d, %d, %d”, i, j, k); • Output: 9, 3, 30

  39. Formatted input BJ Furman 18JUL2009

  40. scanf() function (just a brief treatment!) • scanf() is like the reverse of printf • It reads data entered via the keyboard • Similarities to printf(): • Needs a format string first • Many common format specifiers, which indicate the type of data expected from the keyboard • Which must match the data arguments • Any number of data arguments • Differences from printf(): • Data argument identifiers must be preceded with an ampersand (&) • The & ahead of the variable signifies the address in memory where the data will be stored (its a pointer to the variable) • Beware!!! Forgetting the & is a common error.

  41. scanf() function, cont. Darnell & Margolis (1996) • Differences from printf(), cont.: • Characters other than a conversion string, a space, a newline character, or a vertical tab must match characters in the input stream • A space, horizontal tab, or newline character in the format string causes scanf() to skip over leading white space up to the next nonspace character scanf(“Distance= %lf", &num1); • Will skip leading spaces before the value num1 • Must find a match to the string literal, Distance= (or else it will stop reading the input and will return the number of successful conversions that were stored (try entering a space before typing Distance=)

  42. scanf example 1 • Prompt the user for a integer, and store it in an integer variable named num1 int num1; printf("Enter an integer > "); scanf("%d", &num1); printf("The value you entered is %d\n", num1);

  43. scanf example 2 • Prompt the user for a floating point value, and store it in an floating point variable of type double named dbl_num2 double dbl_num2; printf("Enter a floating point number > "); scanf("%lf", &dbl_num2); printf("The value you entered is %G\n", dbl_num2);

  44. Anatomy of a C program BJ Furman 18JUL2009

  45. Burford Furman Professor Dept. of Mech. and Aero. Eng San José State University San Jose, CA 95192-0087 July 20, 2009 Dear Prof. Furman, I’m writing you to see if I can get into ME 30… … Sincerely, Jane Student Title block Date Salutation Body Closing Signature Structured Programming • A formal letter has a structure • So does a program in C

  46. Essential Program Structure • /* Programmer’s Block */Description and documentation of the program • #include directives Compiler instructions to access to a library • #define directives Compiler instructions for replacement macro • global variable declarations Declaration of variables with global scope • global function declarations Declaration of functions with global scope • int main() Calling of the function ‘main’ • { • variable declarations Declaration of variables with local scope • function declarations Declaration of functions with local scope • variable initializations Initialization of local variables • statements Statements forming the core of the program • return 0; Value to return when main() completes • } • /* function definitions */ • function name(parameter list) Header of function (i.e., name and parameters) • { • statements Statements forming the core of the function • }

  47. A C program (Fig. 2.1 in H&K, p. 47) /* 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, kms; /* miles->dist. in miles, kms-> equiv. distance in kms */ /* Get the distance in miles. */ printf("Enter the distance in miles> "); scanf(“%lf", &miles); /* Convert the distance to kilometers. */ kms = KMS_PER_MILE * miles; /* Display the distance in kilometers. */ printf("That equals %f kilometers.\n", kms); return (0); }

  48. A C programAnnotated(Fig. 2.1 in H&K, p. 47)

  49. References • Darnell, P. A. & Margolis, P. E. (1996) C, a software engineering approach, 3rd ed., Springer, New York.

  50. Extra Items

More Related