Anda di halaman 1dari 53

Introduction to programming in C Lecture

Introduction

References Reference book:

P .J.Deitel and H.M. Deitel, C How to Program, Fifth Edition, Pearson Prentice-Hall, 2007. Jeri R.Hanly and Elliot B.Koffman, Problem Solving and Program Koffman, Design in C, Sixth Edition, Addison Wesley, 2009 Brian W.Kernighan and Dennis M. Ritchie, C Programming Language, Second Edition, Prentice Hall, PTR,1988. Anany Levitin, Introduction to The Design and Analysis of Algorithms, PearsonAddison Wesley, Wesley,2003.

Course Outline
P Programming Methodologies Algorithm Design Flowcharts and Pseudo Codes Top-down Program Design Language) P Structured Language (focus on CLanguage Data Types, Declarations, Operators and Expressions Input and Output Control Structures Functions and Program Structure Pointers Arrays, Strings, and Unions File Processing P Discipline of Programming Programming Style Structured Coding and Program Modularity Program Documentation and Maintenance
4

Outline Basic computer concepts Different types of programming languages Cprogramming language

History CStandard Library Object-oriented Programming Typical CProgram Development Environment

Introduction to Cprogramming language programming

What is a Computer?
Computer Device capable of performing computations and making logical decisions (hardware) Computers process data under the control of sets of instructions called computer programs (software) Hardware Various devices comprising a computer, such as central processing unit (CPU), memory, motherboard and hard disks as well as peripheral devices (keyboard, mouse, external display, optical drive) Hardware trends - Every year or two the following approximately double:
Amount of memory in which to execute programs The processor speed at which computers execute their programs (Moores Law)

Software Programs that run on a computer


6

Computer Organization S Six logical units in every computer:

Input unit Obtains information from input devices (keyboard, mouse)

Output unit
Outputs information (to screen, to printer, to control other devices)

Memory unit
Rapid access, low capacity, stores input information

Arithmetic and logic unit (ALU)


Performs arithmetic calculations and logic decisions

Central processing unit (CPU)


Supervises and coordinates the other sections of the computer ALU is now a fundamental building block of the CPU

Secondary storage unit


capacity Cheap, long-term, high-capacity storage

Hardware

Evolution of Operating Systems Batch processing

Do only one job or task at a time Resource managment and sharing for multiple programs Quasi-simultaneous program execution Single user

Multiprogramming

Multiuser/Timesharing Systems stems


Management of multiple simultaneous users interconnected via terminals Fair resource management: CPU scheduling

Operating Systems

10

Personal Computing, Distributed Computing, and Client/Server Computing

P Personal computers

Economical enough for individual Computing distributed over networks Sharing of information across computer networks between file servers and clients

P Distributed computing

P Client/server computing

11

Personal Computing, Distributed Computing, and Client/Server Computing

12

Outline Basic computer concepts Different types of programming languages Cprogramming language

History CStandard Library Object-oriented Programming Typical CProgram Development Environment

Introduction to Cprogramming language programming

13

Machine Languages, Assembly Languages, and High-level Languages

Three types of programming languages

Machine languages
machine specific instructions, executed by CPU lowest level representation of computer program

Assembly languages
English-like abbreviations representing elementary computer operations (translated via assemblers) Example: mov ax, 1234h (mov value 1234h into register ax)

High-level languages
Codes similar to everyday English Use mathematical notations (translated via compilers) Example: grossPay = basePay + overTimePay

14

Outline
Basic computer concepts Different types of programming languages Cprogramming language His History CStandard Library His Object-oriented Programming His His Typical CProgram Development Environment

Introduction to Cprogramming language programming

15

History of C C

Evolved by Dennis Ritchie from two previous programming languages, BCPLand B Used to develop UNIX Used to write modern operating systems Hardware independent (portable) Many slight variations of Cexisted, and were incompatible existed, Committee formed to create a "unambiguous, machineindependent" definition Standard created in 1989, updated in 1999

Standardization

16

CStandard Library C programs consist of pieces/modules called functions

Aprogrammer can create his own functions


Advantage: the programmer knows exactly how it works Disadvantage: time consuming

Programmers will often use the C Clibrary functions


Use these as building blocks

Avoid re-inventing the wheel


If a premade function exists, generally best to use it rather than write your own Library functions carefully written, efficient, and portable

17

Outline
B Basic computer concepts t B Different types of programming languages t B Cprogramming language t Hist History CStandard Library Hist Object-oriented Programming Hist Hist Typical CProgram Development Environment

programming B Introduction to Cprogramming language t

18

C++ . C++

Superset of Cdeveloped by Bjarne Stroustrup at Bell Labs "Spruces up" C, and provides object object-oriented capabilities Object-oriented design very powerful
10 to 100 fold increase in productivity

. Learning C++

BecauseC++ includes C,some feel it is best to master C, then learn C++

19

Java Java is used to


Create Web pages with dynamic and interactive content Develop large-scale enterprise applications Enhance the functionality of Web servers Provide applications for consumer devices (such ascell phones, pagers and personal digital assistants)

20

Outline
Basic computer concepts Different types of programming languages Cprogramming language His History CStandard Library His Object-oriented Programming His His Typical CProgram Development Environment

Introduction to Cprogramming language programming

21

A Typical CProgram Development Environment

P Phases of CPrograms: Edit (Cprogram file names should end with the .c extension) Preprocess Compile Link Load Execute

22

Outline
Basic computer concepts Different types of programming languages Cprogramming language His History CStandard Library His Object-oriented Programming His His Typical CProgram Development Environment

Introduction to Cprogramming language programming

23

Outline Print a line Escape sequence Variables and Data types Memory concepts Arithmetic operators If-then statements Review

24

A Simple CProgram: Printing a Line of Text


Example 01:

/* and */ indicate comments ignored by compiler #include directive tells C to load a particular file Left brace declares beginning of main function Statement tells C to perform an action return statement ends the function Right brace declares end of main function

Comments T surrounded by / * and * / is ignor by computer ext red Used to describe program

#include <stdio.h>

Adirective to the Cpreprocessor T computer to load contents of a certain file ells <stdio.h> allows standard input/output operations
25

A Simple CProgram: Printing a Line of Text


int m a i n ( )

C programs contain one or more functions, exactly one of which must be main Parenthesis used to indicate a function int means that main "returns" an integer value Braces({ and }) indicate a block

The bodies of all functions must be contained in braces p r i n t f ( "Welcome to C! \n" ) ;

Instructs computer to perform an action


Specifically, prints the string of characters within quotes (" " )

Entire line called a statement


All statements must end with a semicolon (; )

Escape character (\ )
Indicates that printf should do something out of the ordinary \n is the newline character
26

A Simple CProgram: Printing a Line of Text


return 0;

Away to exit a function return 0, in this case, means that the program terminated normally Indicatesend of main has been reached When a function is called, linker locates it in the library Inserts it into object program If function name is misspelled, the linker will produce an error because it will not be able to find function in the library

Right brace }

