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

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

Introduction to C Programming
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
Data types and variables
 2003 Prentice Hall, Inc. All rights reserved. 1 Machine Languages, Assembly Languages, and High-level Languages Three types of computer languages 1.Machine.
Chapter 2 Data Types, Declarations, and Displays
Chapter 2: Introduction to C++.
Introduction to C Programming
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Basic Elements of C++ Chapter 2.
Using C Programming Language.  The programs that run on a computer are referred to as software.  You’ll learn key programming methodology that are enhancing.
Using C Programming Language.  The programs that run on a computer are referred to as software.  You’ll learn key programming methodology that are enhancing.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Chapter 01: Introduction to Computer Programming
COMPUTER SCIENCE I C++ INTRODUCTION
Objectives You should be able to describe: Data Types
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Outline Variables 1.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Chapter 2: Using Data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Week 1 Algorithmization and Programming Languages.
COMPUTER PROGRAMMING. A Typical C++ Environment Phases of C++ Programs: 1- Edit 2- Preprocess 3- Compile 4- Link 5- Load 6- Execute Loader Primary Memory.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
C++ for Engineers and Scientists Second Edition
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Introduction to C Programming
1 Types of Programming Language (1) Three types of programming languages 1.Machine languages Strings of numbers giving machine specific instructions Example:
By Kundang K Juman Hardware & Software. COMP102 Prog. Fundamentals I: Software / Slide 2 l Four components of a computer system: n CPU - central processing.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
ITEC113 Algorithms and Programming Techniques
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1: Introduction to computers and C++ Programming
Chapter 2 Introduction to C++ Programming
CSC201: Computer Programming
Chapter 2 - Introduction to C Programming
Chapter 2, Part I Introduction to C Programming
ITEC113 Algorithms and Programming Techniques
Basic Elements of C++.
Chapter 2 - Introduction to C Programming
Introduction to C Programming
Basic Elements of C++ Chapter 2.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Chapter 2 - Introduction to C Programming
Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 2: Introduction to C++.
Programs written in C and C++ can run on many different computers
Capitolo 1 – Introduction C++ Programming
Chapter 2 - Introduction to C Programming
Introduction to C Programming
Presentation transcript:

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

Introduction to Computer Systems Hardware Software

Hardware

– 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

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

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)

Machine binary languageLow-level assemblyHigh-level An example

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

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

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

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

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

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

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

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

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.

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

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

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

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

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.

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 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 What is “Memory”? Memory is like a big table of numbered slots where bytes can be stored. AddrValue ‘H’ (72) 5‘e’ (101) 6‘l’ (108) 7 8‘o’ (111) 9‘\n’ (10) 10‘\0’ (0) 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 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 x4? y5‘e’ (101) 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 Multi-byte Variables char x; char y=‘e’; int z = 0x ; 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 x4? y5‘e’ (101) 6 7 z x means the constant is written in hex An int consumes 4 bytes padding

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;

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

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,

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.

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

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

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

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.

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 :

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 is represented in C as 1e-9

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

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

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

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 )

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

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 Expressions and Evaluation Expressions combine Values using Operators, according to precedence * 2   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   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 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 

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

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