1 / 27

Variables in C

Variables in C. Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading Sections 2.3 - 2.4. Preprocessor. All preprocessor directives (preprocessor commands) begin with “ # ”.

timothyryan
Télécharger la présentation

Variables in C

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. Variables in C Topics • Naming Variables • Declaring Variables • Using Variables • The Assignment Statement Reading • Sections 2.3 - 2.4

  2. Preprocessor • All preprocessor directives (preprocessor commands) begin with “# ”. • The preprocessor reads and may change source in RAM before a program is compiled. But the source code as stored on disk is not modified. Possible actions: • Include other files to be included in your C code. • Performs various text replacements. • Strips comments and whitespace from the code. • For example: • #include <stdio.h> The preprocessor inserts the contents of the stdio.h at this place in your code. “<…>” means the file is located in the standard include file directory. • #define PI 3.14159The preprocessor replace every occurrence of PI with 3.14159 before it passes the file to the compiler.

  3. Output Data on Screen • Use printf statement – a function call • To prompt user that the program is waiting for input data. Printf(“Enter number of exams: \n”); • Arguments to the function (format string and variables) are listed inside parentheses “()”. • Multiple arguments are separated by commas: “,”. • “\n” denotes a newline. • To output results to user on the screen. Printf(“Your grade is %d\n”, grade);

  4. Input Data into Variables • The scanf function can be used to obtain input data from a user (usually from keyboard) or input file. • scanf ignores leading whitespace, i.e. • Tabs • Spaces • <Enter> or <Return> key • scanf (“%d”, &numExams); • Take user’s input and put it in the memory location of numExams. • First argument: Format control string: type of input data • %d decimal integer • %f floating number • %s string • The second argument: the memory location (address) of numExams. The “&” symbol is the address operator.

  5. Naming Variables • Variable names in C • May only consist of letters, digits, and underscores. • May be as long as you like, but only the first 31 characters are significant • May not begin with a number. • May only begin with letters or underscores. • May not be a C reserved word (keyword).

  6. Reserved Words (Keywords) in C • auto break • case char • const continue • default do • double else • enum extern • float for • goto if • int long • register return • short signed • sizeof static • struct switch • typedef union • unsigned void • volatile while

  7. Naming Conventions • C programmers generally agree on the following conventions for naming variables. • Begin variable names with lowercase letters • Use meaningful identifiers • Separate “words” within identifiers with underscores or mixed upper and lower case. • Examples: surfaceArea surface_Area surface_area • Be consistent!

  8. Naming Conventions (con’t) • Use all uppercase for symbolic constants (used in #define preprocessor directives). • Examples: • #define PI 3.14159 • #define AGE 18

  9. Case Sensitivity • C is case sensitive • It matters whether an identifier, such as a variable name, is uppercase or lowercase. • Example: area Area AREA ArEa are all seen as different variables by the compiler.

  10. Which Are Not Legal Identifiers? • AREA area_under_the_curve • 3D num45 • Last-Chance #values • x_yt3 pi • num$ %done • lucky***

  11. Declaring Variables • Before using a variable, you must give the compiler some information about the variable; i.e., you must declare it. • The declaration statement includes the data type of the variable followed by variable name. • Examples of variable declarations: • int width ; • float area ; • Declarations must be placed at the beginning of a function before any executable statements.

  12. numExams 2 FE07 Declaring Variables (con’t) • Variables in C correspond to locations (address) in the computer’s memory. • When we declare a variable • Space is set aside in memory to hold a value of the specified data type. • That space is associated with the variable name. • That space is associated with a unique address. • Every variable has a name, type, and value. • For example, • int numExams; • numExams = 2;

  13. More About Variables C has three basic predefined data types: • Integers (whole numbers) • int, long int, short int, unsigned int • Floating point (real numbers) • float, double • Characters • char • At this point, you need only be concerned with the data types that are bolded.

  14. Integer Variable int, long int, short int, unsigned int • Int is machine-dependent, can be positive, 0, or negative integer number. • Each compiler is free to choose appropriate size for its own hardware, provided size of short <= size of int <= size of long. Typically short is 16 bits, long is 32 bits, so int is either 16 or 32 bits. • Unsigned int is either 0 or positive integer.

  15. Using Variables: Initialization • Variables may be be given initial values, or initialized, when declared. Examples: int length = 7 ; float diameter = 5.9 ; char initial = ‘A’ ; length 7 diameter 5.9 initial ‘A’

  16. Using Variables: Initialization (con’t) • Do not “hide” the initialization • put initialized variables on a separate line • a comment is always a good idea • Example: int height ; /* rectangle height */ int width = 2 ; /* rectangle width */ int area ; /* rectangle area */ NOT int height, width = 2, area ;

  17. Using Variables: Assignment • Variables may have values assigned to them through the use of an assignment statement. • Such a statement uses the assignment operator “=”. • This operator does not denote equality. It assigns the value of the righthand side of the statement (the expression) to the variable on the lefthand side. • Examples: width = 2; area = length * width ; Note that only single variables may appear on the lefthand side of the assignment operator.

  18. Example: Declarations and Assignments length • #include <stdio.h> • int main( ) • { • int length, width, area ; • width = 2 ; • length = 4 * width ; • area = length * width ; garbage width garbage area garbage width 2 length 8 area 16

  19. Example: Declarations and Assignments (cont’d) • printf (“The dimension of a rectangle: ”) ; • printf (“ width = %d ”, width) ; • printf (“ length = %d \n”, length) ; • printf (“The area of a rectangle = %d. \n”, area) ; • return 0 ; • }

  20. Enhancing Our Example • What if the width were really 2.5? Our program, as it is, couldn’t handle it. • Unlike integers, floating point numbers can contain decimal portions. So, let’s use floating point, rather than integer. • Let’s also ask the user to enter the value of width, rather than “hard-coding” it in.

  21. Enhanced Program #include <stdio.h> int main ( ) { float length, width, area ; printf (“Enter length of a rectangle : ”) ; scanf (“%f”, &length) ; printf (“Enter width of a rectangle : ”) ; scanf (“%f”, &width) ; area = length * width ; • printf (“The dimension of a rectangle: \n”) ; • printf (“ width = %d \n”, width) ; • printf (“ length = %d \n”, length) ; printf (“The area of a rectangle = %f. \n”, area) ; return 0 ; }

  22. Final “Clean” Program #include <stdio.h> int main( ) { /* Variable Declarations */ float length ; /* length of a rectangle in decimal */ float width ; /* width of a rectangle in decimal */ float area ; /* area of a rectangle in decimal */ /* Get the dimension of a rectangle from the user */ printf (“Enter width of a rectangle : ”) ; scanf (“%f”, &width) ; printf (“Enter length of a rectangle : ”) ; scanf (“%f”, &length) ; /* Compute area of a rectangle */ area = length * width ;

  23. Final “Clean” Program (con’t) /* Display the results */ printf (“The dimension of a rectangle is \n”) ; • printf (“ width = %f \n”, width) ; • printf (“ length = %f \n”, length) ; • printf (“The area of a rectangle = %f \n”, area) ; return 0 ; }

  24. Sample Run (con’t) Sample output run: • Create a source code product.c:xemacs product.c • Compile source code product.c:gcc –ansi –Wall product.c • Run and test product.c:a.out • Sample screen dump: Enter width of a rectangle : 3.2 Enter length of a rectangle :5.4 The dimension of a rectangle is width = 3.200000 • length = 5.400000 • The area of a rectangle = 17.280001

  25. Good Programming Practices • Place each variable declaration on its own line with a descriptive comment. • Place a comment before each logical “chunk” of code describing what it does. • Do not place a comment on the same line as code (with the exception of variable declarations). • Use spaces around all arithmetic and assignment operators. • Use blank lines to enhance readability.

  26. Good Programming Practices (con’t) • Place a blank line between the last variable declaration and the first executable statement of the program. • Indent the body of the program 3 to 4 spaces -- be consistent!

  27. Assignment and Next • Read 2.3 – 2.4, and 2.5 (optional) Next: • Arithmetic Operators

More Related