Presentation is loading. Please wait.

Presentation is loading. Please wait.

ITEC113 Algorithms and Programming Techniques

Similar presentations


Presentation on theme: "ITEC113 Algorithms and Programming Techniques"— Presentation transcript:

1 ITEC113 Algorithms 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 What is a program? Work Worker Product Instructions Work Computer
A computer program performs a specific task, and may interact with the user and the computer hardware. Human work model: Computer work model: Work Worker Product Instructions High-level lang., easy Low-level, hard Work Computer Product Program A program is a set of instructions

6 What is a (programming) language?
A sequence of instructions A program (in computer language) An algorithm (in human 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 High-level lang., easy Low-level, hard

7 An example Machine binary language Low-level assembly High-level

8 Levels of programming language
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

9 How to translate? A program written in high-level programming language (for example, C program) COMPILER (for example, MS Visual C++) A low-level (machine language) program that is understandable by a computer (for example, a PC) Examples of compilers: Microsoft Visual C++, Eclipse, Quincy, g++

10 What is a software? The set of all programs or a set of programs
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)

11 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

12 Basics of C Environment
Editor Disk Phase 1 Program edited in Editor and stored on disk Preprocessor Disk Phase 2 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

13 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

14 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

15 Integrated Development Environments (IDE)
Combine all of the capabilities that a programmer would want while developing software (VC++, Eclipse) Editor Compiler Linker Loader Debugger Viewer builder

16 C Syntax and Hello World
#include inserts another file. “.h” files are called “header” files. They contain stuff needed to interface to libraries and code in other “.c” files. What do the < > mean? This is a comment. The compiler ignores this. #include <stdio.h> /* 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. Blocks of code (“lexical scopes”) are marked by { … } What do the <> mean? Include directives use <x.h> (brackets) to indicate that the compiler should look in a “standard” place, such as /usr/include/… They use “x.h” (double quotes) to indicate that it should look first in the current directory. Can your program have more than one .c file? A ‘.c’ file is called a “module”. Many programs are composed of several ‘.c’ files and libraries that are ‘linked’ together during the compile process. Return ‘0’ from this function Print out a message. ‘\n’ means “new line”.

17 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.

18 Preprocessor Lines beginning with # are processed by the preprocessor before the program is compiled. #include <stdio.h> is a directive to the C preprocessor. Tells the preprocessor to include the contents of the standard input/output header (<stdio.h>) in the program. This header contains information used by the compiler when compiling calls to standard input/output library functions such as printf.

19 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.

20 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.

21 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.

22 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. © by Pearson Education, Inc. All Rights Reserved.

23 About the C Compiler my_program Compilation occurs in two steps:
#include <stdio.h> /* The simplest C Program */ int main(int argc, char **argv) { printf(“Hello World\n”); return 0; } Compilation occurs in two steps: “Preprocessing” and “Compiling” Preprocess 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 ( \ ) __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; } Why preprocess? Having two phases to a process with different properties often helps to make a very flexible yet robust system. The underlying compiler is very simple and its behavior is easily understood. But because of that simplicity it can be hard to use. The preprocessor lets you “customize” the way your code “looks and feels” and avoid redunancy using a few simple facilities, without increasing the complexity of the underlying compiler. Macros can be used to make your code look clean and easy to understand. They can also be used for “evil”. What are continued lines? Continued lines are lines that need to be very long. When the preprocessor encounters a ‘\’ (that is not inside a string), it will ignore the next character. If that character is a newline, then this “eats” the newline and joins the two lines into one. This is often used when defining macros with #define, because a macro must be all on one line. Be careful! If you have a space after a ‘\’, it will eat the space and will NOT join the lines. my_program The compiler then converts the resulting text into binary code the CPU can run directly. Compile

24 What is a Function? 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. Return type, or void Function Arguments #include <stdio.h> /* The simplest C Program */ int main(int argc, char **argv) { printf(“Hello World\n”); return 0; } Include directives use <x.h> (brackets) to indicate that the compiler should look in a “standard” place, such as /usr/include/… They use “x.h” (double quotes) to indicate that it should look first in the current directory. 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. Returning a value

