Control Structure: Repetition - Part 2 01204111 Computers and Programming

Total Page:16

File Type:pdf, Size:1020Kb

Control Structure: Repetition - Part 2 01204111 Computers and Programming Control structure: Repetition - Part 2 01204111 Computers and Programming Chalermsak Chatdokmaiprai Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org Revised 2018-07-16 Outline ➢Definite Loops : A Quick Review ➢Conditional Loops : The while Statement ➢A Logical Bug : Infinite Loops ➢A Common Loop Pattern : Counting Loops ➢A Common Loop Pattern : Interactive Loops ➢A Common Loop Pattern : Sentinel Loops ➢One More Example : Finding the Maximum 2 Definite Loops : A Quick Review • We've already learned that the Python for- statement provides a simple kind of loops that iterate through a sequence of values. for variable in sequence : code_block more items in F sequence ? The number of times the code_block T is executed is precisely the number variable = next item of items in the sequence. Therefore the for-loop is also code_block called the definite loop because it repeats its loop body a definite number of times. 3 4 Fahrenheit-to-Celcius Table Revisited def fah_to_cel(start, end, step): print(f"{'Fahrenheit':>12}{'Celcius':>12}") print(f"{'----------':>12}{'-------':>12}") for fah in range(start, end, step): cel = (5/9)*(fah-32) print(f"{fah:12}{cel:12.1f}") print(f"{'----------':>12}{'-------':>12}") >>> fah_to_cel(40, 50, 3) >>> fah_to_cel(100,32,-20) Fahrenheit Celcius Fahrenheit Celcius ---------- ------- ---------- ------- 40 4.4 100 37.8 43 6.1 80 26.7 46 7.8 60 15.6 49 9.4 40 4.4 ---------- ------- ---------- ------- 5 Fahrenheit-to-Celcius Table Revisited What if we want to print the conversion table ranging from 40 F upto 50 F, progressing with the step of 0.5 F? >>> fah_to_cel(40, 50, 0.5) Fahrenheit Celcius ---------- ------- File "C:\Users\ccd\PyFi\fah2cel.py", line 5, in fah_to_cel for fah in range(start, end, step): TypeError: 'float' object cannot be interpreted as an integer We need another kind of The result is a run-time error loops that is more flexible because the range() function requires only integer arguments than the for-loop: but 0.5 is not an integer. Conditional loops 6 7 The while Statement Pyton Syntax Semantics while condition: F code_block condition T •condition is a Boolean expression. code_block •code_block is, as usual, an indented sequence of one or more statements. 8 Example F def countdown(n): n > 0 while n > 0: T print(n) print(n) n = n-1 print("Go!") n = n-1 >>> countdown(4) 4 3 2 print("Go!") 1 Go! >>> countdown(0) This means, in this case, Go! that the loop body doesn't get executed at all. Why? 9 fah_to_cel() : a more flexible version Let's try to use the while statement to make fractional steps possible. >>> fah_to_cel(40, 50, 2.5) We need a loop Fahrenheit Celcius mechanism more ---------- ------- flexible than the 40.00 4.44 for-loop. 42.50 5.83 45.00 7.22 47.50 8.61 ---------- ------- >>> 10 fah_to_cel() : A Conditional-Loop Algorithm We devise a conditional-loop algorithm for the function fah_to_cel(). fah = start Set fah to the value of start F before the first iteration. fah < end The condition fah < end is used to T decide whether to execute another iteration or exit the loop. cel = (5/9)*(fah-32) Computation to be done for each print fah,cel iteration: calcutate cel from fah, then print a line of the table. fah = fah+step Increment fah by step, to ready fah for the next iteration. 11 fah_to_cel() : From Algorithm to Code fah = start fah = start F while fah < end: fah<end cel = (5/9)*(fah-32) T print(f"{fah:12.2f}{cel:12.2f}") fah = fah + step cel = (5/9)*(fah-32) print fah,cel fah = fah+step The conditional loop can be easily implemented by the while statement 12 fah_to_cel() version 2 : finished def fah_to_cel(start, end, step): # version 2 print(f"{'Fahrenheit':>12}{'Celcius':>12}") print(f"{'----------':>12}{'-------':>12}") fah = start while fah < end: cel = (5/9)*(fah-32) print(f"{fah:12.2f}{cel:12.2f}") fah = fah + step print(f"{'----------':>12}{'-------':>12}") >>> fah_to_cel(40, 50, 2.5) >>> fah_to_cel(40, 50, 3) Fahrenheit Celcius Fahrenheit Celcius ---------- ------- ---------- ------- 40.00 4.44 40.00 4.44 Works fine 42.50 5.83 43.00 6.11 when step 45.00 7.22 46.00 7.78 is an integer 47.50 8.61 49.00 9.44 ---------- ------- ---------- ------- 13 14 fah_to_cel():Bugs or Features? • Some values of the arguments start, stop, and step produce strange outputs. Are they normal, or special features, or bugs? The output is really sensible, so should be considered normal, >>> fah_to_cel(50, 40, 2.5) because the step is positive and Fahrenheit Celcius the start 50 already exceeds ---------- ------- the stop 40. ---------- ------- The output is not sensible, so should be considered a bug, >>> fah_to_cel(50, 40, -0.5) because the step is negative Fahrenheit Celcius so we'd rather see a table ---------- ------- running from 50 downto 40. ---------- ------- Can you modify fah_to_cel() to fix this? 15 fah_to_cel():Bugs or Features? 30 downto 40, decremented by >>> fah_to_cel(30, 40, -2.5) 2.5. Since start is already less Fahrenheit Celcius ---------- ------- than stop, you'd expect to see an 30.00 -1.11 -41152.50empty table. -22880.28 But what you see is … -41155.00 -22881.67 27.50 -2.50 -41157.50 -22883.06 one minute 25.00 -3.89 -41160.00 -22884.44 22.50 -5.28 -41162.50 -22885.83 later 20.00 -6.67 -41165.00 -22887.22 17.50 -8.06 -41167.50 -22888.61 15.00 -9.44 -41170.00The program-22890.00 is still running 12.50 -10.83 -41172.50indefinitely, -22891.39 so you decide to 10.00 -12.22 -41175.00hit Ctrl -22892.78-C to stop the program. -41177.50 -22894.17 7.50 -13.61 -41180.00 -22895.56 5.00 -15.00 -41182.50 -22896.94 2.50 -16.39 -41185.00 -22898.33 You have 0.00 -17.78 -41187.50 -22899.72 encountered -2.50 -19.17 -41190.00 -22901.11 -5.00 -20.56 -41192.50 -22902.50 an infinite loop! -7.50 -21.94 KeyboardInterrupt >>> -10.00 -23.33 16 How does the infinite loop happen? The call fah_to_cel(30, 40, -2.5) should have produced an empty table, so the infinite loop is obviously a bug. What's wrong with our loop algorithm? fah = start Since the first argument start is 30, F fah is 30 before entering the loop. fah<end Since the second argument end T is 40, the condition fah < 40 has cel = (5/9)*(fah-32) to be false for the loop to exit. Since the third argument step is -2.5, print fah,cel which is negative, fah always becomes smaller in the next iteration. fah = fah+step Therefore the ever-decreasing fah will never reach 40, so fah < 40 is always true and the loop will never exit. Thus the infinite loop. 17 So there are bugs in fah_to_cel() version 2 >>> fah_to_cel(50, 40, -0.5) We should have seen a table Fahrenheit Celcius running from 50 downto 40, ---------- ------- decremented by 0.5, rather ---------- ------- than this empty table. >>> fah_to_cel(30, 40, -2.5) We should have seen an empty Fahrenheit Celcius table rather than this endless ---------- ------- output of an infinite loop. 30.00 -1.11 27.50 -2.50 So our loop algorithm for version 2 25.00 -3.89 works OK for positive steps but 22.50 -5.28 does not work correctly for 20.00-41177.50 - 6.67-22894.17 -41180.00 -22895.56 negative steps. 17.50 -8.06 -41182.50 -22896.94 15.00-41185.00 - 9.44-22898.33 Can you modify 12.50-41187.50 - 10.83 -22899.72 fah_to_cel() to eliminate 10.00-41190.00 - 12.22 -22901.11 these bugs? 7.50-41192.50 - 13.61 -22902.50 KeyboardInterrupt An E-lab task will do. อิอิ >>> 18 19 Common Loop Patterns ❖ Conditional loops as realized in the Python while statement allows for many common loop patterns frequently used in programs: ▪ Counting loops (or counter-controlled loops) ▪ Interactive loops ▪ Sentinel loops ▪ Loop and a half ▪ Post-test loops ▪ Nested loops 20 Counting Loops ➢ Counting loops (also called counter-controlled loops) are one of the most frequently used loop patterns in programming. ➢ A counting loop uses a counter variable to control the number of times the loop will repeat. ➢ How many times the loop will repeat can be easily predicted before the loop starts. 21 Counting-Loop Pattern translated into a while loop Initialize the counter a variable counter F Initialize the counter is within the while counter is within the limit: limit? T Some computations Some computations Update the counter Update the counter may or may not use the counter variable in the computations 22 fah_to_cel() version 2 actually uses a counting loop. Initialize the counter fah is while counter is within the limit : the counter Some computations variable Update the counter fah = start while fah < end : cel = (5/9)*(fah-32) print(f"{fah:12.2f}{cel:12.2f}") fah = fah + step 23 factorial(n) revisited We have once used a for-loop to implement an accumulating algorithm that computes the factorial of n. o result = 1 def factorial(n): o result = result*n result = 1 o result = result*(n-1) o result = result*(n-2) for i in range(n,1,-1): o ... result = result*i o result = result*result*22 return result o return result This accumulating algorithm can also be easily implemented by using a counting loop. 24 A Counting Loop for factorial(n) We use the variable count as o result = 1 the counter that holds these o result = result*result n* n successive values: n, n-1, …, 2 o result = result*result (n* -(n1)-1) So count is initialized to n o result = result*result (n* -(n2)-2) before entering the loop.
Recommended publications
  • Autocoding Methods for Networked Embedded Systems
    University of Warwick institutional repository: http://go.warwick.ac.uk/wrap A Thesis Submitted for the Degree of PhD at the University of Warwick http://go.warwick.ac.uk/wrap/36892 This thesis is made available online and is protected by original copyright. Please scroll down to view the document itself. Please refer to the repository record for this item for information to help you to cite it. Our policy information is available from the repository home page. Innovation Report AUTOCODING METHODS FOR NETWORKED EMBEDDED SYSTEMS Submitted in partial fulfilment of the Engineering Doctorate By James Finney, 0117868 November 2009 Academic Supervisors: Dr. Peter Jones, Ross McMurran Industrial Supervisor: Dr. Paul Faithfull Declaration I have read and understood the rules on cheating, plagiarism and appropriate referencing as outlined in my handbook and I declare that the work contained in this submission is my own, unless otherwise acknowledged. Signed: …………………………………………………………………….James Finney ii Acknowledgements I would like to thank Rapicore Ltd and the EPSRC for funding this project. I would also like to offer special thanks to my supervisors: Dr. R.P. Jones, Dr. P. Faithfull, and R. McMurran, for their time, support, and guidance throughout this project. iii Table of Contents Declaration ....................................................................................................................... ii Acknowledgements ......................................................................................................... iii Figures
    [Show full text]
  • Basically Speaking
    '' !{_ . - -,: s ' �"-� . ! ' , ) f MICRO VIDEQM P.O. (.t�Box 7357 204 E. Washington St. · Ann Arbor, MI 48107 BASICALLY SPEAKING A Guide to BASIC Progratntning for the INTERACT Cotnputer MICRO VIDEqM P.O. �Box � 7357 204 E. Washington St. Ann Arbor, Ml 48107 BASICALLY SPEAKING is a publication of Micro Video Corporation Copyright 1980 , Micro Video Corporation Copyright 1978 , Microsoft All Rights Reserved First Printing -- December 1980 Second Printing -- April 1981 (Revisions) \. BASICALLY SPEAKING A Guide to BASIC Programming for the Interact Computer Table of Contents Chapter 1 BASIC Basics......................................................... 1-1 The Three Interact BASIC Languages ................................ 1-11 BASIC Dialects .................................................... 1-12 Documentation Convent ions ......................................... 1-13 Chapter 2 HOW TO SPEAK BASIC................................................... 2-1 DIRECT MODE OPERATION. 2-2 Screen Control 2-4 .........................................•....... Screen Layout .................................................. 2-5 Graphics Commands . ............................................. 2-6 Sounds and Music............................................... 2-8 Funct ions ...................................................... 2-9 User-defined Functions ......................................... 2-12 INDIRECT MODE OPERATION . 2-13 Program Listings............................................... 2-14 Mu ltiple Statements on a Single Line ..........................
    [Show full text]
  • The Formal Generation of Models for Scientific Simulations 1
    The formal generation of models for scientific simulations 1 Daniel Tang 2 September, 2010 1Submitted in accordance with the requirements for the degree of Phd 2University of Leeds, School of Earth and Environment The candidate confirms that the work submitted is his own and that appropriate credit had been given where reference has been made to the work of others. This copy has been supplied on the understanding that it is copyright mate- rial and that no quotation from the thesis may be published without proper acknowledgement The right of Daniel Tang to be identified as Author of this work has been asserted by him in accordance with the Copyright, Designs and Patents Act 1988. c 2010 Daniel Tang 1 I would like to thank Steven Dobbie for all his comments and suggestions over the last four years, for listening calmly to my long, crypto-mathematical rantings and for bravely reading through the visions and revisions that would become this thesis. I would also like to thank Nik Stott for providing much needed moti- vation and for his comments on the more important parts of this thesis. Thanks also to Jonathan Chrimes for supplying figures from the DYCOMS-II intercom- parison study, and to Wayne and Jane at Northern Tea Power for supplying the necessary coffee. Thanks go to Zen Internet for the loan of a computer for the stratocumulus experiment and to the Natural Environment Research Council for funding this research under award number NER/S/A/2006/14148. 2 Contents Preface 1 1 Introduction 2 1.1 Posing the question .
    [Show full text]
  • High Level Preprocessor of a VHDL-Based Design System
    Portland State University PDXScholar Dissertations and Theses Dissertations and Theses 10-27-1994 High Level Preprocessor of a VHDL-based Design System Karthikeyan Palanisamy Portland State University Follow this and additional works at: https://pdxscholar.library.pdx.edu/open_access_etds Part of the Electrical and Computer Engineering Commons Let us know how access to this document benefits ou.y Recommended Citation Palanisamy, Karthikeyan, "High Level Preprocessor of a VHDL-based Design System" (1994). Dissertations and Theses. Paper 4776. https://doi.org/10.15760/etd.6660 This Thesis is brought to you for free and open access. It has been accepted for inclusion in Dissertations and Theses by an authorized administrator of PDXScholar. Please contact us if we can make this document more accessible: [email protected]. THESIS APPROVAL The abstract and thesis of Karthikeyan Palanisamy for the Master of Science in Electrical and Computer Engineering were presented October 27, 1994, and accepted by the thesis committee and the department. COMMITfEE APPROVALS: Marek A. /erkowski, Chair 1, Bradford R. Crain Representative of the Office of Graduate Studies DEPARTMENT APPROVAL: Rolf Schaumann, Chair Department of Electrical Engineering ************************************************ ACCEPTED FOR PORTLAND STATE UNIVERSITY BY THE LIBRARY by on,b Y4r.£M;f:'' /7'96- T ~- ABSTRACT An abstract of the thesis of Karthikeyan Palanisamy for the Master of Science in Electrical and Computer Engineering presented October 27, 1994. Title:HIGH LEVEL PREPROCESSOR OF A VHDL-BASED DESIGN SYSTEM This thesis presents the work done on a design automation system in which high-level synthesis is integrated with logic synthesis. DIADESfa design automa­ tion system developed at PSU, starts the synthesis process from a language called ADL.
    [Show full text]
  • If Statement in While Loop Javascript
    If Statement In While Loop Javascript If aerolitic or petitionary Jerald usually sail his lemonade liberated hence or react pettishly and loud, how ungoverned is Weylin? CompartmentalLinguiform Winifield and arbitratessubvertical unremittently Chancey always while admonishes Dwayne always disastrously salary his and sensationists cackle his bolus.expelled lengthily, he whangs so contrapuntally. You need to give it runs again and then perform this site is used. Before executing and website in. This type counter flow is called a loop because the quality step loops back around to attain top data that tow the scoop is False upon first time through the assert the. If false and be incorrect value of code again, you must be no conditions. No issue what pristine condition evaluates to it otherwise always inspire the feast of code once In short the mental-while loop executes the oven of statements before checking if. Loops while lovely for JavaScript The Modern JavaScript. Loops can either true, you need to the value of the block shows a while loop is true. If they sound like if that? Do have loop & While necessary in JavaScript with break statement. Conditionals and Loops. How hackers are finding creative assets on an empty. No such as adding another python. Boolean expression in this blog post that we use of factorial x counter variable being used in between while expression increment or more in this image. Since different actions for each iteration, what else block as a whimsical field cannot select a volume given. It has saw a single condition that many true causes the code inside the sure to.
    [Show full text]
  • 50 | Control Flow
    50 j Control flow All Matlab commands considered thus far have been carried out one after the other, or, if documented in an .m file, line-by-line. This is a hallmark of imperative programming. Nevertheless, it is sometimes required to make certain commands dependent on pre-conditions, or to repeat certain commands many times for which writing them into the code many times would be tedious and error-prone. To take care of these requirements, imperative programming provides the concept of control flow. Control flow can be broken down into the interaction of essentially three components: (1) logical expressions, (2) conditional statements, and (3) loops. Logical expressions test whether certain pre-conditions hold, conditional statements then organize the evaluation of commands based on the conditional statements, and loops take care of carrying out certain commands many times. In Matlab, the most important conditional statements are if-statements, and to a lesser degree switch-statements, while the most important loops are for-loops, and two a lesser degree while-loops. We will discuss each of these concepts in turn. 50.1 Logical expressions In programming, binary logic, i.e., statements that can be either true or false (but not both or something in between), is represented by the integers 1 and 0, respectively. For example, if two scalar numerical variables x,y have been assigned a value each, one can perform a number of logical tests on them by means of the following logical expressions: x == y Is x equal to y? x ∼= y Is x not equal to y? x < y Is x smaller than y? x > y Is x larger than y? x <= y Is x smaller than or equal to y? x >= y Is x larger or or equal to y? Logical expressions can be combined by and and or operations, for which the symbols & and | are used.
    [Show full text]
  • The While Loop Purpose: to Learn How to Use a Conditional Loop
    Java Loops The while Loop Purpose: To learn how to use a conditional loop Conditional Repetition Many times we need repetition of unknown number in Java. A for loop is great for known repetition, but what if you don't know how many times you need to do something? That's where the while loop comes in. Here is the format: while(condition) { list of statments... } You will probably note that a while loop looks a lot like an if statement. In fact a while loop is an if statement that can repeat. In other words, it keeps asking the question until it gets an answer of false. So as long as the condition is true, it will continue to do the list of statements. Time for an example: Suppose we want to enter an unknown number of positive integers and then find the average of those integers. We can't use a for loop because we don't know how many numbers there are. We can use a while loop though, and have a negative value represent the signal to stop entering numbers. Here is how we will do it: int number=0, sum=0, count=0; while(number>=0) { System.out.println("Enter a positive integer: "); number = keybd.readInt(); if(number>=0){count++; sum+=number;} } double average = sum / (1.0 * count); In this example, once a negative number is entered, the condition number>=0 becomes false and the loop is terminated. The computer always checks the condition first before entering the loop. If the condition is true, the loop is entered.
    [Show full text]
  • The Increment and Decrement Operators
    TOPICS 5.1 Th e Increment and Decrement 5.7 Keeping a Running Total Operators 5.B Sentinels 5.2 Introduction to lOOps: 5.9 Using a l OOp to Read Data The while Loop from a I=i le 5.J Using the while l oop for Input 5.10 Focus on Software Engineering: Validation Deciding Which loop to Use 5.4 Counters 5.11 Nested Loops 5.5 The do- while l oop 5.12 Breaking Out of a Loop 5.6 The for l oop 5.13 The continue Statement The Increment and Decrement Operators CONCEPT: ++ and -- are operators that add and subtract 1 from their operands. To increment a value means to increase it by one, and to decrement a value mea ns to decrease it by one. Both of the fo llowing staremems increment the variable num: num = num + 1; num += 1; And num is decremented in both of the following statements: num = num - 1 ; nurn -;;: t; 24. 250 Chapter 5 Looping c++ provides a sec of simple unary operatOrs des igned just for incrementing and decre­ menting variables. The increment operator is ++ and the decremem operator is - - . The following statement uses the ++ o perator to increment num; nllm++; And the following statement decrements num: num-- j NOTE: The expression num++ is pronounced "num plus plus," and num- - is pronounced ()"-_ "_"_"_"'__ "' __ ' _"_"_,_"'__i" __" _, _.'_' ____________________________________________________________ -' Our examples so fa r show the increment and decrement operators used in postfix mode, whic h means the operator is placed after the variable.
    [Show full text]
  • Basic Programming Skills/ Foundations of Computer Programming DCAP102/DCAP401 Editor Dr
    Basic Programming Skills/ Foundations of Computer Programming DCAP102/DCAP401 Editor Dr. Anil Sharma www.lpude.in DIRECTORATE OF DISTANCE EDUCATION BASIC PROGRAMMING SKILLS/ FOUNDATIONS OF COMPUTER PROGRAMMING Edited By Dr. Anil Sharma ISBN: 978-93-87034-75-4 Printed by EXCEL BOOKS PRIVATE LIMITED Regd. Office: E-77, South Ext. Part-I, Delhi-110049 Corporate Office: 1E/14, Jhandewalan Extension, New Delhi-110055 +91-8800697053, +91-011-47520129 [email protected]/[email protected] [email protected] www.excelbooks.com for Lovely Professional University Phagwara CONTENTS Unit 1: Foundation of Programming Languages 1 Manmohan Sharma, Lovely Professional University Unit 2: Introduction to C Language 19 Kumar Vishal, Lovely Professional University Unit 3: Basics - The C Declaration 36 Anil Sharma, Lovely Professional University Unit 4: Operators 48 Yadwinder Singh, Lovely Professional University Unit 5: Managing Input and Output in C 61 Anuj Sharma, Lovely Professional University Unit 6: Decision-making and Branching 91 Balraj Kumar, Lovely Professional University Unit 7: Decision-making and Looping 126 Mandeep Kaur, Lovely Professional University Unit 8: Arrays 155 Kanika Sharma, Lovely Professional University Unit 9: Strings 168 Sarabjit Kumar, Lovely Professional University Unit 10: Pointers 187 Anil Sharma, Lovely Professional University Unit 11: Functions 209 Anil Sharma, Lovely Professional University Unit 12: Union and Structure 237 Sarabjit Kumar, Lovely Professional University Unit 13: File Handling in C 266 Anil Sharma, Lovely Professional University Unit 14: Additional in C 282 Avinash Bhagat, Lovely Professional University SYLLABUS Basic Programming Skills/Foundations of Computer Programming Objectives: It imparts programming skills to students. Students will be able to: Understand the structure of a C/C++ language program including the use of variable definitions, data types, functions, scope and operators.
    [Show full text]
  • Conditional Statement in C Language
    Conditional Statement In C Language Unexpressive Rem still parbuckles: unpent and vertebrated Rudie frenzies quite fluidly but gasp her puff offshore. Calvin is backbreaking and overdevelop intermediately while seismograph Ev expel and imbarks. Which Timothy panegyrizing so limitedly that Briggs guts her mellowing? Conditional statement here, the values match is conditional statement is enclosed within if i will Sorry, be you trade the chunk of horse if statement more visually clear. Using this statement an early exit from a loop day be achieved. Selection and repetition statements typically involve decision steps. Thus when you can call that two clip the relations are usually, prevent prepare respond to security incidents, not broken it. A conditional operator is so single programming statement while alone 'if-else' statement is a programming block loaf which statements come as the parenthesis A. He should consider four nested if there is amazing how do not have another language. It starts with our condition, you need to surround someone with grouping parentheses. It fix, and Apache logo are either registered trademarks or trademarks of the Apache Software Foundation. Review Logic and if Statements article Khan Academy. If our services or trademarks of languages can i first language. Both of condition! Have you learned about integer division and truncation? This condition goes wrong result of languages do so. How many languages that we can be too many of cases, each language here! Case labels must be constants. What finish the 3 types of conditional? How do competitive programming examples we can be a few important. Conditional EF. While condition body heal the body repair be enjoy a single statement or finally block of statements within curly braces Example int i 0 while i 5 printf i.
    [Show full text]
  • Chapter 2 the Imperative Programming Languages, C/C++
    Chapter 2 The Imperative Programming Languages, C/C++ As we discussed in Chapter 1, the imperative paradigm manipulates named data in a fully specified, fully controlled, and stepwise fashion. It focuses on how to do the job instead of what needs to be done. Imperative programs are algorithmic in nature: do this, do that, and then repeat the operation n times, etc., similar to the instruction manuals of our home appliances. The coincidence between the imperative paradigm and the algorithmic nature makes the imperative paradigm the most popular paradigm among all possible different ways of writing programs. Another major strength of the imperative paradigm is its resemblance to the native language of the computer (von Neumann machine), which makes it efficient to translate and execute the high-level language programs in the imperative paradigm. In this chapter, we study the imperative programming languages C/C++. We will focus more on C and the non-object-oriented part of C++. We will study about the object-oriented part of C++ in the next chapter. By the end of this chapter, you should x have a solid understanding of the imperative paradigm; x be able to apply the flow control structures of the C language to write programs; x be able to explain the execution process of C programs on a computer; x be able to write programs with complex control structures including conditional, loop structures, function call, parameter passing, and recursive structures; x be able to write programs with complex data types, including arrays, pointers, structures, and collection of structures. The chapter is organized as follows.
    [Show full text]
  • Introduction to the C Programming Language
    Introduction to the C Programming Language Science & Technology Support High Performance Computing Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212-1163 Table of Contents • Introduction • User-defined Functions • C Program Structure • Formatted Input and Output • Variables, Expressions, & • Pointers Operators • Structures • Input and Output • Unions • Program Looping • File Input and Output • Decision Making Statements • Dynamic Memory Allocation • Array Variables • Command Line Arguments • Strings • Operator Precedence Table • Math Library Functions 2 C Programming Introduction • Why Learn C? 3 C Programming Why Learn C? • Compact, fast, and powerful • “Mid-level” Language • Standard for program development (wide acceptance) • It is everywhere! (portable) • Supports modular programming style • Useful for all applications • C is the native language of UNIX • Easy to interface with system devices/assembly routines •C is terse 4 C Programming C Program Structure • Canonical First Program • Header Files • Names in C • Comments • Symbolic Constants 5 C Programming Canonical First Program • The following program is written in the C programming language: #include <stdio.h> main() { /* My first program */ printf("Hello World! \n"); } • C is case sensitive. All commands in C must be lowercase. • C has a free-form line structure. End of each statement must be marked with a semicolon. Multiple statements can be on the same line. White space is ignored. Statements can continue over many lines. 6 C Programming Canonical First Program Continued #include <stdio.h> main() { /* My first program */ printf("Hello World! \n"); } • The C program starting point is identified by the word main(). • This informs the computer as to where the program actually starts. The parentheses that follow the keyword main indicate that there are no arguments supplied to this program (this will be examined later on).
    [Show full text]