Presentation is loading. Please wait.

Presentation is loading. Please wait.

Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables.

Similar presentations


Presentation on theme: "Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables."— Presentation transcript:

1 Variables in C Amir Haider Lecturer

2 Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables The Assignment Statement The Assignment Statement

3 What Are Variables in C? Variables in C have the same meaning as variables in algebra. That is, they represent some unknown, or variable, value. Variables in C have the same meaning as variables in algebra. That is, they represent some unknown, or variable, value. x = a + b z + 2 = 3(y - 5) Remember that variables in algebra are represented by a single alphabetic character. Remember that variables in algebra are represented by a single alphabetic character.

4 Naming Variables Variables in C may be given representations containing multiple characters. But there are rules for these representations. Variables in C may be given representations containing multiple characters. But there are rules for these representations. Variable names (identifiers) in C Variable names (identifiers) in C May only consist of letters, digits, and underscores May only consist of letters, digits, and underscores May be as long as you like, but only the first 31 characters are significant May be as long as you like, but only the first 31 characters are significant May not begin with a digit. 2, 4, 5 wrong but a, b, c write. May not begin with a digit. 2, 4, 5 wrong but a, b, c write. May not be a C reserved word (keyword) May not be a C reserved word (keyword)

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

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

7 Naming Conventions (cont) Use all uppercase for symbolic constants (used in #define preprocessor directives). Use all uppercase for symbolic constants (used in #define preprocessor directives). Note: symbolic constants are not variables, but make the program easier to read. Note: symbolic constants are not variables, but make the program easier to read. Examples: Examples: #define PI #define PI #define AGE 52 #define AGE 52

8 Case Sensitivity C is case sensitive C is case sensitive It matters whether an identifier, such as a variable name, is uppercase or lowercase. It matters whether an identifier, such as a variable name, is uppercase or lowercase. Example: Example:areaAreaAREAArEa are all seen as different variables by the compiler.

9 Declaring Variables Before using a variable, you must give the compiler some information about the variable; i.e., you must declare it. 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. The declaration statement includes the data type of the variable. Examples of variable declarations: Examples of variable declarations: int meatballs ; int meatballs ; float area ; float area ;

10 Declaring Variables (cont) When we declare a variable When we declare a variable Space is set aside in memory to hold a value of the specified data type 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 the variable name That space is associated with a unique address That space is associated with a unique address Unless we specify otherwise, the space has no known value. Unless we specify otherwise, the space has no known value. Visualization of the declaration Visualization of the declaration int meatballs ; int meatballs ; meatballs garbage FE07 int

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

12 Notes About Variables You must not use a variable until you somehow give it a value. You must not use a variable until you somehow give it a value. You can not assume that the variable will have a value before you give it one. You can not assume that the variable will have a value before you give it one. Assume your compiler does not give it an initial value! Assume your compiler does not give it an initial value!

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

14 Using Variables: Initialization (cont) Do not hide the initialization Do not hide the initialization put initialized variables on a separate line put initialized variables on a separate line a comment is always a good idea a comment is always a good idea Example: Example: int height ; /* rectangle height */ int width = 6 ; /* rectangle width */ int area ; /* rectangle area */ NOT int height, width = 6, area ; NOT int height, width = 6, area ;

15 Using Variables: Assignment Variables may have values assigned to them through the use of an assignment statement. Variables may have values assigned to them through the use of an assignment statement. Such a statement uses the assignment operator = Such a statement uses the assignment operator = This operator does not denote equality. It assigns the value of the right-hand side of the statement (the expression) to the variable on the left-hand side. This operator does not denote equality. It assigns the value of the right-hand side of the statement (the expression) to the variable on the left-hand side. Examples: Examples: diameter = 5.9 ; area = length * width ; Note that only single variables may appear on the left-hand side of the assignment operator.

16 Functions It is necessary for us to use some functions to write our first programs, but we are not going to explain functions in great detail at this time. It is necessary for us to use some functions to write our first programs, but we are not going to explain functions in great detail at this time. Functions are parts of programs that perform a certain task and we have to give them some information so the function can do the task. Functions are parts of programs that perform a certain task and we have to give them some information so the function can do the task. We will show you how to use the functions as we go through the course and later on will show you how to create your own. We will show you how to use the functions as we go through the course and later on will show you how to create your own.

17 Displaying Variables Variables hold values that we occasionally want to show the person using the program. Variables hold values that we occasionally want to show the person using the program. We have a function called printf( ) that will allow us to do that. We have a function called printf( ) that will allow us to do that. The function printf needs two pieces of information to display things. The function printf needs two pieces of information to display things. How to display it How to display it What to display What to display printf( %f\n, diameter ); printf( %f\n, diameter );

18 printf( %f\n, diameter ); The name of the function is printf. The name of the function is printf. Inside the parentheses are: Inside the parentheses are: print specification, where we are going to display: print specification, where we are going to display: a floating point value (%f) a floating point value (%f) We want to have the next thing started on a new line (\n). We want to have the next thing started on a new line (\n). We want to display the contents of the variable diameter. We want to display the contents of the variable diameter. printf( ) has many other capabilities. printf( ) has many other capabilities.

19 Taking Input From Users We use Scan function for input values. We use Scan function for input values. Different values can be taken from users. Different values can be taken from users. we write function as we write function as scanf( %d,a); scanf( %d,a); This shows that a value is taken by user and stored in variable a, %d is telling us the typ of variable. This shows that a value is taken by user and stored in variable a, %d is telling us the typ of variable.

20 Address Types Decimal values %d Decimal values %d Fraction values %f Fraction values %f Character values %c Character values %c Strings values %s (array of chars) Strings values %s (array of chars)

21 Example: Declarations and Assignments #include #include int main( void ) int main( void ) { int inches, feet, fathoms ; int inches, feet, fathoms ; fathoms = 7 ; fathoms = 7 ; feet = 6 * fathoms ; feet = 6 * fathoms ; inches = 12 * feet ; inches = 12 * feet ; inches feet fathoms garbage fathoms 7 garbage feet 42 garbage 504 inches

22 Example: Declarations and Assignments (contd) printf (Its depth at sea: \n) ; printf (Its depth at sea: \n) ; printf ( %d fathoms \n, fathoms) ; printf ( %d fathoms \n, fathoms) ; printf ( %d feet \n, feet) ; printf ( %d feet \n, feet) ; printf ( %d inches \n, inches) ; printf ( %d inches \n, inches) ; return 0 ; return 0 ; }