Linker

27

Outline Print a line Escape sequence Variables and Data types Memory concepts Arithmetic operators If-then statements Review

28

Some common escape sequences

29

The printf function can print Welcome to C! several different ways

Example 02:

fig02_03.c

printf statement starts printing from where the last statement ended, so the text is printed on one line.

30

The printf function can print Welcome to C! several different ways

Example 03:

Newline characters m move the cursor to the next line

31

Objectives Print a line Escape sequence Variables and Data types Memory concepts Arithmetic operators If-then statements Review

32

Example 04:

Definitions of variables scanf obtains a value from the user and assigns it to integer1 scanf obtains a value from the user and assigns it to integer2 Assigns a value to sum

Another Simple C Program: Adding Two ntegers ogram: I

33

Another Simple CProgram: Adding Two Integers As before

Comments, #include <stdio.h> and main Definition of variables


Variables: locations in memory where a value can be stored i n t means the variables can hold integers (-1, 3, 0, 47)

i n t i n t e g e r 1 , i n t e g e r 2 , sum;

Variable names (identifiers)


integer1, integer2, sum Identifiers: consist of letters, digits (cannot begin with a digit) and underscores( _ )
Casesensitive

Definitions appear before executable statements


If an executable statement references and undeclared variable it will produce a syntax (compiler) error
34

Another Simple CProgram: Adding Two Integers


