Download presentation
Presentation is loading. Please wait.
Published byPeregrine Sullivan Modified over 9 years ago
1
ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I
2
Objectives To understand what variables are – initialization/garbage values – naming conventions To learn about the frequently used data types To understand the components of – an assignment Statements – arithmetic expressions To learn about – frequently used operators, – operator precedence
3
Introduction to Computer Systems Hardware Software
4
Hardware
5
– CPU - central processing unit Makes decisions, performs computations, and delegates input/output requests – Memory: Stores information Main memory: RAM, e.g. 256 MB RAM Secondary memory: hard disk, e.g. 20GB – Input devices Gets information from the user to the computer – Output devices Sends information from computer to the user
6
What is a program? A computer program performs a specific task, and may interact with the user and the computer hardware. – Human work model: – Computer work model: A program is a set of instructions
7
What is a (programming) language? A program needs to be written in a language There are many programming languages – Low-level, understandable by a computer – High-level, needs a translator! C is a high level programming language A sequence of instructions A program (in computer language) An algorithm (in human language)
8
Machine binary languageLow-level assemblyHigh-level An example
9
Machine binary language: unintelligible Low-level assembly language – Mnemonic names for machine operations – Explicit manipulation of memory addresses – Machine-dependent High-level language – Readable – Machine-independent Levels of programming language
10
How to translate? Examples of compilers: – Microsoft Visual C++, Eclipse, Quincy, g++ A program written in high-level programming language (for example, C program) A low-level (machine language) program that is understandable by a computer (for example, a PC) COMPILER (for example, MS Visual C++)
11
Application software – Programs designed to perform specific tasks and are easy to use System software – Programs that support the execution and development of other programs Two major types Operating systems Translation systems (compilers & linkers) What is a software? The set of all programs or a set of programs
12
Basics of C Environment C systems consist of 3 parts – Environment – Language – C Standard Library Development environment has 6 phases – Edit – Pre-processor – Compile – Link – Load – Execute
13
Basics of C Environment Editor Disk Phase 1 Program edited in Editor and stored on disk Preprocessor Disk Phase 2 Preprocessor program processes the code Compiler Disk Phase 3 Creates object code and stores on disk Linker Disk Phase 4 Links object code with libraries and stores on disk
14
Basics of C Environment Loader Phase 5 Puts program in memory Primary memory CPU Phase 6 Takes each instruction and executes it storing new data values Primary memory
15
Programming or Software Development Editing (to write the program) Compiling (creates.obj file) Linking with compiled files (creates.exe file) Object files Library modules Loading and executing Testing the program debug
16
Integrated Development Environments (IDE) Editor Compiler Linker Loader Debugger Viewer Combine all of the capabilities that a programmer would want while developing software (VC++, Eclipse) builder
17
17 C Syntax and Hello World #include /* The simplest C Program */ int main(int argc, char **argv) { printf(“Hello World\n”); return 0; } The main() function is always where your program starts running. #include inserts another file. “.h” files are called “header” files. They contain stuff needed to interface to libraries and code in other “.c” files. This is a comment. The compiler ignores this. Blocks of code (“lexical scopes”) are marked by { … } Print out a message. ‘\n’ means “new line”.Return ‘0’ from this function What do the mean?
18
Comments begin with /* and end with */ indicating that these two lines are a comment. You insert comments to document programs and improve program readability. Comments do not cause the computer to perform any action when the program is run. Comments are ignored by the C compiler and do not cause any machine-language object code to be generated. Comments also help other people read and understand your program. C99 also includes the C++ language’s // single-line comments in which everything from // to the end of the line is a comment. These can be used as standalone comments on lines by themselves or as end-of-line comments to the right of a partial line of code.
19
Preprocessor Lines beginning with # are processed by the preprocessor before the program is compiled. #include is a directive to the C preprocessor. Tells the preprocessor to include the contents of the standard input/output header ( ) in the program. This header contains information used by the compiler when compiling calls to standard input/output library functions such as printf. ©1992-2010 by Pearson Education, Inc. All Rights Reserved.
20
main function int main( void ) is a part of every C program. The parentheses after main indicate that main is a program building block called a function. C programs contain one or more functions, one of which must be main. Every program in C begins executing at the function main. The keyword int to the left of main indicates that main “returns” an integer (whole number) value. ©1992-2010 by Pearson Education, Inc. All Rights Reserved.
21
Beginning of the main function A left brace, {, begins the body of every function. A corresponding right brace ends each function. This pair of braces and the portion of the program between the braces is called a block. Line 8 printf( "Welcome to C!\n" ); instructs the computer to perform an action, namely to print on the screen the string of characters marked by the quotation marks. A string is sometimes called a character string, a message or a literal. ©1992-2010 by Pearson Education, Inc. All Rights Reserved.
22
printf The entire line, including printf, its argument within the parentheses and the semicolon ( ; ), is called a statement. Every statement must end with a semicolon (also known as the statement terminator). When the preceding printf statement is executed, it prints the message Welcome to C! on the screen. The characters normally print exactly as they appear between the double quotes in the printf statement. Notice that the characters \n were not printed on the screen. The backslash ( \ ) is called an escape character. It indicates that printf is supposed to do something out of the ordinary. ©1992-2010 by Pearson Education, Inc. All Rights Reserved.
23
Ending of a main function return 0; /* indicate that program ended successfully */ is included at the end of every main function. The keyword return is one of several means we’ll use to exit a function. When the return statement is used at the end of main as shown here, the value 0 indicates that the program has terminated successfully. The right brace, }, indicates that the end of main has been reached. ©1992-2010 by Pearson Education, Inc. All Rights Reserved.
24
24 About the C Compiler #include /* The simplest C Program */ int main(int argc, char **argv) { printf(“Hello World\n”); return 0; } my_program __extension__ typedef unsigned long long int __dev_t; __extension__ typedef unsigned int __uid_t; __extension__ typedef unsigned int __gid_t; __extension__ typedef unsigned long int __ino_t; __extension__ typedef unsigned long long int __ino64_t; __extension__ typedef unsigned int __nlink_t; __extension__ typedef long int __off_t; __extension__ typedef long long int __off64_t; extern void flockfile (FILE *__stream) ; extern int ftrylockfile (FILE *__stream) ; extern void funlockfile (FILE *__stream) ; int main(int argc, char **argv) { printf(“Hello World\n”); return 0; } Compilation occurs in two steps: “Preprocessing” and “Compiling” In Preprocessing, source code is “expanded” into a larger form that is simpler for the compiler to understand. Any line that starts with ‘#’ is a line that is interpreted by the Preprocessor. Include files are “pasted in” (#include) Macros are “expanded” (#define) Comments are stripped out ( /* */, // ) Continued lines are joined ( \ ) Preprocess Compile The compiler then converts the resulting text into binary code the CPU can run directly.
25
25 What is a Function? #include /* The simplest C Program */ int main(int argc, char **argv) { printf(“Hello World\n”); return 0; } Function Arguments Return type, or void Calling a Function: “printf()” is just another function, like main(). It’s defined for you in a “library”, a collection of functions you can call from your program. A Function is a series of instructions to run. You pass Arguments to a function and it returns a Value. “main()” is a Function. It’s only special because it always gets called first when you run your program. Returning a value
26
26 What is “Memory”? Memory is like a big table of numbered slots where bytes can be stored. AddrValue 0 1 2 3 4‘H’ (72) 5‘e’ (101) 6‘l’ (108) 7 8‘o’ (111) 9‘\n’ (10) 10‘\0’ (0) 11 12 The number of a slot is its Address. One byte Value can be stored in each slot. Some “logical” data values span more than one slot, like the character string “Hello\n” 72? A Type names a logical meaning to a span of memory. Some simple types are: char char [10] int float int64_t a single character (1 slot) an array of 10 characters signed 4 byte integer 4 byte floating point signed 8 byte integer not always… Signed?…
27
27 What is a Variable? char x; char y=‘e’; A Variable names a place in memory where you store a Value of a certain Type. SymbolAddrValue 0 1 2 3 x4? y5‘e’ (101) 6 7 8 9 10 11 12 You first Define a variable by giving it a name and specifying the type, and optionally an initial value declare vs define? Type is single character (char) extern? static? const? Name What names are legal? Initial value Initial value of x is undefined The compiler puts them somewhere in memory. symbol table?
28
28 Multi-byte Variables char x; char y=‘e’; int z = 0x01020304; Different types consume different amounts of memory. Most architectures store data on “word boundaries”, or even multiples of the size of a primitive data type (int, char) SymbolAddrValue 0 1 2 3 x4? y5‘e’ (101) 6 7 z84 93 102 111 12 0x means the constant is written in hex An int consumes 4 bytes padding
29
VARIABLES Variables are basic data objects manipulated in a program. Each variable has to be declared before use. Each variable has a name and a data type. You can give initial value (variable initialization) on variable declaration. Examples: int x;char gender;float avg; float sum=0;char name[10];int *fp;
30
VARIABLES Variable declaration allocates a cell in the main memory whose size is determined by the data type – For example for int 4 bytes are used, for double 8 bytes are used When the variable is created in the main memory it contains garbage value – This is due to the existence of 1’s and 0’s in the memory. 1 means high voltage, 0 means low voltage. It is a good idea to initialize variables before first usage. A variable name is the symbolic representation of the memory location that is allocated on variable declaration
31
Rules on Variable Names: DO NOT use reserved words as variable names (e.g. if, else, int, float, case, for, …). The first character has to be a letter or underscore. It can not be a numeric digit. The second and the other characters of the name can be any letter, any number, or an underscore “_”. Examples Some valid names: my_name, m113_1, salary, bluemoon, _at Some invalid names: my name, my-name, 1stmonth, salary!, guns&roses,
32
Tradition on Variable Names: These are NOT rules but you can increase the quality of your program by using them! Select related and meaningful names indicating tasks of the variables. Do not use variable names that exceed 8 characters. Use small case letters for variable names. – Upper case letters are mostly used in the names of symbolic constants.
33
Variable Declaration: Variable declaration is used to introduce the system to the variables that the programmer decides to use on the rest of the program. On variable declaration, – variable name, – data type are declared. Also you can give the initial value of the variable on its declaration. Example : int k ; int m=15; float fnumber= 1.75; char ch=’w’ ;
34
Data Types of the Variables : A variable data type specifies: – The kind of value a variable can store – The set of operations that can be applied to the variable There are 3 main different data types and their derivations for declaration in ANSI–C. Main Data typesDerived Data Types integershort, long floatDouble char
35
Data Types and Sizes : (Continued) Integers (int) : Integers are all numeric values that have no fractional or decimal components. Integer numbers may be positive or negative. Examples : 13 7–62081024 C compiler allocates 4 bytes (32 bits) to an integer (int) variable. An integer variable can store values in the range –32,768 through 32,767 Derived Integers : short, long and unsigned are data types derived from int, and used to keep integer values. The sizes of long and short is differentiated from int. The data type unsigned is used only with positive integers.
36
Data Types and Sizes : (Continued) Data TypesBytes Used int4 Bytes short2 Bytes double8 Bytes unsigned4 Bytes The sizes of long and short is differentiated from int. The data type unsigned is used only with positive integers.
37
Data Types and Sizes : (Continued) Real Numbers : C compiler uses float and double data types for storing real numbers. The float data type requires 4 bytes and has a precision of seven digits – This means after the decimal point you can have seven digits Example: 3.14159 534.3223440.3333333 0.1234567 The double data type requires 8 bytes and has a precision of fifteen digits Example : -3738.78787878783.141592653589790 0.123456789123456
38
Data Types and Sizes : (Continued) We can use Scientific Notation to represent real numbers that are very large or very small in value. The letters e or E is used to represent times 10 to the power. Example: 1.23 x 10 5 is represented in C as 1.23e5 or 1.23e+5 or 1.23E5 1 x 10 -9 is represented in C as 1e-9
39
Data Types and Sizes : (Continued) Character : ( char ) Characters constants are usually used enclosed single quotes Example: ‘A’, ‘7’, Only one byte of memory location is used by a character variable. In ASCII code is used to represent uniquely any one of the available 255 characters Example: A is represented by decimal 65 or 8-bit binary 0 1 0 0 0 0 0 1
40
Data Types and Sizes : (Continued) Categories of characters : Alphabetic Letters : – ( Upper case : ‘A’, ‘B’, …….. ‘Z’ ) – ( Lower case : ‘a’, ‘b’, …….. ‘z’ ) Numeric digits – ( ‘1’,’2’,’3’,…………,’9’,’0’ ) Special Characters – ( blank, ‘+’,’#’,’-‘,’_’,……..) Control Characters – ( ‘\n’, ‘\t’, ……. )
41
Assignment Statements The ‘=‘ sign is an assignment operator. Assignment statements replace old values of the variables with the new ones An assignment statement assigns a value or a computational result to a variable. Example cnt = 1; sum = 0; ch = ‘Y’; sum = sum + 1; avg = sum / cnt; stores values 1 and 0 to cnt and sum. stores character ‘Y’ to ch stores computational results to sum and avg
42
Expressions Arithmetic Expressions involve arithmetic operators such as *,+,-,/,%: – Example : a * 5 + b % 4 Relational Expressions involve relational operators that compare two values such as >,<,== etc: – Example: a > b Logical Expressions involve the logical and and or operators && and || and are used to combine relational expressions: – Example: ( a > b && c == 7 )
43
Arithmetic Expressions In the Assignment Statement: M = a * 5 + b % 4 ; The expression to the right of the assignment operator ( = ) involves an arithmetic operation that combines arithmetic operands with arithmetic operators. The most commonly used arithmetic operators are: – Addition (+) Operator – Subtraction (-) Operator – multiplication (*) Operator – division (/) Operator – remainder (%) Operator For real or integer numbers For integer numbers only
44
Operator Precedence Rules Arithmetic expressions inside parentheses are executed first (left to right). Unary operators ( minus signs and plus signs) are executed before multiplications, divisions and remainder operations. Additions and subtractions are executed last. OperatorsAssociativityPriority Level (, )Left to RightHighest +, - ( unary )Right to Left *, /, %Left to Right +, -Left to RightLowest parentheses -ve and +ve signs Mult. Div., and mod. Add and subtract
45
45 Expressions and Evaluation Expressions combine Values using Operators, according to precedence. 1 + 2 * 2 1 + 4 5 (1 + 2) * 2 3 * 2 6 Symbols are evaluated to their Values before being combined. int x=1; int y=2; x + y * y x + 2 * 2 x + 4 1 + 4 5 Comparison operators are used to compare values. In C, 0 means “false”, and any other value means “true”. int x=4; (x (x < 4) (4 < 4) 0 ((x || (x Not evaluated because first clause was true
46
46 Comparison and Mathematical Operators == equal to < less than <= less than or equal > greater than >= greater than or equal != not equal && logical and || logical or ! logical not + plus - minus * mult / divide % modulo The rules of precedence are clearly defined but often difficult to remember or non-intuitive. When in doubt, add parentheses to make it explicit. For oft-confused cases, the compiler will give you a warning “Suggest parens around …” – do it! Beware division: If second argument is integer, the result will be integer (rounded): 5 / 10 0 whereas 5 / 10.0 0.5 Division by 0 will cause a FPE & bitwise and | bitwise or ^ bitwise xor ~ bitwise not << shift left >> shift right Don’t confuse & and &&.. 1 & 2 0 whereas 1 && 2
47
Operator Precedence Rules:Examples ? =3 + 5* 4 – Evaluated as 3 + (5*4) and the result is 23 ? = 8 / (5 – 2) – Evaluated as 8 / 3 and the result is 2 ? = 8 + 12 % 5 – Evaluated as 8 + (12%5) and the result is 10 ? = 6 * 5 / 2 + 2 – Evaluated as ( ( 6*5) /2) + 2 and the result is 17 ? = 9 – 4 + 2 * 6 – Evaluated as 9 – 4 + (2*6) and the result is 17 ? = 1 + 2 * (3 + 4) – Evaluated as 1 + (2 * (3+4)) and the result is 15 ? = 5 * 2 + 9 % 4 – Evaluated as (5*2) + (9 % 4) and the result is 11 ? = 5 * 2 % ( 7 – 4) – Evaluated as (5 * 2) % (7 – 4) and the result is 1
48
THAT’S IT FOR NOW! NEXT LECTURE: MORE ON VARIABLES, DATA TYPES AND EXPRESSIONS
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.