60 140 01 INTRODUCTION TO ALGORITHMS PROGRAMMING I

  • Slides: 128
Download presentation
60 -140 -01 INTRODUCTION TO ALGORITHMS & PROGRAMMING I Dr. Robert D. Kent Winter

60 -140 -01 INTRODUCTION TO ALGORITHMS & PROGRAMMING I Dr. Robert D. Kent Winter 2009

COURSE DESCRIPTION This course is the first of a two-course sequence designed to introduce

COURSE DESCRIPTION This course is the first of a two-course sequence designed to introduce students to algorithm design and programming in a high-level language such as C. The main objectives of the course are to develop the ability to identify, understand design solutions to a wide variety of problems. Topics include: computer system overview, hardware and software, problem solving steps, concepts of variables, constants, data types, algorithmic structure, sequential logic, decisions, loops, modular programming, one-dimensional arrays, text files. If possible, problems like searching/sorting will be addressed.

60 -140 -01 COURSE OUTLINE – IT MATTERS Dr. Robert D. Kent Winter 2009

60 -140 -01 COURSE OUTLINE – IT MATTERS Dr. Robert D. Kent Winter 2009

COURSE OUTLINE – IT MATTERS! Instructor: Dr. Robert D. Kent Email: rkent@uwindsor. ca (Preferred)

COURSE OUTLINE – IT MATTERS! Instructor: Dr. Robert D. Kent Email: rkent@uwindsor. ca (Preferred) Office: 5100 Lambton Tower Phone: 519 -253 -3000 ext. 2993 (Email preferred) Office Hours: Tuesday & Thursday 11: 00 am – 2: 00 pm (subject to cancellation without notice; or by appointment) Lab Instructor: Ritu Chaturvedi (rituch@uwindsor. ca) Note: Only email originating from a valid University of Windsor student account will be accepted from students wishing to contact the instructor. Please include your full name and student ID in your correspondence.

COURSE OUTLINE (CONTINUED) Graduate Teaching Assistants: GA’s help in the labs and students should

COURSE OUTLINE (CONTINUED) Graduate Teaching Assistants: GA’s help in the labs and students should ask questions GA’s will evaluate lab work, mark assignments and examinations (under the supervision of the instructor) GA’s will hold consulting office hours at times and places to be announced The GA staff (email addresses on outline): Luo, Fangyun Mabroukeh, Nizar Soleimani, Ahmad Wang, Zhuo

COURSE OUTLINE (CONTINUED) Pre-Requisities: This is an introductory level course with no pre-requisites and

COURSE OUTLINE (CONTINUED) Pre-Requisities: This is an introductory level course with no pre-requisites and is required for all programs leading to a degree in Computer Science (including combined degrees). This course may be required by certain other programs. Students who have taken courses in Computer Science in secondary school may find some material to be review; however, students are strongly advised that the required depth and breadth of coverage of topics in this course, as well as the expectations of required performance in labs, assignments and examinations may be very challenging in comparison with secondary school courses. Students may require special permission to take this course as it is intended, in the first instance, for students in the MCA program of study.

COURSE OUTLINE (CONTINUED) LABS: You must register in one of the following sections: Section

COURSE OUTLINE (CONTINUED) LABS: You must register in one of the following sections: Section 51 -53 (Note: 54 is on HOLD) All labs are held in the West Leddy Libary Room 305 NOTE: Laboratory attendance is mandatory. Labs start on Monday January 12. You must have a working student computer account before coming to the lab. You can obtain a UWINID account from the Computer Centre or call ITS ext. 4440.

COURSE OUTLINE (CONTINUED) Required Textbook: Deitel, H. M. and Deitel P. J. C How

COURSE OUTLINE (CONTINUED) Required Textbook: Deitel, H. M. and Deitel P. J. C How To Program, 5 th Edition. Prentice-Hall: New Jersey. NOTE: Earlier editions of the textbook may be used, but all references to the textbook will apply to the 5 th edition. Some students may wish to use another textbook. There are many good texts covering C programming and algorithms, but they are not supported in this course.

COURSE OUTLINE (CONTINUED) Evaluation Scheme: 17% Midterm #1 (in class – 75 minutes) 17%

COURSE OUTLINE (CONTINUED) Evaluation Scheme: 17% Midterm #1 (in class – 75 minutes) 17% Midterm #2 (in class – 75 minutes) 45% Final Exam (Location TBA by Instructor) 10% Laboratory (Mandatory Attendance, Lab Exercises, Quizzes and Lab Exams) 10% Assignments 1% Lecture attendance and participation (in class, up to 3 randomly selected classes by the instructor without prior notice, and/or up to 3 unannounced Quizzes) NOTE: Consistent with University Senate Bylaws, no required (ie. marked) work will be assigned to students during the last 3 days of Intersession lectures, nor will any assigned work come due for submission during this same period.

COURSE OUTLINE (CONTINUED) Assignments and projects (eg. Lab exercises) are expected to be completed

COURSE OUTLINE (CONTINUED) Assignments and projects (eg. Lab exercises) are expected to be completed on the assigned due date and time. LATE ASSIGNMENTS ARE NOT ACCEPTED. You must allocate enough time to complete the assignments; start early and report difficulties to the instructor. UNDOCUMENTED CODE WILL NOT BE GRADED and will receive a mark of zero. Failure to submit the work in the correct format will be penalized. (i. e. incorrect email subject or unreadable/missing file attachments as instructed, etc…). All submitted work MUST be prepared and must be compilable and executable on the Computer Science servers.

COURSE OUTLINE (CONTINUED) THERE IS NO MAKE-UP EXAM FOR MIDTERMS. Missing a test or

COURSE OUTLINE (CONTINUED) THERE IS NO MAKE-UP EXAM FOR MIDTERMS. Missing a test or an exam will greatly affect your grade since they carry a lot of weight. In the case of illness or serious and unavoidable reason (as per the Senate Bylaws), please consult with the instructor in advance, if possible, to make alternate arrangements. You must formally inform the instructor in writing and present proper supporting documents (stating that the student was unable to attend the exam at the specified time and date) within a week from the midterm or earlier to be verified. If the reason is deemed valid, the weight of the midterm will be added to that of the final exam. (i. e. the final exam’s weight will increase to include the missed midterm weight). All students are required to write and PASS the final exam in order to pass the course.

COURSE OUTLINE (CONTINUED) NO MAKE-UP FINAL EXAMINATION. Students who miss the Final Examination due

COURSE OUTLINE (CONTINUED) NO MAKE-UP FINAL EXAMINATION. Students who miss the Final Examination due to valid reasons will normally be required to write the Final Examination in the next semester the course is offered (eg. Fall 2008). Keep in mind that non-completion of a pre-requisite course will prevent students from progressing in their program of study.

COURSE OUTLINE (CONTINUED) PLAGIARISM: Should the instructor or grader find a reason for suspicion

COURSE OUTLINE (CONTINUED) PLAGIARISM: Should the instructor or grader find a reason for suspicion – or just cause – in plagiarized student work (assignment, lab or test), the work in question will not be graded and the student(s) will have to answer to the department’s Director and the Dean of Science. Refer to the University’s policy on Plagiarism in the Senate Bylaws. This issue is taken extremely seriously and students who are found guilty of plagiarism may suffer considerable short and long term negative effects. Students who submit semantically equivalent assignments [or labs] (in other words, the same thing to within trivial modifications) will receive a grade of zero on ALL assignments [or labs].

COURSE OUTLINE (CONTINUED) All students should keep the instructor informed about their difficulties with

