39
Unit 1 Introduction to C Programming

Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Embed Size (px)

Citation preview

Page 1: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Unit 1

Introduction toC Programming

Page 2: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

What is a Program?

Unit 1: Programs

Page 3: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Recall: A Computer System is … Hardware

Central processing unit (CPU)Main memory (RAM, ROM)Secondary memory (Hard disk, CD, DVD, flash

drive, etc)Input devicesOutput devicesNetwork interfacePower supply

SoftwareFirmwareOperating systemApplication programs

Page 4: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

What is a Software “Program”?

A set of instructions Performs a specific task Required to make the hardware “do

something” The hardware “runs” or “executes” it Must be in main memory (RAM or ROM) Is written in machine language (specific to

a CPU) Consists of binary ‘1’s and ‘0’s

Page 5: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

How a Program gets into Memory It is always stored in memory (ROM)

Firmware such as a PC BIOSEmbedded systems contain ROM or Flash

From secondary storage when neededRead from the Hard Disk into main memoryRead directly from a CD or DVD into main

memory Via the network

Automatic updates from the program vendorWeb pages and web applications with active

contentMobile applicationsCloud computing

Page 6: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Programs are Very Diverse … Mobile applications – Info services and transactions Web applications – Web pages, shopping, Virtual Library Business applications – Word processing, email,

accounting Leisure applications – Games, e-book readers Educational applications – Language learning,

encyclopedia Batch data processing – Payrolls, bank statements Server software – Provide information services via web Operating systems – Control hardware, software,

security Control systems – Automation, energy management Embedded software – Routers, printers, appliances,

automobiles, cameras, watches, cell phones, lighting control

Page 7: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

…But Programs Have Much in Common

Programs process informationInformation is stored in the form of binary dataDifferent types of information use different data

typesPrograms acquire input dataPrograms produce output data

Programs are implementations of algorithmsAlgorithms are precise solutions to problems

Programs are written in programming languagesMay be compiled (translated) to machine languageMay be compiled to intermediate form and then

interpreted

Page 8: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

This Class Introduces Programming Programming is the discipline and art of creating

software Focus is on fundamental concepts and building skills Examples, labs, and projects will use the C language Prerequisite class – NT1110 Computer Structure &

Logic Future classes:

ELCT: ET2640 Microprocessors and MicrocontrollersELCT: ET2750 Programmable Logic ControllersEECT: ET4560 C++ ProgrammingEECT: ET4640 Embedded Systems

Page 9: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Programs Relevant to Electronics

Unit 1: Programs

Page 10: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Program-based Solutions Programs used to solve electrical engineering problems

Solutions of equations needed for design and analysisExample: Iterative calculations of roots of complex polynomialsExample: www.wolframalpha.com – Knowledge computation engine

Try: “0.45 ohms per foot for 100 meters”Simulation software to try circuit design before building

MultisimChip design software

Cost is hundreds of thousands of dollars per workstationOne design engineer can access immense libraries of knowledgeSimulations can save millions in time and manufacturing costs

Page 11: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

What is a Control System? An electronic control system is a device that:

Regulates a process (such as a manufacturing system)

Components:Sensors – Convert physical variables to electronic signalsControllers – Based on sensor data, send signals to

actuatorsActuators – Use electronic signals to affect physical world

Example: A commercial baking ovenExample: An automobile engine

The controller can be …Analog electronicsHard-wired digital electronicsA programmable computer-based controller

Page 12: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Benefits of Programmable Control Flexibility – can be reprogrammed

UpgradableCan have optional featuresDefects can be easily repaired

Lower engineering costsStandard hardware designs availableSoftware designs can be reused

Self-testing and error reporting Programmable logic controllers – PLCs

Off-the-shelf hardwareSimplified programming

Page 13: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Embedded Systems Found everywhere as part of electronic devices Examples: Watches, calculators, appliances,

irrigation and lighting systems, copiers, traffic lights, MP3 players