23 Enhancing Our Example What if the depth were really 5.75 fathoms? Our program, as it is, couldnt handle it. What if the depth were really 5.75 fathoms? Our program, as it is, couldnt handle it. Unlike integers, floating point numbers can contain decimal portions. So, lets use floating point, rather than integer. Unlike integers, floating point numbers can contain decimal portions. So, lets use floating point, rather than integer. Lets also ask the user to enter the number of fathoms, rather than hard-coding it in by using the scanf( ) function. Lets also ask the user to enter the number of fathoms, rather than hard-coding it in by using the scanf( ) function.

24 Enhanced Program #include int main ( void ) { float inches, feet, fathoms ; printf (Enter the depth in fathoms : ) ; scanf (%f, &fathoms) ; feet = 6 * fathoms ; inches = 12 * feet ; printf (Its depth at sea: \n) ; printf ( %f fathoms \n, fathoms) ; printf ( %f feet \n, feet) ; printf ( %f inches \n, inches) ; return 0 ;

25 scanf (%f, &fathoms) ; The scanf( ) function also needs two items: The scanf( ) function also needs two items: The input specification %f. (Never put a \n into the input specification.) The input specification %f. (Never put a \n into the input specification.) The address of where to store the information. (We can input more than one item at a time if we wish, as long as we specify it correctly.) The address of where to store the information. (We can input more than one item at a time if we wish, as long as we specify it correctly.) Notice the & in front of the variable name. It says to use the address of the variable to hold the information that the user enters. Notice the & in front of the variable name. It says to use the address of the variable to hold the information that the user enters.

26 Final Clean Program #include #define FEET_PER_FATHOM 6 #define INCHES_PER_FOOT 12 int main( void ) { float inches ; /* number of inches deep */ float feet ; /* number of feet deep */ float fathoms ; /* number of fathoms deep */ /* Get the depth in fathoms from the user */ printf (Enter the depth in fathoms : ) ; scanf (%f, &fathoms) ;

27 Final Clean Program (cont) feet = FEET_PER_FATHOM * fathoms ; inches = INCHES_PER_FOOT * feet ; /* Display the results */ printf (Its depth at sea: \n) ; printf ( %f fathoms \n, fathoms) ; printf ( %f feet \n, feet); printf ( %f inches \n, inches); return 0 ; }

28 Good Programming Practices Place each variable declaration on its own line with a descriptive comment. 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. 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). 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 spaces around all arithmetic and assignment operators. Use blank lines to enhance readability. Use blank lines to enhance readability.

29 Another Sample Program #include #define PI int main ( void ) { float radius = 3.0; float area; area = PI * radius * radius; printf( The area is %f.\n, area ); return 0 ; }

30 Some Examples Some Examples Make a simple calculator which can perform basic functions of + - * /. Make a simple calculator which can perform basic functions of + - * /. Make Ohms Law Calculator. Make Ohms Law Calculator. which can find R, V, I. which can find R, V, I. Also find Power = V*I. Also find Power = V*I. Make a calculator for voltage divider rule? Make a calculator for voltage divider rule? Make a calculator for Current divider rule? Make a calculator for Current divider rule?


Download ppt "Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables."

Similar presentations


Ads by Google