But today, C is also used to write all kinds of application programs: word processing programs, spreadsheet programs, database management programs, accounting programs, games, educational software: the list is endless. And Chapter 10 is about structures: the collection of one or more items, possibly of different types, grouped under a single name for ease of use.
Programs, Languages, and Compilers
First of all, we need to know that computers are built to execute instructions written in so-called machine language. Each computer has its own machine language and the computer can only execute instructions written in that language.
How a Computer Solves a Problem
- Define the Problem
- Analyze the Problem
- Develop an Algorithm to Solve the Problem
- Write the Program for the Algorithm
- Test and Debug the Program
- Document the Program
- Maintain the Program
In this example, the input to the program is the length of one side of the square and the output is the area of the square. These are some of the items that make up the technical documentation of the program.
How a Computer Executes a Program
This allows a non-technical person to use the program without knowing the inner workings of the program. Among other things, the user must know how to load the program on the computer and how to use the various functions of the program.
Data Types
It is possible for one instruction to tell you to skip multiple instructions to a specific one and continue execution from there. For example, trying to store a string constant in an integer variable would be an error.
Characters
When we use a variable in a program, we must say what type of data (the kind of constants) we intend to store in that variable—we say we must declare the variable.
Welcome to C Programming
Run the Program
The file might be called Welcome.c; it is good practice to use .c as the filename extension for those files that contain C source code. Once the file is open, there will usually be a menu command to compile or run the program.
A Word on Program Layout
Write Output with printf
The Newline Character, \n (backslash n)
The first \n says to terminate the current output line; subsequent output starts at the left margin of the next line. is printed on a new line. The first \n ends the first line; the second ends the second line and essentially prints a blank line.
Escape Sequences
Print the Value of a Variable
We'll explain the printf and format specifications in more detail in Chapter 2, but for now, note that we use the %d specification if we want to print an integer value.
Comments
If you remove all the comments from a program, it will run exactly the same as with the comments.
Programming with Variables
It is sometimes pronounced "a becomes 14." In C, an assignment statement consists of a variable (a in the example), followed by an equal sign (=), followed by the value to be assigned to the variable (14 in the example), followed by a semicolon. In the same vein, a good programmer must be able to creatively use the features of the language to solve a wide variety of problems in an elegant and efficient way.
The C Alphabet
When you try to compile the program, the compiler will notify you of an error. It is like saying that one becomes a novelist if one learns a few rules of English grammar and knows how to write a few properly formed sentences.
C Tokens
- Spacing Within a Program
- Reserved Words
- Identifiers
- Some Naming Conventions
A keyword has a special meaning in the context of a C program and can only be used for that purpose. A symbolic (or named) constant is an identifier that can be used in place of a constant such as 100.
Basic Data Types
Apart from the rules for creating identifiers, C imposes no restrictions on the names that should be used or what format (such as upper or lower case) should be used. It is recommended that you use combinations of upper and lower case letters to indicate the type of element that the identifier calls.
Integer Numbers - int
- Declaring Variables
- Integer Expressions
- Precedence of Operators
- Print an Integer Using a “Field Width”
For example, to print an integer value left justified at a field width of 5, we use -5d. Printing n requires two printing columns (one for - and one for 7); since the field width is 5, it is printed with 3 leading spaces, so: ◊◊◊-7.
Floating-Point Numbers – float and double
- Print double and float Variables
- Assignment Between double and float
- Floating-Point Expressions
- Expressions with Integer and Floating-Point Values
- Assigning double/float to int
The value of d will be printed to a predefined number of decimal places (usually six, but may vary from one compiler to another). If n is greater than or equal to w (field width is equal to or less), the value is printed using n columns to print.
Strings
The value of a string constant is the sequence of characters without beginning and ending quotes. The result is that the name will now bear AliceWonderland; the last value does not change.
The Assignment Statement
The first sentence assigns 12 a; the second assigns 5 b; the third adds 14 c; no problem so far.
Write a statement that prints the value of the int variable sum, right justified in a field width of 6. Write a statement that prints the value of the double variable total to 3 decimal places, right justified in a field width of 9.
Introduction
Read Data Supplied by a User
If we want to add two other numbers, we will have to change the numbers 14 and 25 in the program to the ones required. And every time we want to add two different numbers, we will have to change the program.
Read Data Into a f loat Variable
In the latter case there must be no spaces, for example between the 5 and the E or between the E and the + or between the + and the 1.
Read Data Into a double Variable
When scanf receives a number, it remains placed immediately after the number; a subsequent scanf will continue to read data from that point. This scan will stop at the character after 8; this can be a space or the last character.
Read Strings
It is helpful to imagine a "data pointer" that moves through the data as the data items are read. At each time, it marks the position in the data from which the next scanf will start looking for the next data item.
Examples
- Problem 1 - Average
- Problem 2 - Square
- Problem 3 - Banking
- Problem 4 – Tickets
If integers are not entered in the data, the program will crash or, at best, give incorrect results. For each of the following, give examples of data that will be read correctly and examples of data that will cause the program to crash. accept the declaration int i, j; double x, y;);.
Boolean Expressions
AND, &&
For example, suppose we want to know whether the value of h is between 1 and 99 inclusive. We want to know if h is greater than or equal to 1 AND if h is less than or equal to 99.
OR, ||
NOT, !
However, in this book we will use the traditional approach mainly because many popular C compilers do not yet support the C99 standard. If we ever need a "Boolean" variable, we can use an int variable with 1 representing true and 0 representing false.
The if Construct
Find the Sum of Two Lengths
Write a program to ask for two lengths and print their sum so that the centimeter value is less than 100. Program P4.2 solves the problem as described. find the sum of two lengths in meters and cm.
The if...else Construct
Calculate Pay
If hours worked are less than or equal to 40, the regular wage is calculated by multiplying the hours worked by the rate of pay and the overtime pay is 0. If the hours worked are greater than 40, the regular pay is calculated by multiplying 40 by the rate of pay and Overtime pay is calculated by multiplying the number of hours in excess of 40 with the wage rate by 1.5.
On Program Testing
Symbolic Constants
The #define Directive
It is up to the programmer to ensure that the resulting statement makes sense when the identifier is replaced. In practice, the directives say that the identifier ChargePerHour corresponds to the constant 100 and the identifier MinJobCost corresponds to 150.
Example – Symbolic Constants
The numbers 40 and 1.5 used in Program P4.5 are referred to as magic numbers - they appear in the program for no apparent reason, as if by magic. Using symbolic constants can help make our programs more flexible and easier to maintain.
More Examples
Print a Letter Grade
To ensure that the program is correct, you should run it with at least 3 different characters (eg to check that each of the 3 characters is printed correctly. As an exercise, modify the program to print the correct character based on the following:.
Classify a Triangle
Here the if checks whether one side is greater than or equal to the sum of the other two. It is rectangular if the sum of the squares of two sides is equal to the square of the third side.
Introduction
The while Construct
Highest Common Factor
Let's write a program to find the highest common factor, HCF (also called greatest common divisor, GCD), of two numbers. In general, if m is less than n, the first thing the algorithm does is swap their values.
Keep a Count
Find Average
As explained in Section 2.5.4, note the use of the throw (double) to force a floating point calculation. If the user enters 0 as the first number, execution will reach the last printf statement with sum and n both having the value 0.
Increment and Decrement Operators
Assignment Operators
Find Largest
This is to ensure that the while condition makes sense (is defined) the first time. When the while condition is false (number is 0), the program continues with the print statement after the loop.
Find Smallest
Read Data from a File
To read data from a file, we use the fscanf statement (more precisely, the function). Note that the first argument is a file pointer, not a file name.
Find Average of Numbers in a File
This statement unlinks the file pointer to the input.txt file. FILE * and fopen are used to make the fscanf statement retrieve data from the input.txt file.
Send Output to a File
We use the statement (more precisely, the function) fprintf to send output to file. This statement breaks the file pointer link to the output.txt file.
Payroll
For this reason, we will use separate variables for first name (first name) and last name (last name). Because of the way %s works, we'll need to read nouns and adjectives separately.
The for Construct
The for Statement in C
In this case, however, note that the scope of h only extends to the body of for (see next). Caution The ability to declare the loop variable in the for clause was not allowed in early versions of C.
A Bit of Aesthetics
Multiplication Tables
And we should keep changing the program for every table we want. We need to let the user tell the program what type of table and what range they want.
Temperature Conversion Table
To take care of this possibility, we can allow the program to validate the start and end values to ensure that the "From" value is less than or equal to the "To" value. Furthermore, it is better to print a message informing the user of an error than to have the program do nothing.
Expressive Power of for
Here,
The do...while Statement
Highest Common Factor
Now we rewrite the program using do..while to ensure that the two numbers entered are indeed positive integers. At the output of do..while, the value of n is 0 and the value of m is HCF.
Interest at the Bank
Under the appropriate heading, print the gross salary, tax withheld, net salary, and the percentage of gross salary that was paid as tax. Due to inflation, the price of an item is expected to increase by r% each year.
Character Constants and Values
The ASCII codes run from 0 to 127 (the range of numbers that can be stored with 7 bits). In this book, we will, as much as possible, write our programs and make no assumptions about the underlying character set.
The Type char
We can print the character value using the specification %c in printf, and we can print the integer value using %d.
Characters in Arithmetic Expressions
Uppercase To/From Lowercase
Suppose ch contains an uppercase letter and we want to convert it to the corresponding lowercase letter. Of course, this assumes that ch contains an uppercase letter, and the case difference is the same for all letters.
Read and Print Characters
If we want to read and print the first three characters, we can do it with Program P6.2. If we want to read and print the first 20 characters, we only need to change 3 to 20 in the for statement.
Count Characters
Count Characters in a Line
Program P6.6 reads a line of input and counts the number of characters in it, without counting it. The main difference between this and Program P6.5 is that this one reads characters to the end of the line rather than the first non-blank.
Count Blanks in a Line of Data
Therefore, control returns to the top of the while loop, where another character is read and \n is tested.
Compare Characters
Read Characters from a File
The program reads one character at a time from the file and prints it to the screen using putchar. On exiting the while loop, it uses putchar('\n') to break the line on the screen.
Write Characters to a File
Echo Input, Number Lines
If we have a character to print and writeLineNo is 1, the line number is printed and writeLineNo is set to 0. If it turns out that there is a character to print on the next line, the line number will be printed first since writeLineNo is 1.
Convert Digit Characters to Integer
The program will have to read characters until it finds a digit, the first of the integer. Write a program that queries a line of data and prints the first digit on the line.
This location is passed to the function where it is labeled with the parameter name, n. When the function terminates, the location containing the argument is discarded and control is returned to main in the statement after skipLines(3).
A Program with a Function
The Function Header
How a Function Gets Its Data
If, when a function is called, the argument type is not the same as the corresponding parameter, C attempts to convert the argument to the required type. If it is not possible to convert the argument to the required type, you will get a 'type mismatch' error as shown in the call.
These locations are passed to the function max where 24 is labeled with a, the first parameter; and 33 is labeled with b, the second parameter. The if statement is executed; since a (24) is not greater than b (33), control will return to the statement b; and 33 is returned as the value of the function.
Print the Day
This prompts the user for a number and the program then prints the name of the day by calling the printDay function. This location is passed to the printDay function, where it is labeled with the name of the parameter, d.
Highest Common Factor
Using HCF to Find LCM
If we know the HCF of the two numbers, we can find the LCM by multiplying the numbers and dividing by their HCF. Since the HCF of 8 and 6 is 2, we can find their LCM by working out.
Using Factorial
This doesn't happen here, but if the factorial were to change the value of n, the changed value would be at location 472; the value at location 865 would not be affected. When in a factorial, h refers to a local variable; when in main, h refers to the h declared in main.
Combinations
The factorial is calculated and returned to the place in printf from where it was called. When in the factorial, n refers to location 472; when in main, n refers to location 865; factorial does not have any access to the 865 location.
Job Charge
When we say that a function is given certain data, it immediately implies that such data must be defined as parameters of the function. Also, we must specify the return type of the function; it is double since the job cost is a double value.
Calculate Pay
Here the parameter list indicates what data will be given to the function when it is called. As an exercise, write a complete program to read several values for labor hours and part cost, and for each pair print the cost of the job.
Sum of Exact Divisors
Classify Numbers
Some Character Functions
Position of a Letter in the Alphabet
Fetch the Next Integer
Array Declaration
Store Values in an Array
About Not Using Element 0
Average and Differences from Average
Letter Frequency Count
Making Better Use of fopen
Array as Argument to a Function
String – Array of Characters
Reverse the Characters in a String
Palindrome
A Better Palindrome Function
Array of Strings – Name of Day Revisited
A Flexible getString Function
A Geography Quiz Program
Find the Largest Number
Find the Smallest Number
A Voting Problem
Selection Sort
Analysis of Selection Sort
Insertion Sort
Analysis of Insertion Sort
Insert an Element in Place
Sort an Array of Strings
Variable-Length Arrays
Sort Parallel Arrays
Binary Search
Word Frequency Count
Merge Sorted Lists
Implement the Merge
How to Declare a Structure
Array of Structure
Search an Array of Structure
Sort an Array of Structure
Read, Search, and Sort a Structure
Nested Structures
Work with Fractions
Manipulate Fractions
A Voting Problem
Pass Structures to Functions