Pre-programmed computer Dedicated to a few functions inside a device Often must be real-time (respond “immediately”

to events) Non-stop computing (continuously functioning) Traditionally viewed as non-reprogrammable Reprogrammability is becoming commonplaceTherefore, programming is essential to

electronics students!

Page 14: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

How are Programs Created?

Unit 1: Software Development Process

Page 15: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Creating a Program Use problem solving skills Create an algorithm Implement the algorithm in a programming

language Understand the programming model Use specialized tools Use software engineering methodology

Page 16: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Use Problem-Solving Process

Heuristics (strategies) for successful problem solving

Five-step process (from Strategies for Creative Problem Solving, Fogler et al)1. Define the problem2. Generate possible solutions3. Evaluate and decide on a solution4. Implement the solution5. Evaluate the solution

Page 17: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Develop Problem-Solving Skills

A good programmer is an effective problem solver Has a belief that problems can be solved through

analysis Develops a high level of problem-solving skills:

Active – Makes sketches, draws figures, asks questions

Methodical – Keeps track of progress in solving the problem

Detail-orientedTakes great care to understand facts and

relationshipsChecks and re-checks for accuracy

Page 18: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Create an Algorithm

Develop an algorithm before writing a program

Use precise statementsBased in mathematics and logicClear and concrete language

Define a step-by-step process Goal is solution to a problem

Page 19: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Use a Programming Language A computer’s CPU uses machine language

Consists of binary values representing instructionsNot practical for human programmers

Assembly languageLow-level language closely tied to machine languageOnce widely used, now only specialized use

High-level languagesHundreds to thousands of languages in useMuch easier to use than assembly and machine

languageCompiler provides automatic translation to machine

language

Page 20: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Based on a Programming Model The operating system (OS) presents the

programming modelAn OS is used on all but the smallest computersControls the hardwareStandardizes access to files, shared resourcesMay be console user interface or graphical (GUI) user

interfaceConsole-based user interface

Called “command-line” accessBased on text serial input and output

Graphical user interface (GUI)Based on point-and-click or touch screen and windowed

interfaceEvent-driven, object-oriented model

Embedded systems may not have a user interface at all

Page 21: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

The Compiler Approach A compiler is a translation program

Input is written using a programming languageOutput is assembly language for one specific CPU

instruction set Assembler may be included or separate

Completes the translation into machine language Linker

Combines translated program pieces with library pieces

Creates a complete, executable module Operating system and loader

Loads module into main memory and starts execution Process must be done again for each type of “host”

system

Page 22: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

The Interpreter Approach Compiler creates an intermediate representation

Program is neither in high-level language, nor machine language

Instead, it is “virtual instructions” in an intermediate language

The virtual instructions are the same for all CPUs Interpreter follows the virtual instructions

A different interpreter is needed for each CPU type Benefits

A single compilation can theoretically be used on all computers

Presents a common programming model on multiple CPUs

DrawbackInterpreters are slower than compiled (“native”)

programs

Page 23: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

The “Just-In-Time” (JIT) Approach Compiler

Creates an Intermediate Language (IL) representation Runtime system

Does not interpretContains a “compiler” which completes compilationResult is machine language produced just before

execution Best of both worlds

Code can be “Compiled once, Run anywhere” (e.g. Java, .NET)

Single programming model regardless of computer host

Program execution speed is comparable to native code

Page 24: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Specialized Programming Tools Editor Compiler Assembler Debugger Support files Libraries Integrated development environment

Complete package of toolsUses a “project-based” approach

Page 25: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Software Engineering Waterfall model, iterative model, agile

developmentProcesses to move from idea to product

Lifecycle managementBeginning-to-end product managementIncludes program maintenance over time

Support and structure for working in teamsCoding standardsChange controlProject management

Human factors“User friendly” design, ease of use

Page 26: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

What is an Algorithm?

Unit 1: Algorithms

Page 27: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Software Development Method

