Learn to Program with C

323 3.1K 0
Learn to Program with C

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Learn the fundamental programming principles using C, one of the most widely used programming languages in the world today. Learn to Program with C teaches computer programming to the complete beginner using the native C language. As such, it assumes you have no knowledge whatsoever about programming. We discuss only those features and statements in C that are necessary to achieve our goal. Once you learn the principles well, they can be applied to any language. If you are worried that you are not good at highschool mathematics, dont be. It is a myth that you must be good at mathematics to learn programming.

T HE E X P ER T ’S VOIC E ® IN P ROGR A M MING Learn to Program with C Learn to Program using the Popular C Programming Language — Noel Kalicharan www.it-ebooks.info Learn to Program with C Noel Kalicharan www.it-ebooks.info Learn to Program with C Copyright © 2015 by Noel Kalicharan This work is subject to copyright All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer Permissions for use may be obtained through RightsLink at the Copyright Clearance Center Violations are liable to prosecution under the respective Copyright Law ISBN-13 (pbk): 978-1-4842-1372-8 ISBN-13 (electronic): 978-1-4842-1371-1 Trademarked names, logos, and images may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made The publisher makes no warranty, express or implied, with respect to the material contained herein Managing Director: Welmoed Spahr Lead Editor: Steve Anglin Technical Reviewer: Rohan Walia Editorial Board: Steve Anglin, Louise Corrigan, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Susan McDermott, Matthew Moodie, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Gwenan Spearing Coordinating Editor: Mark Powers Copy Editor: Karen Jameson Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc) SSBM Finance Inc is a Delaware corporation For information on translations, please e-mail rights@apress.com, or visit www.apress.com Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com/9781484213728 For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter www.it-ebooks.info To my daughters Anushka Nikita and Saskia Anyara www.it-ebooks.info Contents at a Glance About the Author�����������������������������������������������������������������������������������������������������xv About the Technical Reviewer�������������������������������������������������������������������������������xvii Acknowledgments��������������������������������������������������������������������������������������������������xix Preface�������������������������������������������������������������������������������������������������������������������xxi ■Chapter ■ 1: Elementary Programming Concepts���������������������������������������������������� ■Chapter ■ 2: C – The Basics������������������������������������������������������������������������������������ 23 ■Chapter ■ 3: Programs with Sequence Logic��������������������������������������������������������� 47 ■Chapter ■ 4: Programs with Selection Logic���������������������������������������������������������� 65 ■Chapter ■ 5: Programs with Repetition Logic��������������������������������������������������������� 91 ■Chapter ■ 6: Characters���������������������������������������������������������������������������������������� 141 ■Chapter ■ 7: Functions����������������������������������������������������������������������������������������� 165 ■Chapter ■ 8: Arrays���������������������������������������������������������������������������������������������� 197 ■Chapter ■ 9: Searching, Sorting, and Merging����������������������������������������������������� 243 ■Chapter ■ 10: Structures�������������������������������������������������������������������������������������� 279 Index��������������������������������������������������������������������������������������������������������������������� 307 v www.it-ebooks.info Contents About the Author�����������������������������������������������������������������������������������������������������xv About the Technical Reviewer�������������������������������������������������������������������������������xvii Acknowledgments��������������������������������������������������������������������������������������������������xix Preface�������������������������������������������������������������������������������������������������������������������xxi ■Chapter ■ 1: Elementary Programming Concepts���������������������������������������������������� 1.1 Programs, Languages, and Compilers������������������������������������������������������������������������ 1.2 How a Computer Solves a Problem���������������������������������������������������������������������������� 1.2.1 Define the Problem������������������������������������������������������������������������������������������������������������������������ 1.2.2 Analyze the Problem���������������������������������������������������������������������������������������������������������������������� 1.2.3 Develop an Algorithm to Solve the Problem���������������������������������������������������������������������������������� 1.2.4 Write the Program for the Algorithm���������������������������������������������������������������������������������������������� 1.2.5 Test and Debug the Program��������������������������������������������������������������������������������������������������������� 1.2.6 Document the Program����������������������������������������������������������������������������������������������������������������� 1.2.7 Maintain the Program�������������������������������������������������������������������������������������������������������������������� 1.3 How a Computer Executes a Program������������������������������������������������������������������������ 1.4 Data Types���������������������������������������������������������������������������������������������������������������� 10 1.5 Characters���������������������������������������������������������������������������������������������������������������� 11 1.6 Welcome to C Programming������������������������������������������������������������������������������������� 12 1.6.1 Run the Program�������������������������������������������������������������������������������������������������������������������������� 13 1.6.2 A Word on Program Layout���������������������������������������������������������������������������������������������������������� 14 vii www.it-ebooks.info ■ Contents 1.7 Write Output with printf���������������������������������������������������������������������������������������� 14 1.7.1 The Newline Character, \n (backslash n)������������������������������������������������������������������������������������ 15 1.7.2 Escape Sequences���������������������������������������������������������������������������������������������������������������������� 16 1.7.3 Print the Value of a Variable��������������������������������������������������������������������������������������������������������� 16 1.8 Comments���������������������������������������������������������������������������������������������������������������� 17 1.9 Programming with Variables������������������������������������������������������������������������������������ 18 ■Chapter ■ 2: C – The Basics������������������������������������������������������������������������������������ 23 2.1 Introduction�������������������������������������������������������������������������������������������������������������� 23 2.2 The C Alphabet��������������������������������������������������������������������������������������������������������� 24 2.3 C Tokens������������������������������������������������������������������������������������������������������������������� 24 2.3.1 Spacing Within a Program����������������������������������������������������������������������������������������������������������� 25 2.3.2 Reserved Words��������������������������������������������������������������������������������������������������������������������������� 27 2.3.3 Identifiers������������������������������������������������������������������������������������������������������������������������������������ 27 2.3.4 Some Naming Conventions��������������������������������������������������������������������������������������������������������� 28 2.4 Basic Data Types������������������������������������������������������������������������������������������������������ 28 2.5 Integer Numbers - int��������������������������������������������������������������������������������������������� 29 2.5.1 Declaring Variables���������������������������������������������������������������������������������������������������������������������� 29 2.5.2 Integer Expressions��������������������������������������������������������������������������������������������������������������������� 29 2.5.3 Precedence of Operators������������������������������������������������������������������������������������������������������������� 30 2.5.4 Print an Integer Using a “Field Width”����������������������������������������������������������������������������������������� 31 2.6 Floating-Point Numbers – float and double�������������������������������������������������������� 33 2.6.1 Print double and float Variables������������������������������������������������������������������������������������������������ 34 2.6.2 Assignment Between double and float������������������������������������������������������������������������������������� 36 2.6.3 Floating-Point Expressions���������������������������������������������������������������������������������������������������������� 36 2.6.4 Expressions with Integer and Floating-Point Values������������������������������������������������������������������� 37 2.6.5 Assigning double/float to int�������������������������������������������������������������������������������������������������� 38 2.7 Strings���������������������������������������������������������������������������������������������������������������������� 38 2.8 The Assignment Statement�������������������������������������������������������������������������������������� 41 2.9 printf��������������������������������������������������������������������������������������������������������������������� 42 viii www.it-ebooks.info ■ Contents ■Chapter ■ 3: Programs with Sequence Logic��������������������������������������������������������� 47 3.1 Introduction�������������������������������������������������������������������������������������������������������������� 47 3.2 Read Data Supplied by a User���������������������������������������������������������������������������������� 47 3.3 scanf����������������������������������������������������������������������������������������������������������������������� 50 3.3.1 Read Data Into a float Variable������������������������������������������������������������������������������������������������� 52   3.3.2 Read Data Into a double Variable����������������������������������������������������������������������������������������������� 52 3.4 Read Strings������������������������������������������������������������������������������������������������������������� 54 3.5 Examples������������������������������������������������������������������������������������������������������������������ 55 3.5.1 Problem - Average�������������������������������������������������������������������������������������������������������������������� 55 3.5.2 Problem - Square��������������������������������������������������������������������������������������������������������������������� 56 3.5.3 Problem - Banking�������������������������������������������������������������������������������������������������������������������� 57 3.5.4 Problem – Tickets��������������������������������������������������������������������������������������������������������������������� 60 ■Chapter ■ 4: Programs with Selection Logic���������������������������������������������������������� 65 4.1 Introduction�������������������������������������������������������������������������������������������������������������� 65 4.2 Boolean Expressions������������������������������������������������������������������������������������������������ 65 4.2.1 AND, &&���������������������������������������������������������������������������������������������������������������������������������������� 66 4.2.2 OR, ||�������������������������������������������������������������������������������������������������������������������������������������������� 67 4.2.3 NOT, !������������������������������������������������������������������������������������������������������������������������������������������� 68 4.3 The if Construct������������������������������������������������������������������������������������������������������ 69 4.3.1 Find the Sum of Two Lengths������������������������������������������������������������������������������������������������������ 72 4.4 The if else Construct��������������������������������������������������������������������������������������� 75 4.4.1 Calculate Pay������������������������������������������������������������������������������������������������������������������������������� 77 4.5 On Program Testing�������������������������������������������������������������������������������������������������� 80 4.6 Symbolic Constants�������������������������������������������������������������������������������������������������� 80 4.6.1 The #define Directive������������������������������������������������������������������������������������������������������������������ 81 4.6.2 Example – Symbolic Constants��������������������������������������������������������������������������������������������������� 82 4.7 More Examples��������������������������������������������������������������������������������������������������������� 83 4.7.1 Print a Letter Grade��������������������������������������������������������������������������������������������������������������������� 83 4.7.2 Classify a Triangle������������������������������������������������������������������������������������������������������������������������ 85 ix www.it-ebooks.info ■ Contents ■Chapter ■ 5: Programs with Repetition Logic��������������������������������������������������������� 91 5.1 Introduction�������������������������������������������������������������������������������������������������������������� 91 5.2 The while Construct������������������������������������������������������������������������������������������������ 91 5.2.1 Highest Common Factor�������������������������������������������������������������������������������������������������������������� 96 5.3 Keep a Count������������������������������������������������������������������������������������������������������������ 97 5.3.1 Find Average�������������������������������������������������������������������������������������������������������������������������������� 99 5.4 Increment and Decrement Operators��������������������������������������������������������������������� 100 5.5 Assignment Operators�������������������������������������������������������������������������������������������� 101 5.6 Find Largest����������������������������������������������������������������������������������������������������������� 102 5.7 Find Smallest��������������������������������������������������������������������������������������������������������� 105 5.8 Read Data from a File��������������������������������������������������������������������������������������������� 106 5.8.1 fscanf�������������������������������������������������������������������������������������������������������������������������������������� 108 5.8.2 Find Average of Numbers in a File��������������������������������������������������������������������������������������������� 108 5.9 Send Output to a File���������������������������������������������������������������������������������������������� 110 5.9.1 fprintf����������������������������������������������������������������������������������������������������������������������������������������� 111 5.10 Payroll������������������������������������������������������������������������������������������������������������������ 112 5.11 The for Construct������������������������������������������������������������������������������������������������ 118 5.11.1 The for Statement in C����������������������������������������������������������������������������������������������������������� 120 5.11.2 A Bit of Aesthetics�������������������������������������������������������������������������������������������������������������������� 125 5.12 Multiplication Tables��������������������������������������������������������������������������������������������� 125 5.13 Temperature Conversion Table����������������������������������������������������������������������������� 129 5.14 Expressive Power of for�������������������������������������������������������������������������������������� 131 5.15 The while Statement�������������������������������������������������������������������������������� 132 5.15.1 Highest Common Factor���������������������������������������������������������������������������������������������������������� 133 5.15.2 Interest at the Bank����������������������������������������������������������������������������������������������������������������� 134 ■Chapter ■ 6: Characters���������������������������������������������������������������������������������������� 141 6.1 Character Sets�������������������������������������������������������������������������������������������������������� 141 6.2 Character Constants and Values���������������������������������������������������������������������������� 142 6.3 The Type char�������������������������������������������������������������������������������������������������������� 143 x www.it-ebooks.info ■ Contents 6.4 Characters in Arithmetic Expressions�������������������������������������������������������������������� 143 6.4.1 Uppercase To/From Lowercase������������������������������������������������������������������������������������������������� 144 6.5 Read and Print Characters������������������������������������������������������������������������������������� 145 6.6 Count Characters���������������������������������������������������������������������������������������������������� 152 6.6.1 Count Characters in a Line�������������������������������������������������������������������������������������������������������� 153 6.7 Count Blanks in a Line of Data������������������������������������������������������������������������������� 153 6.8 Compare Characters����������������������������������������������������������������������������������������������� 155 6.9 Read Characters from a File����������������������������������������������������������������������������������� 156 6.10 Write Characters to a File������������������������������������������������������������������������������������� 157 6.10.1 Echo Input, Number Lines�������������������������������������������������������������������������������������������������������� 157 6.11 Convert Digit Characters to Integer���������������������������������������������������������������������� 161 ■Chapter ■ 7: Functions����������������������������������������������������������������������������������������� 165 7.1 About Functions������������������������������������������������������������������������������������������������������ 165 7.2 skipLines������������������������������������������������������������������������������������������������������������ 166 7.3 A Program with a Function������������������������������������������������������������������������������������� 167 7.3.1 The Function Header������������������������������������������������������������������������������������������������������������������ 168 7.3.2 How a Function Gets Its Data���������������������������������������������������������������������������������������������������� 169 7.4 max������������������������������������������������������������������������������������������������������������������������� 170 7.5 Print the Day����������������������������������������������������������������������������������������������������������� 173 7.6 Highest Common Factor����������������������������������������������������������������������������������������� 175 7.6.1 Using HCF to Find LCM�������������������������������������������������������������������������������������������������������������� 177 7.7 factorial������������������������������������������������������������������������������������������������������������������ 178 7.7.1 Using Factorial��������������������������������������������������������������������������������������������������������������������������� 181 7.7.2 Combinations����������������������������������������������������������������������������������������������������������������������������� 182 7.8 Job Charge������������������������������������������������������������������������������������������������������������� 184 7.9 Calculate Pay���������������������������������������������������������������������������������������������������������� 185 7.10 Sum of Exact Divisors������������������������������������������������������������������������������������������ 186 7.10.1 Classify Numbers��������������������������������������������������������������������������������������������������������������������� 186 xi www.it-ebooks.info Chapter 10 ■ Structures else print invalid vote add to spoiltVotes endif get a vote endwhile After all the votes are processed, this function will need to return the number of valid and spoiled votes But how can a function return more than one value? It can, if the values are stored in a structure and the structure returned as the “value” of the function We will use the following declaration: typedef struct { int valid, spoilt; } VoteCount; And we will write processVotes as follows: VoteCount processVotes(PersonData person[], int max, FILE *in, FILE *out) { VoteCount temp; temp.valid = temp.spoilt = 0;   int v; fscanf(in, "%d", &v); while (v != 0) { if (v < || v > max) { fprintf(out, "Invalid vote: %d\n", v); ++temp.spoilt; } else { ++person[v].numVotes; ++temp.valid; } fscanf(in, "%d", &v); } //end while return temp; } //end processVotes Next, we write main, preceded by the compiler directives and the structure declarations #include #include #define MaxCandidates #define MaxNameLength 30 #define MaxNameBuffer MaxNameLength+1   typedef struct { char name[MaxNameBuffer]; int numVotes; 298 www.it-ebooks.info Chapter 10 ■ Structures } PersonData; PersonData candidate[MaxCandidates];   typedef struct { int valid, spoilt; } VoteCount;   int main() { void initialize(PersonData[], int, FILE *); VoteCount processVotes(PersonData[], int, FILE *, FILE *); void printResults(PersonData[], int, VoteCount, FILE *);   PersonData candidate[MaxCandidates+1]; VoteCount count; FILE *in = fopen("votes.txt", "r"); FILE *out = fopen("results.txt", "w");   initialize(candidate, MaxCandidates, in); count = processVotes(candidate, MaxCandidates, in, out); printResults(candidate, MaxCandidates, count, out); fclose(in); fclose(out); } //end main The declarations of PersonData and VoteCount come before main This is done so that other functions can refer to them, without having to repeat the entire declarations If they were declared in main, then the names PersonData and VoteCount would be known only in main, and other functions would have no access to them Now that we know how to read and process the votes, it remains only to determine the winner(s) and print the results We will delegate this task to the function printResults Using the sample data, the array candidate will contain the values shown below after all the votes have been tallied (remember, we are not using candidate[0]) name Victor Taylor numVotes Denise Duncan 3 Kamal Ramdhan Michael Ali Anisa Sawh 6 Carol Khan Gary Olliverie 299 www.it-ebooks.info Chapter 10 ■ Structures To find the winner, we must first find the largest value in the array To this, we will call a function getLargest as follows: int win = getLargest(candidate, 1, MaxCandidates); This will set win to the subscript of the largest value in the numVotes field from candidate[1] to candidate[7] (since MaxCandidates is 7): In our example, win will be set to since the largest value, 6, is in position (6 is also in position 5, but we just need the largest value, which we can get from either position.) Here is getLargest: int getLargest(PersonData person[], int lo, int hi) { //returns the index of the highest vote from person[lo] to person[hi] int big = lo; for (int h = lo + 1; h person[big].numVotes) big = h; return big; } //end getLargest Now that we know the largest value is in candidate[win].numVotes, we can “step through” the array, looking for those candidates with that value This way, we will find all the candidates, if there is more than one, with the highest vote and declare them as winners An outline of printResults is as follows: printResults print the number of voters, valid votes and spoilt votes print the score of each candidate determine and print the winner(s) The details are given in the function printResults: void printResults(PersonData person[], int max, VoteCount c, FILE*out) { int getLargest(PersonData[], int, int); fprintf(out, "\nNumber of voters: %d\n", c.valid + c.spoilt); fprintf(out, "Number of valid votes: %d\n", c.valid); fprintf(out, "Number of spoilt votes: %d\n", c.spoilt); fprintf(out, "\nCandidate Score\n\n");     for (int h = 1; h [...]... about teaching C We discuss only those features and statements in C that are necessary to achieve our goal Once you learn the principles well, they can be applied to any language Chapter 1 gives an overview of the programming process Chapter 2 describes the basic building blocks needed to write programs Chapter 3 explains how to write programs with the simplest kind of logic—sequence logic Chapter 4... different program: • To play a game, we need a game-playing program • To write a letter or a book, we need a word processing program 1 www.it-ebooks.info Chapter 1 ■ Elementary Programming Concepts • To do accounts, we need an accounting program • To learn Spanish, we need a program that teaches Spanish • To listen to a CD, we need a music-playing program • To send a fax, we need a fax-sending program • To. .. 9 • special character – any symbol except a letter or a digit e.g +, 0) b = a + 2; else b = a – 2; And we put statements together to form programs 1.6 Welcome to C Programming We take a quick peek at the C programming language by writing a program to print the message Welcome to Trinidad & Tobago... written in machine language only For the computer to execute the instructions of such a program, those instructions must be loaded into the computer’s memory (also called primary storage), like this: memory instruction 1 instruction 2 instruction 3 etc 9 www.it-ebooks.info Chapter 1 ■ Elementary Programming Concepts You can think of memory as a series of storage locations, numbered consecutively starting

Ngày đăng: 10/08/2016, 15:12

Từ khóa liên quan

Mục lục

  • Contents at a Glance

  • Contents

  • About the Author

  • About the Technical Reviewer

  • Acknowledgements

  • Preface

  • Chapter 1: Elementary Programming Concepts

    • 1.1 Programs, Languages, and Compilers

    • 1.2 How a Computer Solves a Problem

      • 1.2.1 Define the Problem

      • 1.2.2 Analyze the Problem

      • 1.2.3 Develop an Algorithm to Solve the Problem

        • 1.2.3.1 Data and Variables

        • 1.2.3.2 Example—Develop the Algorithm

        • 1.2.4 Write the Program for the Algorithm

        • 1.2.5 Test and Debug the Program

        • 1.2.6 Document the Program

        • 1.2.7 Maintain the Program

        • 1.3 How a Computer Executes a Program

        • 1.4 Data Types

        • 1.5 Characters

        • 1.6 Welcome to C Programming

          • 1.6.1 Run the Program

          • 1.6.2 A Word on Program Layout

Tài liệu cùng người dùng

Tài liệu liên quan