30
Variables in C Variables in C Amir Haider Amir Haider Lecturer Lecturer

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

Embed Size (px)

Citation preview

Page 1: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Variables in CVariables in C

Amir HaiderAmir Haider

LecturerLecturer

Page 2: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

TopicsTopics

Naming VariablesNaming Variables Declaring VariablesDeclaring Variables Using VariablesUsing Variables The Assignment StatementThe Assignment Statement

Page 3: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

What Are Variables in C?What Are Variables in C?

VariablesVariables in C have the same meaning as in C have the same meaning as variables in algebra. That is, they represent variables in algebra. That is, they represent some unknown, or variable, value.some unknown, or variable, value.

x = a + bx = a + bz + 2 = 3(y - 5)z + 2 = 3(y - 5)

Remember that variables in algebra are Remember that variables in algebra are represented by a single alphabetic character.represented by a single alphabetic character.

Page 4: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Naming VariablesNaming Variables

Variables in C may be given representations Variables in C may be given representations containing multiple characters. But there are rules for containing multiple characters. But there are rules for these representations.these representations.

Variable names (identifiers) in CVariable names (identifiers) in C May only consist of letters, digits, and underscoresMay only consist of letters, digits, and underscores May be as long as you like, but only the first 31 characters May be as long as you like, but only the first 31 characters

are significantare 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 May not be a C reserved word (keyword)reserved word (keyword)

Page 5: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Reserved Words (Keywords) in Reserved Words (Keywords) in CC

autoauto break break casecase char char constconst continue continue defaultdefault do do doubledouble else else enumenum extern extern floatfloat for for gotogoto if if

int longregister returnshort signedsizeof staticstruct switchtypedef unionunsigned voidvolatile while

Page 6: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Naming ConventionsNaming Conventions

C programmers generally agree on the C programmers generally agree on the following following conventionsconventions for naming variables. for naming variables. Begin variable names with lowercase lettersBegin variable names with lowercase letters Use Use meaningfulmeaningful identifiers identifiers Separate “words” within identifiers with Separate “words” within identifiers with

underscores or mixed upper and lower case. underscores or mixed upper and lower case. Examples: surfaceArea surface_Area Examples: surfaceArea surface_Area

surface_area surface_area Be consistent!Be consistent!

Page 7: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Naming Conventions (con’t)Naming Conventions (con’t)