s scanf( "%d", &integer1 ) ;

Obtains a value from the user


scanf uses standard input (usually keyboard)

This scanf statement has two arguments


% - indicates data should be a decimal integer d &integer1 - location in memory to store variable & is confusing in beginning for now, just remember to include it with the variable name in scanf statements

When executing the program the user responds to the scanf statement by typing in a number, then pressing the enter (return) key

35

Outline Print a line Escape sequence Variables and Data types Memory concepts Arithmetic operators If-then statements Review

36

Memory Concepts Variables


Variable names correspond to locations in the computer's memory Every variable has a name, a type, a size and a value Whenever a new value is placed into a variable (through scanf, for example), it replaces(and destroys) the previous value Reading variables from memory does not change them

Memory location showing the name and value of a variable.

37

Memory Concepts

input. Memory locations after both variables are inpu

Memory locations after a calculation.

38

Outline Print a line Escape sequence Variables and Data types Memory concepts Arithmetic operators If-then statements Review

39

Another Simple CProgram: Adding Two Integers


= =

(assignment operator)
Assigns a value to a variable Is a binary operator (has two operands)
sum = variable1 + var iable2; sum gets variable1 + variable2;

Variable receiving value on left Similar to scanf


% dmeans decimal integer will be printed sum specifies what integer will be printed

= p r i n t f ( "Sum i s %d\n", sum ) ;

Calculations can be performed inside p r i n t f statements


p r i n t f ( "Sum i s %d\n", integer1 + integer2 ) ;

40

Arithmetic A Arithmetic calculations


Use * for multiplication and / for division Integer division truncates remainder
7/5 evaluates to 1

Modulus operator(% returns the remainder )


7 % 5 evaluates to 2

A Operator precedence

Some arithmetic operators act before others (i.e., multiplication before addition)
Use parenthesis when needed

Example: Find the average of three variables a, b and c


Do not use: a + b + c / 3 Use: (a + b + c ) / 3
41

Arithmetic A Arithmetic operators: r

ecedence: A Rules of operatorprecedence: r

42

Example: operator precedence

43

Outline Print a line Escape sequence Variables and Data types Memory concepts Arithmetic operators If-then statements Review

44

Decision Making: Equality and Relational Operators E Executable statements


Perform actions (calculations, input/output of data) Perform decisions


May want to print "pass" or "fail" given the value of a test grade

E if control statement

If a condition is true, then the body of the if statement executed


0 is false, non-zero is true

Control always resumes after the if structure

45

Decision Making: Equality and Relational Operators

46

An Example to Use if statements, relational operators, and equality operators


Example 05:

Checks if num1 is equal to num2 Checks if num1 is not equal to num2

Checks if num1 is less than num2

47

Checks if num1 is greater than num2

Checks if num1 is less than or equal to num2

Checks if num1 is greater than equal to num2

48

49

Precedence and associativity of the operators discussed so far

Cs keywords.

Keywords Specialwords reserved for C Cannot be used asidentifiers or variable names

50

Outline Print a line Escape sequence Variables and Data types Memory concepts Arithmetic operators If-then statements Review

51

Review Comments begin with / * and end with * / . Comments document programs and improve readability. The #include directive tells the preprocessor to include the content of another file (typically a header file such as <stdio.h> ). The <stdio.h> header contains information used by the compiler when compiling calls to standard input/output library functions such as pr intf . Every program in Cbegins executing at the function main. Functions can return information. Functions can receive information. Afunction starts by a left brace { and ends by a right brace } . Every statement must end by a semicolon semicolon. Escapesequences, for example \ newline. \n
52

Review Avariable is a location in memory where a value can be stored for use by a program. All variables must be defined with a name and a data type before they can be used in a program. The %d indicates that the data should be an decimal integer. The & indicates the memory address of an variable. Function p r i n t f can also use a format control string. Every variable has a name, a type and a value. Variable names correspond to locations in the computers memory. Arithmetic operators and precedence.

53

Review
if

statement allows a program to make a decision based on the truth or falsity of a statement of fact called a condition. Conditions in if statement are formed by using the equality operators and relational operators. The precedence of relational operators = should be readgets and == should be readdouble equals. Keywords.

54