COURSE OUTLINE (CONTINUED) All students should keep the instructor informed about their difficulties with the course. To the extent possible, students should contact the instructor outlining their problems with the course. Most consultations will be by e-mail or in person. What you learn today, you must practice at for tomorrow! This course is a vital pre-requisite for other courses – some in the next semester (eg. 60 -141) and others in Years 2, 3 or 4. Pre-requisite does not just refer to Calendar course regulations; it really means retaining a core basis of understanding and competency over time (ie. don`t forget what you`ve learned, just because you haven`t had a course recently).

COURSE OUTLINE (CONTINUED) Late Assignment Penalty Waiver/Bonus Coupon Usage: This coupon is primarily intended

COURSE OUTLINE (CONTINUED) Late Assignment Penalty Waiver/Bonus Coupon Usage: This coupon is primarily intended to provide the student extra time to complete an assignment properly if the need arises for whatever reason. Use this coupon if you feel you are unable to submit the assignment on time. It grants you to extend the original deadline by 72 hours without being penalized for late submission. If you successfully complete ALL assignments on time, and do not use this coupon for the purpose of time extension, then you may submit this coupon in person to the instructor on or before the last official lecture and earn 1% toward your cumulative total of the assignments. For late waiver, the student must notify the instructor and submit the coupon in person within 24 hours from the original assignment due date. If you submit the coupon for late waiver and do not submit the assignment, or submit it after 72 hours from the original due date, then you will lose the coupon value and your assignment will not be graded. Rules: Limit one per student. Not valid with any other offer. Coupon expires at the end of your last regular lecture. Non-negotiable, not redeemable for marks other than that specified above, not transferable. No late coupon submission is accepted once the offer expires. The instructor reserves the right to refuse or cancel this coupon offer at any time without notification. You must present this original coupon in person and in class before the end of the last lecture to the instructor. Copies or digital reproductions are not accepted. PLEASE COMPLETE ALL FIELDS LEGIBLY PRINT NAME: ____________________________ LECTURE SECTION: ___01____ LAB SECTION: ____ Last name, First name STUDENT ID: ____________________________ CHECK ONE: DATE: ____________________ WAIVE LATE PENALTY FOR ASSIGNMENT NUMBER: ______ DUE: _______ (This grants the student up to 72 hours to submit the assignment from the original due date/time without penalty. Submitting the assignment after the 72 hours grace period is considered late and will be penalized accordingly; not submitting the assignment void the coupon and as a result the coupon can no longer be used for “bonus” and the assignment mark will be zero. This coupon does not apply for labs. ) or: CLAIM 1 BONUS POINT (Valid only if ALL assignments were successfully submitted on time)

COURSE OUTLINE (CONCLUSION) A University of Windsor graduate will have the ability to demonstrate:

COURSE OUTLINE (CONCLUSION) A University of Windsor graduate will have the ability to demonstrate: the acquisition, application and integration of knowledge research skills, including the ability to define problems and access, retrieve and evaluate information (information literacy) critical thinking and problem-solving skills literacy and numeracy skills responsible behaviour to self, others and society interpersonal and communications skills teamwork, and personal and group leadership skills creativity and aesthetic appreciation the ability and desire for continuous learning

COMPUTERS, SYSTEMS AND NETWORKS Lecture 1 A

COMPUTERS, SYSTEMS AND NETWORKS Lecture 1 A

OVERVIEW AND MOTIVATION To begin, let’s reflect on what we might know. Then we’ll

OVERVIEW AND MOTIVATION To begin, let’s reflect on what we might know. Then we’ll consider what we might be able to do if we learn more.

COMPUTERS, SYSTEMS AND NETWORKS Computer system overview Hardware and software Operating systems Application programs

COMPUTERS, SYSTEMS AND NETWORKS Computer system overview Hardware and software Operating systems Application programs Editors and compilers Programming paradigms and languages The Internet and World Wide Web

COMPUTER SYSTEM OVERVIEW Modern computing systems consist of hardware devices and software logic Hardware

COMPUTER SYSTEM OVERVIEW Modern computing systems consist of hardware devices and software logic Hardware Dedicated microprocessors and sensors Storage Fully integrated personal and server computers Networks interconnecting devices Wireless, mobile Software Operating systems, File systems Application programs Communications protocols

HARDWARE Charles Babbage (~1850) and System John von Neuman Computer (~1950) provided the basic

HARDWARE Charles Babbage (~1850) and System John von Neuman Computer (~1950) provided the basic model of a stored Computer program digital computer. Input Device Data CPU Bus Main Memory Output Device Control Five Main Components: 1. CPU 2. Main Memory (RAM) 3. I/O Devices 4. Mass Storage 5. Interconnection network (Bus) Bus Secondary Storage Device

NOTE: CPU’s do not make any sense of human readable text. Rather, they respond

NOTE: CPU’s do not make any sense of human readable text. Rather, they respond to and act on groups (strings) of bits, according to the engineered capabilities of individual components. IMPLICATION: Charles Babbage Computer (~1850) and von Neuman Logic. John Sub-system Programs written as characters (text) must be converted (transformed) (~1950) provided the basic of“comprehend”. a stored into appropriate binary encodings that themodel CPU can Computer HARDWARE program digital computer. Data Main Memory CPU Character Input (program) Control Processing of binary encoded strings of bits (instructions and data) Secondary Storage Device Character and Binary files

HARDWARE Some computer scientists focus on design of hardware, but in recent years this

HARDWARE Some computer scientists focus on design of hardware, but in recent years this study has become the focus of computer engineers. Computer science is primarily concerned with how to express the logic of a problem solution using the fundamental capabilities of the machines available. It is useful, if not necessary, to understand how hardware works (instruction sets) and what are its limitations (speed, precision, error) A useful concept is that of a primitive, or atomic, operation. Most CPU instructions (built as electronic circuits) are always guaranteed to complete their operation, once it has been commenced.

HARDWARE Students may take courses in digital design and logic and assembly/machine language programming.

HARDWARE Students may take courses in digital design and logic and assembly/machine language programming. We will discuss only some relevant aspects of hardware appropriate to the conceptual discussion of programming logic. Data representations Instruction types and timing Volatile Memory (RAM)

SOFTWARE As much as hardware defines the limiting capability of a (set of) machines

SOFTWARE As much as hardware defines the limiting capability of a (set of) machines to carry out a specific set of logical operations, software is the actual set of operations expressed as executable units. A program is a static entity stored on a disk. It does not actually do anything, though it may have the potential to solve a problem. A process is a dynamic entity that has been loaded into volatile memory (RAM) while notifying the Operating System to provide resources (such as memory space, file access and time on the CPU) For simplicity, we will often use the generic name “program”.

SOFTWARE The act of designing and perfecting a program is referred to as programming.

SOFTWARE The act of designing and perfecting a program is referred to as programming. More recently, the techniques of design have become formalized in the study of software engineering. Software takes many forms and uses: Operating systems Application programs Editors, word processors Email, ftp, communications Engineering, Science, Social Science, Finance …. . Data structures (protocols) File systems

OPERATING SYSTEMS Operating systems (O/S’s) are programs that are used to manage the underlying

OPERATING SYSTEMS Operating systems (O/S’s) are programs that are used to manage the underlying hardware systems of computers Resource allocation Device control Programs Process concurrency Inter-process communication Communication sockets, port allocation Files Fault detection and recovery Security Often designed using the C language

APPLICATION PROGRAMS Application programs are special purpose programs designed to solve specific problems in

APPLICATION PROGRAMS Application programs are special purpose programs designed to solve specific problems in a restricted domain of interest. Word processing and editing Compilers and Translators Image processing, multi-media, graphics Mathematical, scientific, engineering Expert rule-based systems Communications Designing an application involves selecting an appropriate choice of programming languages. The choice may affect the ease of design, performance or ongoing maintenance of program codes.

EDITORS AND COMPILERS General word processing programs are used to markup text (and possibly

EDITORS AND COMPILERS General word processing programs are used to markup text (and possibly graphics and multimedia content). Files created using WP’s are not suitable for transformation into executable programs. Editors are simple tools used for text entry and editing, but they create files that contain no markup content. Unix: nedit, xedit, vi Windows: textedit (NOT Notepad)

EDITORS AND COMPILERS Compilers are special application programs that accept inputs of program text

EDITORS AND COMPILERS Compilers are special application programs that accept inputs of program text (source) codes translate the codes into machine-dependent strings of bit encodings (0’s and 1’s) analyze code syntax and semantics, detect and report errors organize the bit encodings to support process execution in RAM and CPU produce object (or executable) files that can be stored and used repeatedly (without re-compiling). REMEMBER: Files created using WP’s are not suitable for transformation into executable programs.

EDITORS AND COMPILERS Compilers are intended to perform translation of source codes to executable

EDITORS AND COMPILERS Compilers are intended to perform translation of source codes to executable codes once Although compilation is done anew each time errors are fixed (debugged) or programs are moved (ported) to a new computer. Translators (sometime called emulators) are similar to compilers, but they feature the ability to consider a single instruction (and data) and perform execution. Usually very slow compared to compiled programs Programs must always be re-translated each time they are executed.

PROGRAMS A program is a set of ordered, logical statements that, once initiated, process

PROGRAMS A program is a set of ordered, logical statements that, once initiated, process data to produce a final result, then terminate. Programming languages impose rigorous constraints on syntax and punctuation. Programmers must follow the rules defined by the language designers! Programs are the technical embodiment of logic. Logic is ultimately mathematics, but most of us can do it (and we do it all the time as part of our own survival!). Some problems seem to deny the use of logic and are considered to be non-computable. How much do you love your mother?

PROGRAMS Programs are categorized into High-level : : Abstract, suitable for human logic Low-level

PROGRAMS Programs are categorized into High-level : : Abstract, suitable for human logic Low-level : : Concrete, suitable for direct control over devices Programs typically contain definitions of variables using symbolic names and attribute types. Containers for data (where bits must be stored) Programs typically are written hierarchically Using computational units such as functions (or objects or documents). Often these units are provided in programming libraries

PROGRAMMING PARADIGMS AND LANGUAGES Many different programming languages have been developed (including only a

PROGRAMMING PARADIGMS AND LANGUAGES Many different programming languages have been developed (including only a few): C is. Pascal an example Modula of a strongly typed, C procedural language. PL/I COBOL programming Ada SQL LISP Miranda Simula Prolog It is. C++ sometimes also called a systems Java Small. Talk programming language. These languages are often grouped into conceptual paradigms (ways of thinking and planning): Procedural Logic Functional Object Oriented Declarative. . . and others Learning new languages and paradigms greatly improves one’s ability to solve problems.

THE INTERNET AND WORLD WIDE WEB The Internet has grown from early research work

THE INTERNET AND WORLD WIDE WEB The Internet has grown from early research work on networks and communications (ARPAnet) to a sophisticated network of high-throughput devices that supports massive amounts of data to be transferred on a global scale. Often called a “network of networks” Many kinds - LAN, WAN, VPN Technologies - Ethernet, optical, wireless, satellite Core hardware - SONET, bus, routers, switches, NICs Communication protocols - IP, TCP, UDP, ICMP, BGP This subject is discussed in considerable detail in a future course in Computer Networks (60 -367).

THE INTERNET AND WORLD WIDE WEB The World Wide Web is a software infrastructure

THE INTERNET AND WORLD WIDE WEB The World Wide Web is a software infrastructure that permits increasingly effective modes of accessing and sharing data (and information) on a massive scale. Standard web browsers (eg. IE, Mozilla) are enabling technologies that support WWW interactions for users Current research efforts are directed at semantic webs that support rich, user-perspective oriented data mining. An emergent software technology called SOA (Service Oriented Architecture) is forming the basis for a potential new industry in (stateful) Web Services.

STRUCTURED PROBLEM SOLVING Lecture 1 B

STRUCTURED PROBLEM SOLVING Lecture 1 B

STRUCTURED PROBLEM SOLVING The challenge of complex systems Pseudo-code Flowcharts Modularization Top-Down versus Bottom-Up

STRUCTURED PROBLEM SOLVING The challenge of complex systems Pseudo-code Flowcharts Modularization Top-Down versus Bottom-Up design principles Concepts of function, control structures and computability. Testing and Validation Software engineering

Units of Scale for Computing THE CHALLENGE OF COMPLEX Time: SYSTEMS 1 Second 10

Units of Scale for Computing THE CHALLENGE OF COMPLEX Time: SYSTEMS 1 Second 10 -3 milli second EMERGING -6 TRENDS: Many are suitable for computation, but 10 problems micro second Micro-miniaturization of circuitlogical elements continues. Research in 10 -9 nano second determining detailed, solutions to all aspects -12 biological, 10 photonic, pico quantum second and molecular computing of the problems demands careful paradigms have produced promising resultsplanning and futurein design. Storage *: pervasive possibilities. Wecapacity talk about and ubiquitous Some issues that arise in complex systemscomputing 1 sets. Byte (=8 bits) and networks as computational and we view of computers Memory requirements 10 2 Kilo power byte (1024) grids, much like the grid we rely on for electricity, with 220 Mega byte (about 106) Number of instructions executed in CPU(s) massively 30 distributed workload and 9 access to huge informational 2 Giga byte (about 10 ) Distribution of codes and data on multiple platforms resources. 240 Tera byte (about 1012) Storage 250 requirements Peta byte (about 1015) • Incredibly small – nanoscale architectures Data communication within and between computers • Incredibly* Also fast – switching times and smaller used with frequency (clock speed)distances measured in (latency) of Hertz (oscillations, or “ticks”, per second) • Incredibly units parallel – multiple processing elements working Fault detection, tolerance and recovery simultaneously Hence, Gigahertz CPU’s carrying are basedvast on clocks that of tick • Incredibly distributed – networks amounts information about a billion times a second.

ALGORITHM: THE CHALLENGE OF COMPLEX A finite, ordered set of statements with a beginning

ALGORITHM: THE CHALLENGE OF COMPLEX A finite, ordered set of statements with a beginning and an ending, intended to carry out a set of logical SYSTEMS operations to solve a problem. The strategy of a solution is a matter of logic – not programming language! Programming languages do affect matters such as efficiency of execution, maintenance of codes, portability of codes and even ease of implementation Designers of algorithms need additional tools and formalisms besides programming languages alone Language independent approaches to logic Mathematical formalism Pseudo-language for logic representation Graphical tools for logic representation and workflow

STRUCTURED PROBLEM SOLVING BEGINNINGS Now, as nice and easy as it is to sit

STRUCTURED PROBLEM SOLVING BEGINNINGS Now, as nice and easy as it is to sit back and read about the fantastic things that others have done, it is time for a reality check Would you like to participate directly in the Information Age and the Knowledge Revolution? Are you motivated to learn the basics before you try to conquer the universe with re-invented tools? Are you ready to accept discipline and excellent work and study habits as strong requirements for success? It’s time to take a step back and begin anew!

MATHEMATICAL LOGIC AND FORMALISM The mathematics of computational logic is rooted in Boolean Set

MATHEMATICAL LOGIC AND FORMALISM The mathematics of computational logic is rooted in Boolean Set Theory (George Boole). The concepts of bits (binary digits) and binary logic (calculus) based on set theoretic operations (complement/not, and, or, nand, nor, xnor) This is the fundamental connection point between computer science and computer engineering since BST applies directly to design of digital circuits Further work added an interpretive aspect to Boole’s work and led to various kinds of calculus systems (predicate, lambda and pi) Suitable for specifying formal logic operations on data objects with logical attributes

MATHEMATICAL LOGIC AND FORMALISM Pure Mathematics offers methods formally proving theorems, based on axioms

MATHEMATICAL LOGIC AND FORMALISM Pure Mathematics offers methods formally proving theorems, based on axioms (starting assumptions) and consistent argumentation Deductive and Inductive logic Applied Mathematics offers methods for analysis of static and dynamic systems for which a mathematical basis exists (eg. Physics, Chemistry, Biology, Finance, Games, etc. ) Algebra, Trigonometry, Calculus Vectors, Matrices, Linear algebra Statistics offers methods for analysis of discrete systems with large numbers of interacting elements, whose behaviours can only be estimated Regression analysis Queueing theory

MATHEMATICAL LOGIC AND FORMALISM From time to time we will refer to mathematics in

MATHEMATICAL LOGIC AND FORMALISM From time to time we will refer to mathematics in a formal way In general, we will take a less formal approach based on technical approaches that have proven effectiveness, but are based on trained reasoning principles This may sound a bit “fuzzy”, but it is based on the observations … In mathematics, the student learns to prove theorems by proving theorems (often incorrectly, at first) In programming and algorithm design, the student learns to achieve results/programs by achieving results/programs (often incorrectly, at first).

TWO SIMPLE PROBLEMS – WITH VARIATIONS Find the sum of the ages (in years)

TWO SIMPLE PROBLEMS – WITH VARIATIONS Find the sum of the ages (in years) of 3 friends, as well as their average age. Each friend tells his/her age when you ask them. Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the very first friend will know the actual value of N. (version 1) Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2)

PSEUDO-CODE First we will develop and express a solution to each problem based on

PSEUDO-CODE First we will develop and express a solution to each problem based on our own experience and in a somewhat structured language. This language is called pseudo-code (‘syu-do’ from Greek).

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well as their average age. Each friend tells his/her age when you ask them. Solution – in human terms: Select clear paper and pencil to record ages and do arithmetic Ask first friend’s age and write it on paper Ask second friend’s age and add it to total age on paper Ask third friend’s age and add it to total age on paper Divide total age on paper by 3 to find average Tell everyone the total age and the average

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well as their average age. Each friend tells his/her age when you ask them. Solution – in human terms: Select clear paper and pencil to record ages and do arithmetic Ask first friend’s age and write it on paper Ask second friend’s age and add it to total age on paper Ask third friend’s age and add it to total age on paper Divide total age on paper by 3 to find average Tell everyone the total age and the average

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well as their average age. Each friend tells his/her age when you ask them. Solution – in more structured terms: Identify variables: Age, Total. Age and Average. Age Initialize: Total. Age to 0. Ask first friend’s age and write it on paper Ask second friend’s age and add it to total age on paper Ask third friend’s age and add it to total age on paper Divide total age on paper by 3 to find average Tell everyone the total age and the average

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well as their average age. Each friend tells his/her age when you ask them. Solution – in more structured terms: Identify variables: Age, Total. Age and Average. Age Initialize: Total. Age to 0. Ask friend’s Age and add it to Total. Age Divide total age on paper by 3 to find average Tell everyone the total age and the average

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well as their average age. Each friend tells his/her age when you ask them. Solution – in more structured terms: Identify variables: Age, Total. Age and Average. Age Initialize: Total. Age to 0. Repeat 3 times Ask Age and add it to Total. Age Divide Total. Age by 3 to find Average. Age Report the Total. Age and the Average. Age

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well

PSEUDO-CODE Find the sum of the ages (in years) of 3 friends, as well as their average age. Each friend tells his/her age when you ask them. Solution – in more structured terms: Identify variables: Age, Total. Age and Average. Age Initialize: Total. Age to 0. Repeat 3 times Ask Age and add it to Total. Age Divide Total. Age by 3 to find Average. Age Report the Total. Age and the Average. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the very first friend will know the actual value of N. (version 1) Build on previous solution: Identify variables: Age, Total. Age , Average. Age Initialize: Total. Age to 0. Repeat 3 times Ask Age and add it to Total. Age Divide Total. Age by 3 to find Average. Age Report the Total. Age and the Average. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the very first friend will know the actual value of N. (version 1) Build on previous solution: Identify variables: Age, Total. Age , Average. Age, Num, Count Initialize: Total. Age to 0. Repeat 3 times Ask Age and add it to Total. Age Divide Total. Age by 3 to find Average. Age Report the Total. Age and the Average. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the very first friend will know the actual value of N. (version 1) Build on previous solution: Identify variables: Age, Total. Age , Average. Age, Num, Count Initialize: Total. Age to 0, Count to 0. Repeat 3 times Ask Age and add it to Total. Age Divide Total. Age by 3 to find Average. Age Report the Total. Age and the Average. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the very first friend will know the actual value of N. (version 1) Build on previous solution: Identify variables: Age, Total. Age , Average. Age, Num, Count Initialize: Total. Age to 0, Count to 0. Ask Num Repeat 3 times Ask Age and add it to Total. Age Divide Total. Age by 3 to find Average. Age Report the Total. Age and the Average. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the very first friend will know the actual value of N. (version 1) Build on previous solution: Identify variables: Age, Total. Age , Average. Age, Num, Count Initialize: Total. Age to 0, Count to 0. Ask Num Repeat until Count is equal to Num Ask Age and add it to Total. Age Add 1 to Count Divide Total. Age by 3 to find Average. Age Report the Total. Age and the Average. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the very first friend will know the actual value of N. (version 1) Build on previous solution: Identify variables: Age, Total. Age , Average. Age, Num, Count Initialize: Total. Age to 0, Count to 0. Ask Num Repeat until Count is equal to Num Ask Age and add it to Total. Age Add 1 to Count Divide Total. Age by Num to find Average. Age Report the Total. Age and the Average. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2)

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Build on previous solution: Identify variables: Age, Tot. Age , Ave. Age, Num, Count Initialize: Tot. Age to 0, Count to 0. Ask Num Repeat until Count is equal to Num Ask Age and add it to Tot. Age Add 1 to Count Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Build on previous solution: Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot. Age , Ave. Age, Num Initialize: Tot. Age to 0, Count to 0. Ask Num Repeat until Count is equal to Num Ask Age and add it to Tot. Age Add 1 to Count Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Build on previous solution: Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot. Age , Ave. Age, Num Initialize: Tot. Age to 0, Count to 0. Ask Num Repeat until Count is equal to Num Ask Age and add it to Tot. Age Add 1 to Count Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Build on previous solution: Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot. Age , Ave. Age, Num Initialize: Tot. Age to 0, Num to 0. Ask Num Repeat until Count is equal to Num Ask Age and add it to Tot. Age Add 1 to Count Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Build on previous solution: Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot. Age , Ave. Age, Num Initialize: Tot. Age to 0, Num to 0. Ask Age Repeat until Count is equal to Num Ask Age and add it to Tot. Age Add 1 to Count Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Build on previous solution: Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot. Age , Ave. Age, Num Initialize: Tot. Age to 0, Num to 0. Ask Age Do while Age is greater or equal to 0 Add Age to Tot. Age Add 1 to Num Ask Age Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

FLOWCHARTS Display Decision Connecting lines Process User input connector Off-page connector Terminal

FLOWCHARTS Display Decision Connecting lines Process User input connector Off-page connector Terminal

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends.

PSEUDO-CODE Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Solution: Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot. Age , Ave. Age, Num Initialize: Tot. Age to 0, Num to 0. Ask Age Do while Age is greater or equal to 0 Add Age to Tot. Age Add 1 to Num Ask Age Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

Start PSEUDO-CODE Tot. Age = 0 Num = 0 Find the sum and average

Start PSEUDO-CODE Tot. Age = 0 Num = 0 Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Solution: Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot. Age , Ave. Age, Num Initialize: Tot. Age to 0, Num to 0. Ask Age Do while Age is greater or equal to 0 Add Age to Tot. Age Add 1 to Num Ask Age Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

Start PSEUDO-CODE Tot. Age = 0 Num = 0 Find the sum and average

Start PSEUDO-CODE Tot. Age = 0 Num = 0 Find the sum and average of the ages (in years) of N friends. Each friend will Age tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Solution: Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot. Age , Ave. Age, Num Initialize: Tot. Age to 0, Num to 0. Ask Age Do while Age is greater or equal to 0 Add Age to Tot. Age Add 1 to Num Ask Age Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

Start PSEUDO-CODE Tot. Age = 0 Num = 0 Find the sum and average

Start PSEUDO-CODE Tot. Age = 0 Num = 0 Find the sum and average of the ages (in years) of N friends. Each friend will Age tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) F Solution: Age >= Assumptions: A last person exists who inputs Age as <0 0 Identify variables: Age, Tot. Age , Ave. Age, Num T Initialize: Tot. Age to 0, Num to 0. Tot. Age = Tot. Age + Age Ask Age Num = Num + 1 Do while Age is greater or equal to 0 Add Age to Tot. Age Add 1 to Num Ask Age Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

Start PSEUDO-CODE Tot. Age = 0 Num = 0 Find the sum and average

Start PSEUDO-CODE Tot. Age = 0 Num = 0 Find the sum and average of the ages (in years) of N friends. Each friend will Age tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) F Solution: Age >= Assumptions: A last person exists who inputs Age as <0 0 Identify variables: Age, Tot. Age , Ave. Age, Num T Initialize: Tot. Age to 0, Num to 0. Tot. Age = Tot. Age + Age Ask Age Num = Num + 1 Do while Age is greater or equal to 0 Add Age to Tot. Age Add 1 to Num Ask Age Divide Tot. Age by Num to find Ave. Age = Tot. Age / Num Report the Tot. Age and the Ave. Age Tot. Age, Ave. Age

Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot.

Assumptions: A last person exists who inputs Age as <0 Identify variables: Age, Tot. Age , Ave. Age, Num PSEUDO-CODE Start Tot. Age = 0 Num = 0 Find the sum and average of the ages (in years) of N friends. Each friend will Age tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) F Solution: Age >= Assumptions: A last person exists who inputs Age as <0 0 Identify variables: Age, Tot. Age , Ave. Age, Num T Initialize: Tot. Age to 0, Num to 0. Tot. Age = Tot. Age + Age Ask Age Num = Num + 1 Do while Age is greater or equal to 0 Add Age to Tot. Age Add 1 to Num Ask Age Divide Tot. Age by Num to find Ave. Age = Tot. Age / Num Report the Tot. Age and the Ave. Age Tot. Age, Ave. Age COMPLETE ? ! Stop

MODULARIZATION Initialize: Tot. Age to 0, Num to 0. Simple problems can often Ask

MODULARIZATION Initialize: Tot. Age to 0, Num to 0. Simple problems can often Ask be Agesolved entirely Do – while is greater or equal to 0 through a “flash of insight” one. Age sees the entire Add Age to Tot. Age solution immediately Add 1 to Num Most complex problems are. Ask not. Age easily solvable and require solutions of many smaller problems (sub. Divide Tot. Agetogether by Num toto find Ave. Age problems) which must be “stitched” form Report the Tot. Age and the Ave. Age a whole Each sub-problem solution represents a module that is part of the entire solution. We refer to the act of breaking large problems into smaller subproblems as modularization.

TOP-DOWN VERSUS BOTTOM-UP DESIGN PRINCIPLES Breaking apart a large problem into smaller problems is

TOP-DOWN VERSUS BOTTOM-UP DESIGN PRINCIPLES Breaking apart a large problem into smaller problems is called Top-Down design Top refers to a high level of abstraction Down refers to increasing levels of concreteness, or detail Once a problem module has been identified, it is usually the case that the programmer senses that they understand the problem well enough to have that “flash of insight”. Providing the details of the solution is called Bottom-Up design Bottom refers to fundamental details of the solution Up refers to adding the additional details to produce the full solution, which is then a higher level of abstraction

CONCEPTS OF FUNCTION, CONTROL STRUCTURES AND COMPUTABILITY Functions (as well as procedures in some

CONCEPTS OF FUNCTION, CONTROL STRUCTURES AND COMPUTABILITY Functions (as well as procedures in some languages) are the formal embodiments of modularized logic. Typically, functions perform one kind of action (solve one type of problem Functions are of particular importance in C Control structures are formal grammatical techniques used to identify structural components of a complete algorithm (module or program) Decision Repetition Logic blocks

CONCEPTS OF FUNCTION, CONTROL STRUCTURES AND COMPUTABILITY Computability refers to the capability to perform

CONCEPTS OF FUNCTION, CONTROL STRUCTURES AND COMPUTABILITY Computability refers to the capability to perform digital computation that achieves a result for a problem. Emotional (non-rational, illogical ? ? ) problems are generally considered non-computable (although even this statement is controversial to some researchers) Some problems require immense resources and time to perform a complete calculation and are considered infeasible, or intractable Calculating the N’th digit of pi for huge N (pi is irrational) Calculating an accurate weather forecast over the next 100 years for every city on earth We will stick to simple problems, but there are still dangers to avoid (eg. the infinite loop).

TESTING AND VALIDATION Software is only as good as the degree to which it

TESTING AND VALIDATION Software is only as good as the degree to which it has been tested There’s always one more case you forgot to test for! Validation refers to the completeness with which software specifications and requirements have been satisfied Writing programs is only one step in a process. Before one can state that a program is ready for distribution (ie. sale or assessment), it is absolutely necessary to test it thoroughly Testing is most often performed by treating many special data sets designed to test the logic Formal methods of testing are also used.

SOFTWARE ENGINEERING Software engineering is the modern study of software design. Sometimes called software

SOFTWARE ENGINEERING Software engineering is the modern study of software design. Sometimes called software development Like traditional engineering disciplines, SE is focused on developing formal methods for analysis of problems, algorithmic and data design strategies, proof techniques, emphasis on reliability, quality and assurance. This is an exciting area of current research, but its impact is being felt increasingly in industry where better, more reliable, software results.

C LANGUAGE PROGRAMMING BASICS Lecture 1 C

C LANGUAGE PROGRAMMING BASICS Lecture 1 C

C LANGUAGE PROGRAMMING - BASICS From humble beginnings …. .

C LANGUAGE PROGRAMMING - BASICS From humble beginnings …. .

C LANGUAGE PROGRAMMING - BASICS Introduction to the C language Basic program examples from

C LANGUAGE PROGRAMMING - BASICS Introduction to the C language Basic program examples from coding with an editor to compilation and execution, debugging techniques. Logic and Algorithms in problem solving. Memory and CPU concepts. Syntax, grammar and punctuation.

INTRODUCTION TO THE C LANGUAGE C is a strongly typed, procedural language It is

INTRODUCTION TO THE C LANGUAGE C is a strongly typed, procedural language It is formally defined by about 20+ pre-defined keywords, a set of operator symbols, pre-processor directives and a grammar that defines the rules of constructing C programs C is supported by a range of pre-defined libraries of special purpose functions that can be referenced and used in programs C is a suitable high-level language that supports programming at an abstract level and at a detailed level of machine control (systems programming) C is the parent of the C++ language, sometimes called a “better version of C”

INTRODUCTION TO THE C LANGUAGE Rather than start out formally and rigorously, let’s jump

INTRODUCTION TO THE C LANGUAGE Rather than start out formally and rigorously, let’s jump right in and see what some C programs look like. Along the way we’ll also re-visit the problems we considered earlier. With each program we will note a number of concepts that will require further explanation later. NOTE: You will gain technical experience and skill in the course Laboratory, using editors, email programs, compilers and other tools.

BASIC PROGRAM EXAMPLES “Hello World” Using a Unix editor, type in the codes given

BASIC PROGRAM EXAMPLES “Hello World” Using a Unix editor, type in the codes given and save as the file: myprog 01. c /* A simple first program in C */ #include <stdio. h> int main ( ) { printf( “Hello world, I’m here!” ) ; return 0 ; }

BASIC PROGRAM EXAMPLES Comments (documentation) are expressed as text, sandwiched between the delimiter symbol

BASIC PROGRAM EXAMPLES Comments (documentation) are expressed as text, sandwiched between the delimiter symbol (combinations) “/*” and “*/”. Comments are for humans and not for the machine (or compiler) /* A simple first program in C */ #include <stdio. h> int main ( ) { printf( “Hello world, I’m here!” ) ; return 0 ; }

BASIC This PROGRAM EXAMPLES means include pre-defined library files (stdio. h) that permit use

BASIC This PROGRAM EXAMPLES means include pre-defined library files (stdio. h) that permit use of the standard input and output functions The C pre-processor refers to a preliminary step in (actually, header files). Note the use of angle brackets (< compilation. entire program code is searched for special and >)The to enclose the file references symbol definitions and external files – these Thistostep permits the C compiler to properly translate references are denoted by the symbol # such (pound sign). references to pre-defined functions, as printf(), which would non-recognizable (ie. logic undefined) Note that these arebenot proper C program statements and do otherwise. not have punctuation. /* A simple first program in C */ #include <stdio. h> int main ( ) { printf( “Hello world, I’m here!” ) ; return 0 ; }

BASIC PROGRAM EXAMPLES The main function is a necessary part of every C program.

BASIC PROGRAM EXAMPLES The main function is a necessary part of every C program. As shown, main is defined as a function that returns an integer (int) value. Functions in C always have a data type, a symbolic name and parentheses ( ) that often enclose a list of items called parameters The body of the function containing coded statements is enclosed between braces { and }. /* A simple first program in C */ #include <stdio. h> int main ( ) { printf( “Hello world, I’m here!” ) ; return 0 ; } C language programs always begin execution at the first executable statement in main.

BASIC PROGRAM EXAMPLES The C pre-processor refers to a preliminary step in compilation. The

BASIC PROGRAM EXAMPLES The C pre-processor refers to a preliminary step in compilation. The entire program code is searched for special references to symbol definitions and external files – these references are denoted by the symbol # (pound sign). Note that these are not proper C program logic statements and do not have punctuation. /* A simple first program in C */ #include <stdio. h> int main ( ) { printf( “Hello world, I’m here!” ) ; return 0 ; }

BASIC PROGRAM EXAMPLES The return 0 statement should be included at the end of

BASIC PROGRAM EXAMPLES The return 0 statement should be included at the end of main to provide a distinct point of logic where the program is known to terminate The value 0 is a signal to the O/S that “everything is OK” return’s can be placed anywhere in a program /* A simple first program in C */ #include <stdio. h> int main ( ) { printf( “Hello world, I’m here!” ) ; return 0 ; }

BASIC PROGRAM EXAMPLES Once the program has been created it is time to compile

BASIC PROGRAM EXAMPLES Once the program has been created it is time to compile it At the command line prompt, type the following (don’t forget to press the Enter key): % cc % myprog 01. c If there are no errors or warnings of any kind, the command prompt will simply appear. Look at your files (use: % ls) and check that a file called a. out has been created. This file was created by the compiler. It is the executable translation of your program.

BASIC PROGRAM EXAMPLES Now you are ready to execute your program. Type a. out

BASIC PROGRAM EXAMPLES Now you are ready to execute your program. Type a. out at the command prompt and watch what happens: % cc myprog 01. c % a. out Hello world, I’m here!% Note: the command prompt % shows up directly after the output from the program’s printf() statement. It is not a logical error (or bug), but it is not suitable. Let’s fix this.

BASIC PROGRAM EXAMPLES Re-enter the editor and open the myprog 01. c file. Edit

BASIC PROGRAM EXAMPLES Re-enter the editor and open the myprog 01. c file. Edit the line with the printf function /* A simple first program in C */ #include <stdio. h> int main ( ) { printf( “Hello world, I’m here!” ) ; return 0 ; }

BASIC PROGRAM EXAMPLES Re-enter the editor and open the myprog 01. c file. Edit

BASIC PROGRAM EXAMPLES Re-enter the editor and open the myprog 01. c file. Edit the line with the printf function Add the n (newline) character sequence (backslash plus letter n) This tells the output routines to move the cursor to the beginning (left) of the next line following the output. /* A simple first program in C */ #include <stdio. h> int main ( ) { printf( “Hello world, I’m here!n” ) ; return 0 ; }

BASIC PROGRAM EXAMPLES Now, re-compile and re-run the program. % cc myprog 01. c

BASIC PROGRAM EXAMPLES Now, re-compile and re-run the program. % cc myprog 01. c % a. out Hello world, I’m here! % Ah. . . Success! At this point, don’t forget to take just a moment to feel good about your accomplishment ! OK, that’s enough - now let’s get busy.

BASIC PROGRAM EXAMPLES Find the sum of the ages (in years) of 3 friends,

BASIC PROGRAM EXAMPLES Find the sum of the ages (in years) of 3 friends, as well as their average age. Each friend tells his/her age when you ask them. Solution: Identify variables: Age, Tot. Age and Ave. Age Initialize: Tot. Age to 0. Input: Age, add it to Tot. Age Divide Tot. Age by 3 to find Ave. Age Output: Tot. Age, Ave. Age

/* Three friend’s age problem */ #include <stdio. h> int main ( ) {

/* Three friend’s age problem */ #include <stdio. h> int main ( ) { int Age, Tot. Age ; float Ave. Age ; BASIC PROGRAM EXAMPLES Identify variables: Age, Tot. Age and Ave. Age Using an editor, we translate the pseudo-code into valid C Tot. Age = 0 ; Initialize: Tot. Age tocodes. 0. language printf( “Enter your age: “ ) ; scanf( “%d”, &Age ) ; Tot. Age = Tot. Age + Age ; Input: Age, add it to Tot. Age Divide Tot. Age by 3 to find Ave. Age = Tot. Age / 3. 0 ; printf( “Total age = %dn”, Tot. Age ) ; printf( “Average = %fn”, Ave. Age ) ; return 0 ; Output: Tot. Age, Ave. Age }

BASIC PROGRAM EXAMPLES After compiling to create a. out, we test the program by

BASIC PROGRAM EXAMPLES After compiling to create a. out, we test the program by entering values 1, 2 and 3 (don’t forget to press the Enter key after each number) The interaction and outputs are shown as: % a. out 1 2 3 Total age = 6 Average = 2 % Now, let us study our program code more closely …

/* Three friend’s age problem */ #include <stdio. h> int main ( ) {

/* Three friend’s age problem */ #include <stdio. h> int main ( ) { int Age, Tot. Age ; float Ave. Age ; BASIC PROGRAM EXAMPLES Tot. Age = 0 ; Variable definitions: printf( “Enter your age: “ ) ; • Variables must be declared (ie. defined) scanf( “%d”, &Age ) ; by the = Tot. Agesymbolic + Age ; name data type and. Tot. Age the user-defined printf( “Enter your age: “ ) ; (sometimes called varname). “%d”, &Age ; be • Declarationsscanf( are statements that )must = Tot. Age + Age ; terminated by. Tot. Age a semi-colon. printf( “Enter your age: “ ) ; • Several variables may be declared in the same scanf( “%d”, &Age ) ; statement – they form =a Tot. Age list of items. Tot. Age + Age ; Ave. Age = Tot. Age / 3. 0 ; printf( “Total age = %dn”, Tot. Age ) ; printf( “Average = %fn”, Ave. Age ) ; return 0 ; }

/* Three friend’s age problem */ #include <stdio. h> int main ( ) {

/* Three friend’s age problem */ #include <stdio. h> int main ( ) { int Age, Tot. Age ; float Ave. Age ; BASIC PROGRAM EXAMPLES Tot. Age = 0 ; Variable definitions: printf( “Enter your age: “ ) ; • Variables must be declared (ie. defined) scanf( “%d”, &Age ) ; by the = Tot. Agesymbolic + Age ; name data type and. Tot. Age the user-defined printf( “Enter your age: “ ) ; (sometimes called varname). “%d”, &Age ; be • Declarationsscanf( are statements that )must = Tot. Age + Age ; terminated by. Tot. Age a semi-colon. printf( “Enter your age: “ ) ; • Several variables may be declared in the same scanf( “%d”, &Age ) ; statement – they form =a Tot. Age list of items. Tot. Age + Age ; Ave. Age = Tot. Age / 3. 0 ; printf( “Total age = %dn”, Tot. Age ) ; printf( “Average = %fn”, Ave. Age ) ; return 0 ; }

Assignment Operator: /* Three friend’s age problem */ • The value of an expression

Assignment Operator: /* Three friend’s age problem */ • The value of an expression be assigned to a #include can <stdio. h> variable using the =int operator. main EXAMPLES ( ) { BASIC PROGRAM Age, Tot. Age • The value is stored at int the memory location; float indicated by the variable name. Ave. Age ; Tot. Age = 0 ; printf( “Enter your age: “ ) ; scanf( “%d”, &Age ) ; Tot. Age = Tot. Age + Age ; Ave. Age = Tot. Age / 3. 0 ; printf( “Total age = %dn”, Tot. Age ) ; printf( “Average = %fn”, Ave. Age ) ; return 0 ; }

/* Three friend’s <stdio. h> age problem */ Standard Input/Output Functions: <stdio. h> •

/* Three friend’s <stdio. h> age problem */ Standard Input/Output Functions: <stdio. h> • Output (to VDU)#include is performed using the printf() int main EXAMPLES ( ) { BASIC function. PROGRAM Age, Tot. Age ; scanf() • Input (from KBD) isint performed using the float Ave. Age ; function. Tot. Age = 0 ; printf( “Enter your age: “ ) ; scanf( “%d”, &Age ) ; Tot. Age = Tot. Age + Age ; Ave. Age = Tot. Age / 3. 0 ; printf( “Total age = %dn”, Tot. Age ) ; printf( “Average = %fn”, Ave. Age ) ; return 0 ; }

BASIC PROGRAM EXAMPLES Find the sum and average of the ages (in years) of

BASIC PROGRAM EXAMPLES Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the very first friend will know the actual value of N. (version 1) Solution: Identify vars: Age, Tot. Age , Ave. Age, Num, Count Initialize: Tot. Age to 0, Count to 0. Ask Num Repeat until Count is equal to Num Ask Age and add it to Tot. Age Add 1 to Count Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

/* The N friends age problem – ver 1 */ #include <stdio. h> int

/* The N friends age problem – ver 1 */ #include <stdio. h> int main ( ) { int Num, K, Age, Tot. Age ; float Ave. Age ; Find the sum and average of the ages (in years) of N friends. Each friend will. Tot. Age tell their = age asked, but the very first friend will know 0 when ; the actualprintf( value of N. (version “Tell me 1)number of friendsn” ) ; scanf( “%d”, &Num ) ; K = 0 ; Solution: while( K < Num ) { Identify vars: Age, Tot. Age , Ave. Age, Num, Count printf( “Enter your age: n“ ) ; Initialize: scanf( Tot. Age to“%d”, 0, Count to 0. ) ; &Age Ask Num Tot. Age = Tot. Age + Age ; K =Count K + is 1 equal ; Repeat until to Num } Ask Age and add it to Tot. Age Ave. Age = (float) Tot. Age / Num ; Add 1 to Count printf( “Total age = %dn”, Tot. Age ) ; Divide Tot. Age by“Average Num to findage Ave. Age printf( = %fn”, Ave. Age ) ; return 0 ; and the Ave. Age Report the Tot. Age } BASIC PROGRAM EXAMPLES

/* The N friends age problem – ver 1 */ #include <stdio. h> int

/* The N friends age problem – ver 1 */ #include <stdio. h> int main ( ) { int Num, K, Age, Tot. Age ; float Ave. Age ; Find the sum and average of the ages (in years) of N friends. Each friend will. Tot. Age tell their = age asked, but the very first friend will know 0 when ; the actualprintf( value of N. (version “Tell me 1)number of friendsn” ) ; scanf( “%d”, &Num ) ; K = 0 ; Solution: while( K < Num ) { Identify vars: Age, Tot. Age , Ave. Age, Num, Count printf( “Enter your age: n“ ) ; Initialize: scanf( Tot. Age to“%d”, 0, Count to 0. ) ; &Age Ask Num Tot. Age = Tot. Age + Age ; K =Count K + is 1 equal ; Repeat until to Num } Ask Age and add it to Tot. Age Ave. Age = (float) Tot. Age / Num ; Add 1 to Count printf( “Total age = %dn”, Tot. Age ) ; Divide Tot. Age by“Average Num to findage Ave. Age printf( = %fn”, Ave. Age ) ; return 0 ; and the Ave. Age Report the Tot. Age } BASIC PROGRAM EXAMPLES

Repetition Logic : While <cond_true> Statement /* Theof. Nlogic, friends age problem 1 */

Repetition Logic : While <cond_true> Statement /* Theof. Nlogic, friends age problem 1 */ Repetition or simply may)–bever accomplished using the Relational Operator Logic. Looping, : ( K < Num #include <stdio. h> while control structure. Relational operators are used to “compare” values. The Boolean int main ( ) { expressions formed always evaluate either to true (1) or false (0). int Num, K, the Age, Tot. Age ; variable (K) to count-up from In. The thissix example, note use of a counter operators include: float Ave. Age 0 toless Num-1 the ; Age of the Ngreater friends. than > thanto obtain < Find the sum and average of the ages (in years) of N friends. Each less than or equal to <= greater than or equal to >= friend will. Tot. Age tell their = age when asked, but the very first friend will know 0 ; Alsoequal note to that == it is necessary to use a not counter, the value of Num equalsince to != the actualprintf( value of N. (version 1) me number of later. friendsn” ) ; must be stored for“Tell calculating the Ave. Age scanf( “%d”, &Num ) ; K = 0 ; Solution: while( K < Num ) { Identify vars: Age, Tot. Age , Ave. Age, Num, Count printf( “Enter your age: n“ ) ; Initialize: scanf( Tot. Age to“%d”, 0, Count to 0. ) ; &Age Ask Num Tot. Age = Tot. Age + Age ; K =Count K + is 1 equal ; Repeat until to Num } Ask Age and add it to Tot. Age Ave. Age = (float) Tot. Age / Num ; Statement syntax: Add 1 to Count printf( “Total age = %dn”, Tot. Age ) ; Control structures, such as while(), and Ave. Age later if() and others, imply possible Divideprintf( Tot. Age by“Average Num to find age = %fn”, Ave. Age ) ; execution of a Statement. return 0 ; and the Ave. Age Report the Tot. Age A simple statement is a complete C language set of operations (or function call) } terminated by a semi-colon ; . A compound statement, or statement structure, is an ordered list of simple statements, all enclosed between braces { and }. BASIC PROGRAM EXAMPLES

/* The N friends Type Casting: (float) age problem – ver 1 */ #include

/* The N friends Type Casting: (float) age problem – ver 1 */ #include Placing a cast<stdio. h> operator in front of an expression converts the data intof main ( ) { value to the specified cast data type the expression int Num, K, Age, Tot. Age ; Sincefloat Tot. Age. Ave. Age and Num; are both int data types, the division will be of Find the sum and average of the ages (in years) of N friends. Each int data type. Using the cast operator (float) before Tot. Age friend will. Tot. Age tell their = age asked, but the very first friend will know 0 inwhen ; Tot. Age converts the value to a float data type and the subsequent the actualprintf( value of N. (version 1) number friendsn” division produces“Tell a resultme value that isof a float data type. ) ; scanf( “%d”, &Num ) ; K =outputs 0 ; are machine dependent. If specialized hardware Compiler Solution: while( K that < Num ) { the data type conversion, they are used. exist perform instructions Identify vars: Age, Tot. Age , Ave. Age, Num, Count printf( “Enter your age: n“ ) ; Otherwise, the process of conversion may require its own logic based Initialize: scanf( Tot. Age to“%d”, 0, Count to 0. &Age )– such ; on available hardware instructions code expansion is called = Tot. Age + Age ; instruction Ask Num Tot. Age hardware emulation. K =Count K + is 1 equal ; Repeat until to Num } Ask Age and add it to Tot. Age Ave. Age = (float) Tot. Age / Num ; Add 1 to Count printf( “Total age = %dn”, Tot. Age ) ; Divide Tot. Age by“Average Num to findage Ave. Age printf( = %fn”, Ave. Age ) ; return 0 ; and the Ave. Age Report the Tot. Age } BASIC PROGRAM EXAMPLES

/* The N friends age problem – ver 1 */ #include <stdio. h> int

/* The N friends age problem – ver 1 */ #include <stdio. h> int main ( ) {and test the program. Keep It Simple – KIS ! Now it’s time to compile int Num, K, Age, Tot. Age ; float Ave. Age ; Find the sum and average of the ages (in years) of N friends. Each % a. out friend will. Tot. Age tell their age asked, but the very first friend will know = 0 when ; the actualprintf( value 3 of N. (version “Tell me 1)number of friendsn” ) ; 1 “%d”, &Num ) ; scanf( K = 02 ; Solution: 3 K < Num ) { while( Identify vars: Age, Tot. Age , Ave. Age, Num, Count printf( age: n“ ) ; Total “Enter age = your 6 Initialize: scanf( Tot. Age to“%d”, 0, Count to Average age&Age = 0. 2) ; OK = Tot. Age + Age ; Ask Num Tot. Age % K =Count K + is 1 equal ; Repeat until to Num } Ask Age and add it to Tot. Age Ave. Age = (float) Tot. Age / Num ; Add 1 to Count printf( “Total age = %dn”, Tot. Age ) ; Divide Tot. Age by“Average Num to findage Ave. Age printf( = %fn”, Ave. Age ) ; return 0 ; and the Ave. Age Report the Tot. Age } BASIC PROGRAM EXAMPLES

/* The N friends age problem – ver 1 */ #include <stdio. h> inttest

/* The N friends age problem – ver 1 */ #include <stdio. h> inttest main ( )values, { We must various so what if we enter 0 first ? int Num, K, Age, Tot. Age ; float Ave. Age ; Find the sum and average of the ages (in years) of N friends. Each % a. out OK! will know friend will. Tot. Age tell their age asked, but the very NOT first friend = 0 when ; the actualprintf( value 0 of N. (version “Tell me 1)number of friendsn” ) ; --Gobbledegook --scanf( “%d”, &Num ) ; K = 0% ; Solution: while( K < Num ) { Identify vars: Age, Tot. Age , Ave. Age, Num, Count printf( “Enter your age: n“ ) ; Initialize: scanf( Tot. Age to“%d”, 0, Count to 0. ) ; &Age Ask Num Tot. Age = Tot. Age + Age ; K =Count K + is 1 equal ; Repeat until to Num } Ask Age and add it to Tot. Age Ave. Age = (float) Tot. Age / Num ; Add 1 to Count printf( “Total age = %dn”, Tot. Age ) ; Divide Tot. Age by“Average Num to findage Ave. Age printf( = %fn”, Ave. Age ) ; return 0 ; and the Ave. Age Report the Tot. Age } BASIC PROGRAM EXAMPLES

/* The N friends age problem – ver 1 */ #include <stdio. h> inttest

/* The N friends age problem – ver 1 */ #include <stdio. h> inttest main ( )values, { We must various so what if we enter 0 first ? int Num, K, Age, Tot. Age ; float Ave. Age ; Find the sum and average of the ages (in years) of N friends. Each % a. out OK! will know friend will. Tot. Age tell their age asked, but the very NOT first friend = 0 when ; the actualprintf( value 0 of N. (version “Tell me 1)number of friendsn” ) ; --Gobbledegook --scanf( “%d”, &Num ) ; K = 0% ; Solution: while( K < Num ) { Identify vars: Age, Tot. Age , Ave. Age, Num, Count printf( “Enter your age: n“ ) ; problem Initialize: occurs Tot. Agebecause to“%d”, 0, Count 0. ) ; by zero error that we did not The of&Age a to divide scanf( plan for. Num In general, errors are referred to as; exceptions (because the Tot. Age = Tot. Age + Age Ask computer takes to; being abused ) K exception =Count K + is 1 equal Repeat until to Num } Ask Age and add it to Tot. Age Ave. Age = (float) Tot. Age / Num ; Add 1 to Count printf( “Total age = %dn”, Tot. Age ) ; Divide Tot. Age by“Average Num to findage Ave. Age General Tip: printf( = %fn”, Ave. Age ) ; It is always areturn good idea spend time to read fully and interpret the error 0 to ; and Report the Tot. Age thethe Ave. Age messages } outputted by the O/S runtime monitoring system. Sometimes errors are easy to interpret and then to locate their origins. Other times, debugging code is very difficult. BASIC PROGRAM EXAMPLES

/* The N friends age problem – ver 1 */ #include. Refine <stdio. h>

/* The N friends age problem – ver 1 */ #include. Refine <stdio. h> the solution to account for this case. int main ( ) { int Num, K, Age, Tot. Age ; float Ave. Age ; BASIC PROGRAM EXAMPLES Find the sum and average of the ages (in years) of N friends. Each Tot. Age = 0 ; friend will tell their age when asked, but theof very first friend will)know printf( “Tell me number friendsn” ; the actual scanf( value of N. (version 1) “%d”, &Num ) ; if (Num <= 0 ) { printf( “Get a friend. n” ) ; Solution: return 0 ; Identify}vars: Age, Tot. Age , Ave. Age, Num, Count K = 0 ; to 0, Count to 0. Initialize: Tot. Age while( K < Num ) { Ask Num Decision Logic“Enter : if <cond> printf( your. Statement age: n“ ) ; Repeat until Countit is equal to Num scanf( “%d”, &Age ; perform an action, or Sometimes is necessary to )either Tot. Age =it action. Tot. Age + Age perform the These are ; mutually exclusive Asknot Age and add to Tot. Age K = Kof + 1 ; a specified condition. Addoutcomes 1 to Count } Divide Ave. Age Tot. Age by= Num to find Tot. Age Ave. Age / Num ; (float) In C we use the if control structure to form decision logic. = %dn”, Tot. Age ) ; Reportprintf( the Tot. Age“Total and the age Ave. Age printf( “Average = %fn”, Ave. Age ) ; The condition return 0 ; expression is a valid Boolean expression, } typically formed using relational operators.

BASIC PROGRAM EXAMPLES Find the sum and average of the ages (in years) of

BASIC PROGRAM EXAMPLES Find the sum and average of the ages (in years) of N friends. Each friend will tell their age when asked, but the actual value of N can only be determined by counting the friends. (version 2) Solution: Assumptions: A last person exists who inputs Age as <0 Identify vars: Age, Tot. Age , Ave. Age, Num Initialize: Tot. Age to 0, Num to 0. Ask Age Do while Age is greater or equal to 0 Add Age to Tot. Age Add 1 to Num Ask Age Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

/* The N friend’s age problem – ver 2 */ #include <stdio. h> int

/* The N friend’s age problem – ver 2 */ #include <stdio. h> int main ( ) { int Num=0, Age, Tot. Age=0 ; float Ave. Age ; Find the sum and average of the ages (in years) of N friends. Each friend printf( will tell their“Enter age when asked, but the actual your age: n” ) ; value of N can only be determined by counting scanf( “%d”, &Age ) the ; friends. (version 2) BASIC PROGRAM EXAMPLES Solution: while( Age >= 0) { Tot. Age. A =last Tot. Age + Agewho ; inputs Age as <0 Assumptions: person exists Num. Tot. Age + 1 ; , Ave. Age, Num Identify. Num vars: = Age, printf( “Enter your age: n“ ) ; Initialize: Tot. Age to 0, Num to 0. scanf( “%d”, &Age ) ; Ask } Age Do. Ave. Age while Age greater or. Tot. Age equal to /0 Num ; = is(float) printf( Add Age to“Total Tot. Age age = %dn”, Tot. Age ) ; printf( “Average = %fn”, Ave. Age ) ; Add 1 to Num return 0 ; Ask Age } Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

/* The N friend’s age problem – ver 2 */ #include <stdio. h> int

/* The N friend’s age problem – ver 2 */ #include <stdio. h> int main ( ) { int Num=0, Age, Tot. Age=0 ; float Ave. Age ; Find the sum and average of the ages (in years) of N friends. Each friend printf( will tell their“Enter age when asked, but the actual your age: n” ) ; value of N can only be determined by counting scanf( “%d”, &Age ) the ; friends. (version 2) BASIC PROGRAM EXAMPLES Solution: while( Age >= 0) { Tot. Age. A =last Tot. Age + Agewho ; inputs Age as <0 Assumptions: person exists Num. Tot. Age + 1 ; , Ave. Age, Num Identify. Num vars: = Age, printf( “Enter your age: n“ ) ; Initialize: Tot. Age to 0, Num to 0. scanf( “%d”, &Age ) ; Ask } Age Do. Ave. Age while Age greater or. Tot. Age equal to /0 Num ; = is(float) printf( Add Age to“Total Tot. Age age = %dn”, Tot. Age ) ; printf( “Average = %fn”, Ave. Age ) ; Add 1 to Num return 0 ; Ask Age } Divide Tot. Age by Num to find Ave. Age Report the Tot. Age and the Ave. Age

/* The N friend’s age problem – ver 2 */ Decision Logic : if

/* The N friend’s age problem – ver 2 */ Decision Logic : if <cond> Statement #include <stdio. h> Sometimes int main ( it)is {necessary to either perform an action, or not perform the action. These are mutually exclusive int Num=0, Age, Tot. Age=0 ; outcomes of a specified float Ave. Age ; condition. Find the sum and average of the ages (in years) of N friends. Each friend will telluse their age when asked, buttothe actual valuelogic. of N can In printf( C we the if control structure form decision “Enter your age: n” ) ; only be determined by counting scanf( “%d”, &Age ) the ; friends. (version 2) BASIC PROGRAM EXAMPLES The condition expression Solution: while( Age >= 0) {is a valid Boolean expression, typically formed using relational operators. Tot. Age + Age ; inputs Age as <0 Assumptions: A =last person exists who Num. Tot. Age + 1 ; , Ave. Age, Num Identify. Num vars: = Age, printf( “Enter your age: n“ ) ; Initialize: Tot. Age to 0, Num to 0. scanf( “%d”, &Age ) ; Ask } Age Doif while Age is> greater ( Num 0 ) {or equal to 0 = (float) Tot. Age / Num ; Add. Ave. Age to Tot. Age printf( “Total age = %dn”, Tot. Age ) ; Add 1 to Num printf( “Average = %fn”, Ave. Age ) ; Ask Age } Divide Tot. Age by Num to find Ave. Age return 0 ; } Report the Tot. Age and the Ave. Age

/* The N friend’s age problem – ver 2 */ #include <stdio. h> int

/* The N friend’s age problem – ver 2 */ #include <stdio. h> int main ( ) { int Num=0, Age, Tot. Age=0 ; float Ave. Age ; Find the sum and average of the ages (in years) of N friends. Each your age: n” ) ; value of N can friend printf( will tell their“Enter age when asked, but the actual scanf( “%d”, &Age ) the ; friends. (version 2) only. Decision be determined by counting Logic : if <cond> while( Age >= 0) { Statement else Statement In cases where a= decision a specific action, Solution: Tot. Ageof+TRUE Age implies ; FALSE a 1 different, mutually exclusive action, Num =implies ; exists while Assumptions: ANum last +person who inputs Age as <0 the else clause may be used. printf( “Enter your age: n“ ) ; Identify vars: Age, Tot. Age , Ave. Age, Num scanf( “%d”, &Age ) ; Initialize: Tot. Age to 0, Num to 0. } if. Age ( Num > 0 ) { Ask Ave. Age = (float) Tot. Age / Num ; Do while Age is greater or equal to 0 printf( “Total age = %dn”, Tot. Age ) ; Addprintf( Age to Tot. Age “Average = %fn”, Ave. Age ) ; } Add 1 to Num else Ask Age printf( “No data entered. n” ) ; Divide Tot. Age by Num to find Ave. Age return 0 ; } Report the Tot. Age and the Ave. Age BASIC PROGRAM EXAMPLES

BASIC PROGRAM EXAMPLES We have just spent some time examining a simple problem, with

BASIC PROGRAM EXAMPLES We have just spent some time examining a simple problem, with several variations. Along the way we have seen examples of how to Solve the problem and express its solution without using any computer, or special coding techniques Express the solution in the C language Compile a program (a. out) Debug and Test a program

BASIC PROGRAM EXAMPLES Our brief introduction to C-by-example has revealed many aspects Syntax and

BASIC PROGRAM EXAMPLES Our brief introduction to C-by-example has revealed many aspects Syntax and Grammar C pre-processor (#include) and C library (stdio. h) Functions Main Pre-defined (printf, scanf) Statements and Structures Data declaration, data types (int, float) Logical operations (=) Control structures (while, if), simple/compound Expressions Arithmetic Relational logic

LOGIC AND ALGORITHMS IN PROBLEM SOLVING Seek to generalize the applicability of code sequences.

LOGIC AND ALGORITHMS IN PROBLEM SOLVING Seek to generalize the applicability of code sequences. Often these represent fundamental and re-usable algorithms. Large programs typically involve the integration of smaller algorithms. The logic problem often shifts focus to the interface between algorithms (fitting the pieces of a puzzle together). /* A summation algorithm in C */ We started with ages of friends, but we discovered a simple algorithm for finding the sum of a list of numbers. Later, we’ll encapsulate this code within a function. int main ( ) { int N, K=0, A, T=0 ; scanf( “%d”, &N ) ; while( K < N ) { scanf( “%d”, &A ) ; T = T + A ; K = K + 1 ; } printf( “Total = %dn”, T ) ; } return 0 ;

MEMORY AND CPU CONCEPTS Let us get some insight into how our program looks

MEMORY AND CPU CONCEPTS Let us get some insight into how our program looks from a hardware, or executable, viewpoint allocation Memory access Memory addressing CPU control CPU operations O/S communication int main ( ) { int N, K=0, A, T=0 ; float Ave ; scanf( “%d”, &N ) ; while( K < N ) { scanf( “%d”, &A ) ; T = T + A ; K = K + 1 ; } Ave = (float) T / N ; Memory return 0 ; }

MEMORY AND CPU CONCEPTS Address Data 04 EC 32 [int N] uninit 04 EC

MEMORY AND CPU CONCEPTS Address Data 04 EC 32 [int N] uninit 04 EC 36 [int K] 0 04 EC 3 A [int A] uninit 04 EC 3 E [int T] 0 04 EC 42 [float Ave] uninit int main ( ) { int N, K=0, A, T=0 ; float Ave ; scanf( “%d”, &N ) ; while( K < N ) { scanf( “%d”, &A ) ; T = T + A ; K = K + 1 ; } Ave = (float) T / N ; 04 EC 46 return 0 ; } All data containers, such as variables, must be declared according to their assigned name and their prescribed data type (int, float).

MEMORY AND CPU CONCEPTS Address Data 04 EC 32 [int N] uninit 04 EC

MEMORY AND CPU CONCEPTS Address Data 04 EC 32 [int N] uninit 04 EC 36 [int K] 0 04 EC 3 A [int A] uninit 04 EC 3 E [int T] 0 04 EC 42 [float Ave] uninit int main ( ) { int N, K=0, A, T=0 ; float Ave ; scanf( “%d”, &N ) ; while( K < N ) { scanf( “%d”, &A ) ; T = T + A ; K = K + 1 ; } Ave = (float) T / N ; 04 EC 46 return 0 ; } Each data type has a specified size of allocation unit (number of bytes) and the location of a named container is accomplished by the compiler and operating system. C compilers typically initialize variables and mark uninitialized variables to detect meaningless references.

In scanf() functions we provide the address of var_name so that the input knows

In scanf() functions we provide the address of var_name so that the input knows where to place data. Later we will discuss this in more detail – call by reference (address). MEMORY AND CPU CONCEPTS Address Data 04 EC 32 [int N] uninit 04 EC 36 [int K] 0 04 EC 3 A [int A] uninit 04 EC 3 E [int T] 0 04 EC 42 [float Ave] uninit int main ( ) { int N, K=0, A, T=0 ; float Ave ; scanf( “%d”, &N ) ; while( K < N ) { scanf( “%d”, &A ) ; T = T + A ; K = K + 1 ; } Ave = (float) T / N ; 04 EC 46 return 0 ; } RAM addresses are numerical to the computer. Humans are more comfortable with symbols (names). Compilers reconcile this difference by mapping names to numerical address locations where data is stored.

MEMORY AND CPU CONCEPTS Address Data 04 EC 32 [int N] uninit 04 EC

MEMORY AND CPU CONCEPTS Address Data 04 EC 32 [int N] uninit 04 EC 36 [int K] 0 04 EC 3 A [int A] uninit 04 EC 3 E [int T] 0 04 EC 42 [float Ave] uninit int main ( ) { int N, K=0, A, T=0 ; float Ave ; scanf( “%d”, &N ) ; while( K < N ) { scanf( “%d”, &A ) ; T = T + A ; K = K + 1 ; } Ave = (float) T / N ; 04 EC 46 return 0 ; } CPU: Fetch data, Fetch data and operate, Store data Arithmetic, Relational Logic, Boolean Logic, Shift, Data Conversion Interrupts, Control signals

MEMORY AND CPU CONCEPTS When programs are executed, it is a result of the

MEMORY AND CPU CONCEPTS When programs are executed, it is a result of the operating system passing control to the program for a brief period of time. main is identified as an integer function type because it returns an integer value that indicates whether the function has executed correctly (or not). Returning 0 tells the O/S that it may resume control It is not just “polite”, it is a strongly advisable protocol int main ( ) { int N, K=0, A, T=0 ; float Ave ; scanf( “%d”, &N ) ; while( K < N ) { scanf( “%d”, &A ) ; T = T + A ; K = K + 1 ; } Ave = (float) T / N ; return 0 ; }

SYNTAX, GRAMMAR AND PUNCTUATION All programming languages are rigidly defined in order to construct

SYNTAX, GRAMMAR AND PUNCTUATION All programming languages are rigidly defined in order to construct language compilers capable of translating the logic and intention of the programmer into suitable machine language (ie. executable) form Punctuation serves the purpose of clarifying logic into separable language structures or elements Grammar defines the rules of combining key terms and user defined terms into meaningful expressions of logic Syntax prescribes the rules of spelling and other matters that affect self-consistency of coding

SYNTAX, GRAMMAR AND PUNCTUATION Compilers compose machine codes of binary strings into units that

SYNTAX, GRAMMAR AND PUNCTUATION Compilers compose machine codes of binary strings into units that can be loaded into memories and executed. Code modules Data modules I/O buffer modules Stacks and Heap modules Compilers generally issue detailed error and warning messages aimed at syntax errors These should never be ignored. Although they may seem to be a pain in the &#t* they can be the programmer’s best friend Study them and learn how to interpret them

SUMMARY AND REVIEW Lecture 1 D

SUMMARY AND REVIEW Lecture 1 D

SUMMARY AND REVIEW – LECTURE 1 Concepts Computers, systems and networks Structured problem solving

SUMMARY AND REVIEW – LECTURE 1 Concepts Computers, systems and networks Structured problem solving Programming, compilation and execution Memory, Input/Output Techniques C language coding – the main() function Simple statements, variables, operators and I/O Assigned Reading & Study Chapters 1, 2, 3. 1 -3. 4