ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

48
ITEC113 Algorithms and Programming Techniques C programming: Variables, Expressions Part I

Transcript of ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

Page 1: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

ITEC113 Algorithms and Programming Techniques

C programming: Variables, Expressions Part I

Page 2: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 3: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

Introduction to Computer Systems

• Hardware• Software

Page 4: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

Hardware

M em ory

C PU

InputD evices

O utpu tD evices

Page 5: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

– 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

Page 6: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 7: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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)

Page 8: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

Machine binary language Low-level assembly High-level

An example

Page 9: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

• 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

Page 10: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 11: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

• 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

Page 12: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 13: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

Basics of C Environment

Editor DiskPhase 1

Program edited in Editor and storedon disk

Preprocessor DiskPhase 2

Preprocessor program processesthe code

Compiler DiskPhase 3

Creates object code and stores on disk

Linker DiskPhase 4

Links object code with libraries and stores on disk

Page 14: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

Basics of C Environment

LoaderPhase 5

Puts program in memory

Primary memory

CPUPhase 6

Takes each instructionand executes it storingnew data values

Primary memory

Page 15: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

C om pile

L ink

L ib ra ry routines

O ther ob jec t files

Th ink

E d it

Load

E xecu te

S ource Program

debug

Page 16: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 17: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

17

C Syntax and Hello World

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

#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?

Page 18: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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.

Page 19: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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.

©1992-2010 by Pearson Education, Inc. All Rights Reserved.

Page 20: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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.

Page 21: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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.

Page 22: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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.

Page 23: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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.

Page 24: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

24

About the C Compiler#include <stdio.h>

/* 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.

Page 25: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

25

What is a Function?

#include <stdio.h>

/* 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

Page 26: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

26

What is “Memory”?Memory is like a big table of numbered slots where bytes can be stored.

Addr Value

0

1

2

3

4 ‘H’ (72)

5 ‘e’ (101)

6 ‘l’ (108)

7 ‘l’ (108)

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]intfloatint64_t

a single character (1 slot)an array of 10 characterssigned 4 byte integer4 byte floating pointsigned 8 byte integer

not always…

Signed?…

Page 27: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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.

Symbol Addr Value

0

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

The compiler puts them somewhere in memory.

symbol table?

Page 28: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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)

Symbol Addr Value

0

1

2

3

x 4 ?

y 5 ‘e’ (101)

6

7

z 8 4

9 3

10 2

11 1

12

0x means the constant is written in hex

An int consumes 4 bytes

padding

Page 29: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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;

Page 30: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 31: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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 ,

Page 32: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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.

Page 33: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 34: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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, longfloat Double char

Page 35: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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 –6 208 1024• 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.

Page 36: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

Data Types and Sizes : (Continued)

Data Types Bytes Used

int 4 Bytes

short 2 Bytes

double 8 Bytes

unsigned 4 Bytes

•The sizes of long and short is differentiated from int.• The data type unsigned is used only with positive integers.

Page 37: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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.322344 0.3333333

0.1234567• The double data type requires 8 bytes and has a precision

of fifteen digitsExample :

-3738.7878787878 3.141592653589790 0.123456789123456

Page 38: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 39: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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 charactersExample: A is represented by decimal 65 or

8-bit binary 0 1 0 0 0 0 0 1

Page 40: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 41: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 42: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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 )

Page 43: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 44: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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* , / , % Left to Right+ , - Left to Right Lowest

parenthesesparentheses

-ve and +ve -ve and +ve signssignsMult. Div., and Mult. Div., and modmod..Add and Add and

subtractsubtract

Page 45: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

45

Expressions and EvaluationExpressions 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 < 5) (4 < 5) <true>(x < 4) (4 < 4) 0((x < 5) || (x < 4)) (<true> || (x < 4)) <true>

Not evaluated because first clause was true

Page 46: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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 <true>

Page 47: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

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

Page 48: ITEC113Algorithms and Programming Techniques C programming: Variables, Expressions Part I.

THAT’S IT FOR NOW!NEXT LECTURE: MORE ON VARIABLES, DATA TYPES

AND EXPRESSIONS