Use all uppercase for Use all uppercase for symbolic constantssymbolic constants (used in (used in #define#define preprocessor directives). preprocessor directives).

Note: symbolic constants are not variables, Note: symbolic constants are not variables, but make the program easier to read.but make the program easier to read.

Examples:Examples:

#define PI 3.14159#define PI 3.14159 #define AGE 52#define AGE 52

Page 8: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Case SensitivityCase Sensitivity

C is C is case sensitivecase sensitive It matters whether an It matters whether an identifieridentifier, such as a variable , such as a variable

name, is uppercase or lowercase.name, is uppercase or lowercase. Example:Example:

areaareaAreaAreaAREAAREAArEaArEa

are all seen as are all seen as differentdifferent variables by the compiler. variables by the compiler.

Page 9: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Declaring VariablesDeclaring Variables

Before using a variable, you must give the Before using a variable, you must give the compiler some information about the variable; compiler some information about the variable; i.e., you must i.e., you must declaredeclare it. it.

The The declaration statementdeclaration statement includes the includes the data data typetype of the variable. of the variable.

Examples of variable declarations:Examples of variable declarations: int meatballs ;int meatballs ; float area ;float area ;

Page 10: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Declaring Variables (con’t)Declaring Variables (con’t)

When we declare a variableWhen we declare a variable Space is set aside in memory to hold a value of the Space is set aside in memory to hold a value of the

specified data typespecified data type That space is associated with the variable nameThat space is associated with the variable name That space is associated with a unique That space is associated with a unique addressaddress Unless we specify otherwise, the space has no known Unless we specify otherwise, the space has no known

value.value.

Visualization of the declarationVisualization of the declaration int meatballs ;int meatballs ;

meatballs

garbage

FE07 int

Page 11: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

More About VariablesMore About Variables

C has three basic predefined data types:C has three basic predefined data types:

Integers (whole numbers)Integers (whole numbers) Int. Int. long int, short int, unsigned int long int, short int, unsigned int

Floating point (real numbers)Floating point (real numbers) Float.Float. FloatFloat , , doubledouble

CharactersCharacters charchar

At this point, you need only be concerned with the At this point, you need only be concerned with the data types that are bolded.data types that are bolded.

Page 12: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Notes About VariablesNotes About Variables

You must not use a variable until you You must not use a variable until you somehow give it a value.somehow give it a value.

You can not assume that the variable will have You can not assume that the variable will have a value before you give it one.a value before you give it one. Assume your compiler does not give it an initial Assume your compiler does not give it an initial

value!value!

Page 13: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Using Variables: InitializationUsing Variables: Initialization

Variables may be given initial values, or Variables may be given initial values, or initializedinitialized, when declared. Examples:, when declared. Examples:

int length = 7 ;int length = 7 ;

float diameter = 5.9 ;float diameter = 5.9 ;

char initial = ‘A’ ;char initial = ‘A’ ;

7

5.9

‘A’

length

diameter

initial

Page 14: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Using Variables: Initialization Using Variables: Initialization (con’t)(con’t)

Do not “hide” the initializationDo not “hide” the initialization put initialized variables on a separate lineput initialized variables on a separate line a comment is always a good ideaa comment is always a good idea Example:Example:

int height ; /* rectangle height */int height ; /* rectangle height */

int width = 6 ; /* rectangle width */int width = 6 ; /* rectangle width */

int area ; /* rectangle area */int area ; /* rectangle area */

NOT int height, width = 6, area ;NOT int height, width = 6, area ;

Page 15: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Using Variables: AssignmentUsing Variables: Assignment Variables may have values assigned to them through Variables may have values assigned to them through

the use of an the use of an assignment statementassignment statement.. Such a statement uses the Such a statement uses the assignment operator =assignment operator = This operator This operator does notdoes not denote equality. It assigns the denote equality. It assigns the

value of the right-hand side of the statement (the value of the right-hand side of the statement (the expressionexpression) to the variable on the left-hand side.) to the variable on the left-hand side.

Examples:Examples:diameter = 5.9 ;diameter = 5.9 ;area = length * width ;area = length * width ;

Note that only single variables may appear on the Note that only single variables may appear on the left-hand side of the assignment operator.left-hand side of the assignment operator.

Page 16: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

FunctionsFunctions

It is necessary for us to use some functions to It is necessary for us to use some functions to write our first programs, but we are not going write our first programs, but we are not going to explain functions in great detail at this time.to explain functions in great detail at this time.

Functions are parts of programs that perform a Functions are parts of programs that perform a certain task and we have to give them some certain task and we have to give them some information so the function can do the task. information so the function can do the task.

We will show you how to use the functions as We will show you how to use the functions as we go through the course and later on will we go through the course and later on will show you how to create your own.show you how to create your own.

Page 17: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Displaying VariablesDisplaying Variables

Variables hold values that we occasionally Variables hold values that we occasionally want to show the person using the program.want to show the person using the program.

We have a function called printf( ) that will We have a function called printf( ) that will allow us to do that.allow us to do that.

The function printf needs two pieces of The function printf needs two pieces of information to display things. information to display things. How to display itHow to display it What to displayWhat to display

printf( “%f\n”, diameter );printf( “%f\n”, diameter );

Page 18: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

printf( “%f\n”, diameter );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 (“\We want to have the next thing started on a new line (“\

n”).n”). We want to display the contents of the variable We want to display the contents of the variable

diameter.diameter. printf( ) has many other capabilities.printf( ) has many other capabilities.

Page 19: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Taking Input From UsersTaking 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 This shows that a value is taken by user and

stored in variable a, %d is telling us the typ of stored in variable a, %d is telling us the typ of variable. variable.

Page 20: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Address TypesAddress Types

Decimal values %dDecimal values %d Fraction values %fFraction values %f Character values %cCharacter values %c Strings values %s (array of chars) Strings values %s (array of chars)

Page 21: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Example: Declarations and Example: Declarations and AssignmentsAssignments

#include <stdio.h>#include <stdio.h>

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

garbagefeet

42

garbage

504

inches

Page 22: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Example: Declarations and Assignments Example: Declarations and Assignments (cont’d)(cont’d)

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

Page 23: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Enhancing Our ExampleEnhancing Our Example

What if the depth were really 5.75 fathoms? What if the depth were really 5.75 fathoms? Our program, as it is, couldn’t handle it.Our program, as it is, couldn’t handle it.

Unlike integers, floating point numbers can Unlike integers, floating point numbers can contain decimal portions. So, let’s use floating contain decimal portions. So, let’s use floating point, rather than integer.point, rather than integer.

Let’s also ask the user to enter the number of Let’s also ask the user to enter the number of fathoms, rather than fathoms, rather than “hard-coding”“hard-coding” it in by it in by using the scanf( ) function.using the scanf( ) function.

Page 24: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Enhanced ProgramEnhanced Program #include <stdio.h> 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 ;

Page 25: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

scanf (“%f”, &fathoms) ;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” The input specification “%f”. (Never put a “\n”

into the input specification.)into the input specification.) The address of where to store the information. The address of where to store the information.

(We can input more than one item at a time if we (We can input more than one item at a time if we wish, as long as we specify it correctly.)wish, as long as we specify it correctly.)

Notice the “&” in front of the variable name. Notice the “&” in front of the variable name. It says to use the address of the variable to It says to use the address of the variable to hold the information that the user enters.hold the information that the user enters.

Page 26: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Final “Clean” ProgramFinal “Clean” Program #include <stdio.h>

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

Page 27: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Final “Clean” Program (con’t)Final “Clean” Program (con’t)

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

Page 28: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Good Programming PracticesGood Programming Practices

Place each variable declaration on its own line with a Place each variable declaration on its own line with a descriptive comment.descriptive comment.

Place a comment before each logical “chunk” of code Place a comment before each logical “chunk” of code describing what it does.describing what it does.

Do not place a comment on the same line as code Do not place a comment on the same line as code (with the exception of variable declarations).(with the exception of variable declarations).

Use spaces around all arithmetic and assignment Use spaces around all arithmetic and assignment operators.operators.

Use blank lines to enhance readability.Use blank lines to enhance readability.

Page 29: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Another Sample ProgramAnother Sample Program #include <stdio.h>

#define PI 3.14159

int main ( void ) { float radius = 3.0; float area;

area = PI * radius * radius; printf( “The area is %f.\n”, area ); return 0 ; }

Page 30: Variables in C Amir Haider Lecturer. Topics Naming Variables Naming Variables Declaring Variables Declaring Variables Using Variables Using Variables

Some Examples Some Examples

Make a simple calculator which can perform Make a simple calculator which can perform basic functions of + - * / . 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?