25 What is “Memory”? Memory is like a big table of numbered slots where bytes can be stored. Addr Value 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. 72? Some “logical” data values span more than one slot, like the character string “Hello\n” A Type names a logical meaning to a span of memory. Some simple types are: What’s 72? ASCII is the coding scheme that maps bytes to characters. Type ‘man ascii’ at the shell to get a listing of the mapping. Not always… Types such as int vary in size depending on the architecture. On a 32 bit or 64 bit platform, ints are 4 bytes (32 bits). On an 8 or 16 bit platform, an int is 2 bytes (16 bits). To be safe, it’s best to specify types exactly e.g. int32_t, int16_t., int8_t. Defined in #include <inttypes.h> Signed? Signedness is a common source of problems in C. It’s always clearest to specify signness explicitly (and size) using the [u]int[8,16,32]_t types. Signedness can introduce surprises when casting types because of “sign extension”. For example, char is signed (although it’s normally used as unsigned 0-255). If you cast char to int, it will be a signed integer and the sign will be extended. If you then cast that to unsigned, it turns a small negative number into an enormous int value (high bit set). That is, (uint32_t)(int)(char)(128) == (not 128!) One easy solution to this is to always use uint8_t rather than char for byte streams. a single character (1 slot) an array of 10 characters signed 4 byte integer 4 byte floating point signed 8 byte integer char char [10] int float int64_t not always… Signed?…

26 What is a Variable? symbol table? A Variable names a place in memory where you store a Value of a certain Type. Symbol Addr Value 1 2 3 x 4 ? y 5 ‘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 char x; char y=‘e’; The compiler puts them somewhere in memory. Symbol table: The “Symbol Table” is the mapping from symbol to address. You can extract this from a compiled program (if debugging is enabled aqt compile time with –g) using the nm utility. Declaration and definition mean slightly different things in C. Declaration is mapping a name to a type, but not to a memory location. Definition maps a name and type to a memory location (which could be the body of a function). Definitions can assign an initial value. Declarations can point to something that never actually gets defined, or is defined in a library external to your program. What names are legal? Symbols in C (function and variable names) must start with an alphabetic character or ‘_’. They may contain numeric digits as well but cannot start with a digit. Common naming strategies are ‘CamelCase’, ‘lowerUpper’, and ‘under_bar’. Some people use complicated schemes but I prefer under_bar. extern, static, and const are modifiers of variable declarations. ‘extern’ means the variable being declared is defined elsewhere in some other program module (.c file). ‘static’ means that the variable cannot be accessed outside of the current scope. ‘const’ means the variable’s value cannot be changed (directly).

27 Multi-byte Variables 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) Symbol Addr Value 1 2 3 x 4 ? y 5 ‘e’ (101) 6 7 z 8 9 10 11 12 char x; char y=‘e’; int z = 0x ; 0x means the constant is written in hex padding An int consumes 4 bytes

28 VARIABLES int x; char gender; float avg; float sum=0; char name[10];
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;

29 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

30 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 ,

31 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.

32 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’ ;

33 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 types Derived Data Types integer short, long float Double char

34 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 : C compiler allocates 4 bytes (32 bits) to an integer (int) variable. An integer variable can store values in the range –32, 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.

35 Data Types and Sizes : (Continued)
The sizes of long and short is differentiated from int. The data type unsigned is used only with positive integers. Data Types Bytes Used int 4 Bytes short 2 Bytes double 8 Bytes unsigned

36 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: The double data type requires 8 bytes and has a precision of fifteen digits Example :  

37 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 is represented in C as e5 or e+5 or 1.23E5 1 x is represented in C as 1e-9

38 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

39 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’ , ……. )

40 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

41 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 )

42 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

43 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. Operators Associativity Priority Level ( , ) Left to Right Highest + , - ( unary ) Right to Left * , / , % + , - Lowest parentheses -ve and +ve signs Mult. Div., and mod. Add and subtract

44 Expressions and Evaluation
Expressions combine Values using Operators, according to precedence. 1 + 2 *   5 (1 + 2) * 2  3 *  6 Symbols are evaluated to their Values before being combined. int x=1; int y=2; x + y * y  x + 2 *  x   5 Comparison operators are used to compare values. In C, 0 means “false”, and any other value means “true”. int x=4; (x < 5)  (4 < 5)  <true> (x < 4)  (4 < 4)  0 ((x < 5) || (x < 4))  (<true> || (x < 4))  <true> Not evaluated because first clause was true

45 Comparison and Mathematical Operators
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! == 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 & bitwise and | bitwise or ^ bitwise xor ~ bitwise not << shift left >> shift right 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 Don’t confuse & and &&.. 1 & 2  0 whereas 1 && 2  <true>

46 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 ? = % 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 – * 6 Evaluated as 9 – 4 + (2*6) and the result is 17 ? = * (3 + 4) Evaluated as 1 + (2 * (3+4)) and the result is 15 ? = 5 * % 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

47 That’s It for now! Next Lecture: More on varIables, data types and expressions


Download ppt "ITEC113 Algorithms and Programming Techniques"

Similar presentations


Ads by Google