1. Specify the problem requirements2. Analyze the problem3. Design the algorithm to solve the problem4. Implement the algorithm as a program5. Test and verify the completed program6. Maintain and update the program

Page 28: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Analyzing the Problem Requires identifying the …

Inputs – the data available to work withOutputs – the desired results

Including the format of the outputAdditional requirementsConstraints

Page 29: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Producing the Algorithm List of steps from beginning to end Begin at step 1, have a specific step to End Don’t try to get every detail at first Use top-down design:

Break the problem into subproblemsSolve each subproblem individuallySimilar to outlining a written paper

Use pseudo-code combined with flowcharting

Desk-check the algorithm

Page 30: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Convert the Algorithm to a Program Implement the flowchart and pseudo-code as

a program Verify that the program compiles Test the program

Create several test cases and verify the resultsTest boundary conditionsEnter erroneous data intentionally

If the program behaves unexpectedly, back upDouble-check the algorithm, modify if neededDouble-check the program, modify if neededUse debugging tools and techniques

Page 31: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Identify Variables Information in an algorithm is put into variables A variable is the programming term describing the

storage of a single datum or a collection of data. In a program, the compiler will put the variables into

memory Each data item used in the algorithm should be

given a name Each name should be distinct and used for only one

variable Data types for variables include:

Integers: 0, 12, -53Decimal numbers: 22.76, 193.1Decimals in scientific notation 3.0x108

Character strings (in double-quotes) “Programming is fun!”

Page 32: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Simple Example: miles to kilometers Problem statement

“Convert a distance in miles to kilometers” Identify the inputs

dist_in_milesA decimal number representing a distance in miles

Identify the outputsdist_in_kmsA decimal number representing the distance in kilometers

Page 33: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

List the Steps to Solve the ProblemBreak the problem into steps:

1. Input the dist_in_miles2. Convert dist_in_miles to kilometers3. Output the dist_in_kms

As you can see, step 2 is not precise, because it does not specify how to do the conversion. This is not yet a complete algorithm.

Page 34: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

What is the Formula for Step 2?

One mile is equal to approximately equal to

1.609 km A number of miles can be converted to

kilometers by multiplying by 1.609 The formula is:

dist_in_km = dist_in_mi × 1.609

Page 35: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

Algorithm to Convert mi to km

1. Input the dist_in_miles2. Convert dist_in_miles to kilometers

a) Multiply dist_in_miles by 1.609b) Put the result in dist_in_kms

3. Output the dist_in_kms4. End

This algorithm accomplishes the task, but it is not user-friendly. We need to add some human factors to the algorithm.

Page 36: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

An Improved Algorithm

1. Output “Convert miles to kilometers”2. Output “Please enter the distance in miles”3. Input dist_in_miles4. Convert dist_in_miles to kilometers

a)Multiply dist_in_miles by 1.609b)Put the result in dist_in_kms

5. Output “The distance in kilometers is ”6. Output dist_in_kms7. End

As you can see, creating a good algorithm requires substantial effort and attention to details

Page 37: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

An Algorithm to List #s < 10

1. Output “List of Numbers less than 10”2. Put 1 in number3. Output number4. Add 1 to number5. If number is less than 10, go back to step

36. End

Notice this algorithm has no inputs, only one variable, “number”

Page 38: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

An Algorithm to List Odd #s < 10

1. Output “List of Odd Numbers less than 10”2. Put 1 in number3. If number is even, skip to step 54. Output number5. Add 1 to number6. If number is less than 10, go back to step 37. End

Is this an algorithm? Is step 3 sufficiently precise?

Page 39: Unit 1 Introduction to C Programming. What is a Program? Unit 1: Programs

An Algorithm to List Odd #s < 10

1. Output “List of Odd Numbers less than 10”2. Put 1 in number3. If number divided by 2 has remainder 0, go

to step 54. Output number5. Add 1 to number6. If number is less than 10, go back to step 37. End

Now we have precise instructions which can be followed!