C for dummies free download pdf






















The resulting machine-executable files carry the extension. Keep going. How do I program? To write a program, you need two specialized computer programs. One an editor is what you use to write your code as you build your. CPP source file. The other a compiler converts your source file into a machine-executable. EXE file that carries out your real-world commands open spreadsheet, make rude noise, deflect incoming asteroid, whatever.

Nowadays, tool developers generally combine compiler and editor into a single package — a development environment. We use one of them in this book — the Dev-CPP environment. You can download quite a range of public-domain programs from the Internet.

See the Web site for details. You can check out my Web site at www. They are two separate things and for the sake of sanity should remain so in your mind. NET which are essentially the same thing. NET are different and often just as difficult to decipher , but the territory will seem mysteriously familiar. Navigate to and double-click the file devcpp Note that 4. Starting an installation with a threat is an inauspicious way to begin a relationship, but everything gets better from here.

NET, for example. It is possible, but difficult, to undo this association. NET installed. NET coexist peacefully on the same machine, but what Visual Studio has done, let no man cast assunder.

You can still open your. Personally, I prefer to use this option, even with Visual Studio. Click the Next button. Make sure you have enough room for the program, wherever you decide to put it. Click Install. At first, nothing seems to happen. Figure displays the eventual result. Choose whether you want to install for all users, and then click the Close button to complete installation of the package.

But you knew that. Read on. You can change these settings at any time, but now is as good as any. Choose the Settings tab. Choose Code Generation from the menu on the left. Make sure that the Enable Exception Handling is enabled, as shown in Figure Choose Linker and make sure the Generate Debugging Information option is enabled. Figure shows you what to look for.

Figure The Generate Debugging Information option must be enabled. Choose OK. Installation is now complete! Your options are saved automatically. This is a lot of clicking. My personal preference is to create a shortcut on the desktop.

To create a shortcut, double-click My Computer. Now double-click the Local Disk C:. Finally, double-click Dev-CPP — whew! Right-click the file devcpp. Drag the Shortcut to devcpp. Enter the following program exactly as written. You can cheat and copy the Conversion. Choose Save As under the File menu. Then type in the program name and press Enter. Within this, I created Chap Finally, I saved the program with the name Conversion. To build your Conversion.

Nothing will happen at first sshh. If all goes well, a window like that shown in Figure appears. Figure Bad little programs generate error messages in the Compiler window.

Guess pletely unrelated error. Had the compiler simply which one I vote for? There was once a language that tried to fix simple mistakes like this for you. From my personal experience, I can tell you it was a waste of time — because except for very simple cases the compiler was almost always wrong.

At least it warned me of the problem so I could fix it myself. EXE program file and give it input to see how well it works. I have no idea how they selected function keys. A window opens immediately, requesting a temperature in Celsius.

Enter a known temperature, such as degrees. After you press Enter, the program returns with the equivalent temperature of degrees Fahrenheit as follows: Enter the temperature in Celsius Fahrenheit value is Press any key to continue. Windows programs show the user a very visually oriented output, all nicely arranged in onscreen windows. Click a topic of interest to display help. You really need to get behind the wheel itself.

Programs are a bit like cars as well. All cars are basically the same with small differences and additions — OK, French cars are a lot different than other cars, but the point is still valid. Cars follow the same basic pattern — steering wheel in front of you, seat below you, roof above you and stuff like that. This pattern is already present in this very first program. We can review the Conversion program by looking for the elements that are common to all programs.

I have copied this code into a file called Template. Clarifying source code with comments The first few lines in Conversion. These first six lines are known as comments. The compiler ignores comments. You can put any character you want in a comment. Some printers still default to 80 characters across when printing text. A newline was known as a carriage return back in the days of typewriters — when the act of entering characters into a machine was called typing and not keyboarding.

A newline is the character that terminates a command line. Later in this book, I describe the one case in which this type of comment is applied. In fact, the programmer herself may forget what her program meant if she looks at it months after writing the original code and has left no clue.

A statement is a single set of commands. All statements other than comments end with a semicolon. Why nobody asked me about that remains a mystery. As you look through the program, you can see that spaces, tabs, and newlines appear throughout the program. You may add white space anywhere you like in your program to enhance readability — except in the middle of a word: See wha t I mean?

The variable fullspeed and the variable FullSpeed have nothing to do with each other. Writing declarations The line int nCelsius; is a declaration statement.

A variable contains a value, such as a number or a character. In this case, the value of x is 10, but we could have just as well set the value of x to 20 or 30 or —1. The variable defined on Line 11 is called celsius and declared to hold an integer. A variable must begin with the letters A through Z or a through z. Variable names can be as long as you want to make them.

Each new word within a variable begins with a capital letter, as in myVariable. Try to make variable names short but descriptive. Avoid names such as x because x has no particular meaning. A variable name such as lengthOfLine Segment is much more descriptive. The next line is exactly the opposite. For the remainder of the program, the value of celsius is whatever the user enters there. Calculating Expressions All but the most basic programs perform calculations of one type or another.

Said another way, an expression is a statement that has a value. An operator is a command that generates a value. The term equals is one of those ambiguities. Examining the remainder of Conversion. The value contained in the variable called factor calculated immediately prior, by the way is multiplied by the value contained in celsius which was input from the keyboard. The result is divided by and summed with The result of the total expression is assigned to the integer variable fahrenheit.

You can store things in the box for later use, particularly numbers. The concept of a variable is borrowed from mathematics. That is, the value of x is 1. A mathematician might for example write down something like the following: www.

You can declare variables almost anywhere you want in your program — as long as you declare the variable before you use it. Some storage bins are so small that they can only handle a single number. It takes a larger bin to handle a sentence. Of course, no bin is large enough to hold Texas maybe Rhode Island or Delaware. In addition, different types of variables have different properties. So far, you have only seen the int type of variable in this chapter: www.

Integers are also known as counting numbers or whole numbers. Integers are great for most calculations. You can make it up through most if not all of elementary school with integers. Integer round-off Consider the problem of calculating the average of three numbers. Given the values 1, 2, and 2, the sum is 5. The result of the division is also an integer. The resulting value of nAverage is unreasonable but logical: 1.

To see how this can occur, consider that 13 truncates to 0, 23 truncates to 0, and 23 truncates to 0. The sum of 0, 0, and 0 is zero. Limited range A second problem with the int variable type is its limited range. A normal int variable can store a maximum value of 2,,, and a minimum value of —2,,, — roughly from positive 2 billion to negative 2 billion, for a total range of about 4 billion.

Two billion is a very large number: plenty big enough for most uses. In fact, your computer probably executes faster than 2 gigahertz, depending upon how old your computer is. Giga is the prefix meaning billion. An unsigned int value type can represent a number from 0 to 4,,,, should the need arise for some unimaginable reason.

You can declare a variable simply unsigned. The int is implied. Solving the truncation problem The limitations of int variables can be unacceptable in some applications. A decimal number can have a nonzero fractional part. Mathematicians also call those real numbers. Decimal numbers avoid many of the limitations of int type integers. The equivalent integer is written simply as 1. Decimals numbers can also be negative, like —2. Floating- point variables are declared in the same way as int variables: double dValue1; From this point forward, the variable dValue1 is declared to be a double.

Once declared, you cannot change the type of a variable. This is not necessarily the case. Looking at the limits of floating-point numbers Although floating-point variables can solve many calculation problems such as truncation, they have some limitations themselves — in effect, the reverse of those associated with integer variables. But what about 0. Should these also be considered as 1? Calculation speed Historically, a computer processor can process integer arithmetic quicker than it can floating-point arithmetic.

Calculation speed is becoming less of a problem as microprocessors increase their capabilities. Loss of accuracy Floating-point variables cannot solve all computational problems. Floating- point variables have a limited precision of about 6 digits — an extra-economy size, double-strength version of float can handle some 15 significant digits with room left over for lunch.

To evaluate the problem, consider that 13 is expressed as 0. The concept of an infinite series makes sense in math, but not to a computer. The computer has a finite accuracy.

Average 1, 2, and 2 for example , and you get 1. The maximum value of a double variable is roughly 10 to the 38th power. Only the first 13 digits or so have any meaning; the remaining 25 digits suffer from floating-point round-off error.

Fortunately ta-dah! This smaller version takes less memory than a double but has less accuracy and a smaller range. Not suitable for arithmetic. Logically false. In days gone by, memory was an expensive asset — you could reap significant space savings by using a float variable. This is no longer the case. That, combined with the fact that modern processors perform double precision calculations at the same speed as float, makes the double the default.

Bigger is better, after all. Types of constants A constant is an explicit number or character such as 1, 0. As with variables, every constant has a type. The analogy is as follows: 1 represents a single ball in the bed of a pickup truck, whereas 1L is a single ball in the bed of a dump truck. The ball is the same, but the capacity of its container is much larger. Following the int to long comparison, 1. Notice, however, that the default for floating-point constants is double. Thus, 1.

You can also store a set of non-printable characters that is used as character constants. See Table for a description of these important non- printable characters. The type bool comes from Boolean, the last name of the inventor of the logical calculus.

There are two values for a boolean variable: true and false. There are actually calculations that result in the value bool. That is, you are allowed to add an integer with a double precision floating-point value. Mixed-mode expressions generate a value whose type is equal to the more capable of the two operands.

Converting a larger value type into a smaller value type is called demotion, whereas converting values in the opposite direction is known as promotion. Thus, you can seems to have nothing to do with the name. Programs have to be able to perform these operations in order to get anything done. If you can say var1 op var2, op must be a binary operator. The most common binary operators are the simple operations you performed in grade school.

The binary operators are flagged in Table You may not have encountered modulus in your studies. For example, 4 goes into 15 three times with a remainder of 3. I discuss round-off errors in Chapter 2. Every expression has a type such as int, double, char, and so on.

A statement involving any mathematical operator is an expression since all these operators return a value. Remember that constants without decimal points are ints.

Expressions can be complex or extremely simple. In fact, the statement 1 is an expression because it has a value 1 and a type int. Determining the Order of Operations All operators perform some defined function. In addition, every operator has a precedence — a specified place in the order in which the expressions are evaluated.

The precedence of the operators determines who goes first. Table shows that multiplication has higher precedence than addition, so the result is 7. The concept of precedence is also present in arithmetic. So what happens when we use two operators of the same precedence in the same expression? When operators of the same precedence appear in the same expression, they are evaluated from left to right the same rule applied in arithmetic.

Thus, the answer is 8 divided by 4, which is 2 divided by 2 which is 1. But what if the programmer wanted to divide x by plus 32? The programmer can change the precedence by bundling expressions together in parentheses shades of algebra! Multiplication and division have higher precedence than addition and subtraction. In summary: Precedence refers to the order in which operators are evaluated.

An operator with higher precedence is executed first. You can override the precedence of an operator by using parentheses. Performing Unary Operations Arithmetic binary operators — those operators that take two arguments — are familiar to a lot of us from school days.

But consider the unary operators, which take a single argument for example, —a. Many unary operations are not so well known. The minus operator changes the sign of its argument. Positive numbers become negative and vice versa. The plus operator does not change the sign of its argument.

Consider, for example, the increment operator the decrement works in exactly the same way. Suppose that the variable n has the value 5. Why define a separate increment operator? This operator puts the value of the right-hand argument into the left argument. However, as odd as they might look, sometimes they can actually make the resulting program easier to read.

This chapter describes these types of expressions. There is a whole other class of operators known as the logical operators. Logical operators fall into two types. Why Mess with Logical Operations? The temperature-conversion program laid out in Chapter 1 is about as complex you can get without some type of decision-making.

By the same token, that same property makes a computer look really stupid when the program makes the wrong decision.

Using the Simple Logical Operators The simple logical operators, shown in Table , evaluate to true or false. NOT; true if its argument is false The first six entries in Table are comparison operators. The following expression logical comparison is true: www. You may think that n1 is greater than or less than n2; however, this ignores the possibility that n1 and n2 are equal.

Store the results of this comparison in the variable b. The equality operator is executed before the assignment. Better look at that again. Note the difference between the operators. The next section explains why this is necessary. The program inputs two values from the keyboard and displays the result of the equality comparison: Input value 1: 5 Input value 2: 5 The statement, 5 equals 5 is true Press any key to continue.

A value of 0 was considered false and all other values true. By the same token, a logical operator generated a 0 for false and a 1 for true. You get completely different output from the BitTest program if you remove the line cout. Variables of type int and bool can be mixed in expressions as well. Other compilers may not be as forgiving.

Be careful performing logical operations on floating-point variables Real numbers are those numbers that can have a fractional part. Because of this, real numbers cannot be counting numbers. That is, you can say the first 1st , second 2nd , third, fourth, and so on because the relationship of 1, 2, and 3 are known exactly. It does not make sense to speak of the 4.

This brings to mind the number between the fourth and fifth, but it has no real meaning. Use Python to create and run your first application Find out how to troubleshoot and fix errors Learn to work with Anaconda and use Magic Functions Benefit from completely updated and revised information since the last edition If you've never used Python or are new to programming in general, Beginning Programming with Python For Dummies is a helpful resource that will set you up for success.

A quick and easy reference to get the most out of your Android tablet It's not a computer and it's not a smartphone—so what in the world is it? Whether you're new to Android or new to tablets altogether, you're about to experience mobile computing like never before with this fun, full-color guide! In Android Tablets For Dummies, you'll find clear, easy-to-follow explanations for making sense of all the features native to Android tablets, as well as model-specific guidance.

Inside, trusted tech guru Dan Gookin—who wrote the very first For Dummies book in —walks you through setting up your Android tablet, navigating the interface, browsing the web, setting up email, finding the best apps, and so much more.

No matter which Android tablet tickles your fancy, this hands-on guide takes the intimidation out of the technology and gives you everything you need to make the most of your new device. Set up your tablet, configure the Home screen, and get connected Surf the web, send and receive email and texts, and use video chat and social media to keep in touch with family and friends Have fun with photos, videos, games, eBooks, music, and movies Get up and running with the Nougat Operating System If you're eager to learn the ins and outs of your Android device—but don't want to pull your hair out in the process—this one-stop guide has you covered.

Skip to content. PDF eBooks. C For Dummies. C For Dummies Book Review:. C Programming For Dummies. Beginning Programming with C For Dummies. C For Dummies Volume 1. Author : Stephen R. C All in One For Dummies. Python All in One For Dummies.

Author : John C. Objective C For Dummies. C 7 0 All in One For Dummies. Introduction to C Programming. Introduction to C Programming Book Review:. Day Trading For Dummies. Author : Ann C. Coding All in One For Dummies. Scrum For Dummies. Author : Mark C. Scrum For Dummies Book Review:.

Bigger is better, after all. Types of constants A constant is an explicit number or character such as 1, 0. As with variables, every constant has a type.

The analogy is as follows: 1 represents a single ball in the bed of a pickup truck, whereas 1L is a single ball in the bed of a dump truck. The ball is the same, but the capacity of its container is much larger. Following the int to long comparison, 1. Notice, however, that the default for floating-point constants is double.

Thus, 1. You can also store a set of non-printable characters that is used as character constants. See Table for a description of these important nonprintable characters.

The type bool comes from Boolean, the last name of the inventor of the logical calculus. There are two values for a boolean variable: true and false. There are actually calculations that result in the value bool. That is, you are allowed to add an integer with a double precision floating-point value. Mixed-mode expressions generate a value whose type is equal to the more capable of the two operands.

Converting a larger value type into a smaller value type is called demotion, whereas converting values in the opposite direction is known as promotion. You can immediately recognize dVariable as a variable of type double by using this convention. Character Type n int l long f float d double c character sz string These leading characters help the programmer keep track of the variable type. Mixed-mode expressions are not a good idea.

Programs have to be able to perform these operations in order to get anything done. If you can say var1 op var2, op must be a binary operator. The most common binary operators are the simple operations you performed in grade school. The binary operators are flagged in Table You may not have encountered modulus in your studies. For example, 4 goes into 15 three times with a remainder of 3.

I discuss round-off errors in Chapter 2. Every expression has a type such as int, double, char, and so on. A statement involving any mathematical operator is an expression since all these operators return a value. Remember that constants without decimal points are ints. Expressions can be complex or extremely simple. In fact, the statement 1 is an expression because it has a value 1 and a type int. Determining the Order of Operations All operators perform some defined function.

In addition, every operator has a precedence — a specified place in the order in which the expressions are evaluated. The precedence of the operators determines who goes first. Table shows that multiplication has higher precedence than addition, so the result is 7. The concept of precedence is also present in arithmetic. So what happens when we use two operators of the same precedence in the same expression?

When operators of the same precedence appear in the same expression, they are evaluated from left to right the same rule applied in arithmetic. Thus, the answer is 8 divided by 4, which is 2 divided by 2 which is 1. But what if the programmer wanted to divide x by plus 32? The programmer can change the precedence by bundling expressions together in parentheses shades of algebra! Multiplication and division have higher precedence than addition and subtraction.

In summary: Precedence refers to the order in which operators are evaluated. An operator with higher precedence is executed first. You can override the precedence of an operator by using parentheses. Performing Unary Operations Arithmetic binary operators — those operators that take two arguments — are familiar to a lot of us from school days. But consider the unary operators, which take a single argument for example, —a. Many unary operations are not so well known.

The minus operator changes the sign of its argument. Positive numbers become negative and vice versa. The plus operator does not change the sign of its argument. Consider, for example, the increment operator the decrement works in exactly the same way.

Suppose that the variable n has the value 5. Why define a separate increment operator? To provide some convenience, a special add 1 instruction was added to the language. Chapter 3: Performing Mathematical Operations Using Assignment Operators An assignment operator is a binary operator that changes the value of its left argument.

This operator puts the value of the right-hand argument into the left argument. However, as odd as they might look, sometimes they can actually make the resulting program easier to read. This chapter describes these types of expressions. There is a whole other class of operators known as the logical operators.

Logical operators fall into two types. Why Mess with Logical Operations? The temperature-conversion program laid out in Chapter 1 is about as complex you can get without some type of decision-making.

By the same token, that same property makes a computer look really stupid when the program makes the wrong decision. Using the Simple Logical Operators The simple logical operators, shown in Table , evaluate to true or false. NOT; true if its argument is false The first six entries in Table are comparison operators. C For Dummies. Read more. Objective-c for dummies. Objective-C For Dummies. C Timesaving Techniques for Dummies.

C For Dummies, 2nd Edition. Evolution For Dummies For Dummies. Europe For Dummies Dummies Travel. Australia For Dummies Dummies Travel. Recommend Documents. Search GetPedia Works! Welcome To GetPedia. According to what the compiler knows, you need only one or the other, not both. Who knows! Why a line by itself? Because no matter what, puts always tacks on that pesky newline character.

You cannot blend a variable into another string of text by using the puts function. C program in your editor. Name some jerk you know: David Yeah, I think David is a jerk, too. But the program works the way it was intended. For one, puts automatically sticks a newline on the end of a string it displays. Second, puts can display only one string variable at a time, all by itself, on its own line.

And, last, the next bit of code shows the program the way it should be written by using only puts and gets.

Then you must stick something in the variable, which you can do by using the scanf or gets function. The output is weird. See Chapter 8 for the lowdown on variables.

P rogramming a computer involves more than just splattering text on a screen. In fact, when you ask most folks, they assume that programming is some branch of mathematics or engineering. After all, computers have their roots in the calculators and adding machines of years gone by. And, early computers were heavily involved with math, from computing missile trajectories to landing men on the moon.

I have to admit: Programming a computer does involve math. Unlike those sweaty days in the back of eighth-grade math class, with beady-eyed Mr. Perdomo glowering at you like a fat hawk eyeing a mouse, you merely have to jot down the problem. The computer solves it for you. Yes, computers have something to do with math. You add, subtract, divide, multiply, and maybe do a few other things. Nothing gets beyond the skills of anyone who can handle a calculator.

In this chapter, I try to make it as enjoyable as possible for you. The Ever-Changing Variable A variable is a storage place. The C compiler creates the storage place and sets aside room for you to store strings of text or values — depending on the type of storage place you create.

Could be anything. The contents can change too — just like the psychic prediction or campaign promise. The number of points PacMan racks up are stored in a variable. And, when you win the game, you enter your name, and that too is stored in a variable. It depends. Variables are defined as being able to store strings of text or numbers.

Variables can change. Strings change The following program is brought to you by the keyword char and by the printf and gets functions. What else do you have in mind? C into your text editor. If you get any errors, reedit your source code. Check for missing semicolons, misplaced commas, and so on. Running the program is covered in the next section.

C in the preceding section, run the final program. The output looks something like this: What would you like to name your cat?

Rufus Rufus is a nice name. Fuzzball Fuzzball is nice, too. The kitty variable is assigned one value by using the first gets function. Though the same variable is used, its value changes. That is the idea behind variables.

C program, the variable is named kitty. Welcome to the Cold World of Numeric Variables Just as strings of text are stored in string variables, numbers are stored in numeric variables. This allows you to work with values in your program and to do the ever-dreaded math.

Unlike char, which creates all types of strings, different keywords are used to create variables for storing different types of numbers. It all depends on how big or how weird the number is. Hello, integer To keep things sane for now, I show you only one of the numeric variable types. Any other values — larger or smaller, fractions, or values with a decimal point, such as 1.

To use an integer variable in a program, you have to set aside space for it. You do this with the int keyword at the beginning of the program. For now, forgive me for the unofficial introduction. This type of int is the same one used to declare the main function in every program you have written in this book — if you have been reading the chapters in order.

Yeah, this information is completely optional; no need cluttering your head with it. Using an integer variable in the Methuselah program If you need only small, whole-number values in a C program, you should use integer variables. If you get any errors, reedit the source code and make sure that everything matches the preceding listing.

Run the program and you see the following: Methuselah was years old. The variable age was assigned the value The variable age comes first, and then the equal sign, and then the value to be placed in the age variable. So shoot me.

What could value be? Anything that pops out a value — an integer value, in this case — is acceptable. Strings can be read into variables from the keyboard by using the scanf , gets , or other C language keyboard-reading functions. String variables can also be preset, but you cannot use an equal sign with them, like you can with numeric variables!

What does it really do? Who knows what wacky value the user may enter? One is a value, and the other is a string. I leave it up to you to figure out which is which. The secret command to do it is atoi, the A-to-I function. A numeric value is what translate it into a value, suitable for storage in a you find lurking in a numeric variable. This book numeric variable. There are numbers and there are values. Which A value is 5 apples, 3. Those are values. Those are the characters 2, 5, and one enters a dollar amount, percentage, size, 5, as found on your keyboard.

I call it a number. The atoi function follows the equal sign. Most often, the string to convert is the name of a string variable, one created by the char keyword and read from the keyboard by using gets or scanf or some other keyboard- reading function.

The line does not end with a semicolon. So how old is this Methuselah guy, anyway? In this version of the program, you read a string that the user types at the keyboard. That string — and it is a string, by the way — is then magically converted into a numeric value by the atoi function. Then, that value is displayed by using the printf function. A miracle is happening here, something that the ancients would be truly dazzled by, probably to the point of offering you food and tossing fragrant posies your way.

C source code into your editor. Repair any errors you may have encountered. Run the program. The output you see may look something like this: How old was Methuselah? Unlike that sober tome, this book old, but the program accepts it. Is the oldest human really four-and-a-half? C program again, and when Probably at one time. Press Enter and the output tells you that the old guy was 1,,, years old — old or some other value, not what you typed.

The Yes, he was old. But when you enter old into the reason is that you entered a value greater than program, it claims that he was only zero. The an integer can hold. How about typing the following value: In this example, the user typed 26 for the age. That was entered as a string, transformed by atoi into an integer value and, finally, displayed by printf. Other sections in this chapter, as well as in the rest of this book, continue to drive home this message.

The atoi function examines the string and spits up a number. That number is then placed in the age variable as a numeric value. Well, you can. However, only with a numeric variable can you perform mathematical operations. Strings and math? Give up now and keep your sanity! You and Mr. Wrinkles Time to modify the old Methuselah program again. C source code, as shown next. C, only subtle modifications are made to the original program.

Fix any errors that sneak into the picture. Methuselah was years old. Of course, this data is merely regurgitated. First, it reads in your age, and then the atoi function converts it and saves the value in the you variable. Then, years is used again for input. This strategy works because the original value was saved in another variable — a cool trick. C program has been divided into four sections.

The idea is to write the program in paragraphs — or thoughts — similar to the way most people try to write English. No, wait! The first real math explanation is several pages away. When you do math in the C programming language, it helps to know two things: First, know which symbols — or, to be technical, unique doodads — are used to add, subtract, multiply, and divide numbers. Second, you have to know what to do with the results. Of course, you never have to do the math.

Basic mathematical symbols The basic mathematical symbols are probably familiar to you already if you have been around computers a while. These are mathematical or arithmetic — I never know which to use operators. The preceding line tells the C compiler to take the value of the var variable and put it into some numbers.

This chapter introduces only the four most common symbols. The slash, asterisk, minus, and plus symbols are right there, cornering the number keys. You can work with a variable and a value, two variables, functions — lots of things. C source code uses a bit of math to figure out how many more years you have to live before you can hold the unofficial title of the oldest human ever to live or at least tie with him.

What are the advantages of being the oldest person ever to live? What else do we know about Methuselah? He died before the flood. He was a good man, well received by The Man Upstairs. But, what else? Did he avoid the grape? The Bible offers no hints. Cross-check your work with the preceding source code listing, just to be sure. Fix any errors that may crop up.

Then run the final product. Your output may look something like the following: How old are you? It does math! The result then slides through the equal sign and into the diff numeric variable. Bonus modification on the final Methuselah program! Because he got his first job at 19, he has been contributing to Social Security.

As soon as he hits 65, he starts drawing his money out. And out. And out some more. How about writing a program that can do what no bureaucrat in Washington can do: Figure out how much money Methuselah is drawing from the system? C — which I promise is the last of the Methuselah suite of programs. Double-check your typing and all that stuff. Your fine sense of logic wants you to type i before e in received, though the illogic of English dictates otherwise.

Check for any errors or small pieces of meat the compiler may choke on. Dislodge them reedit the source code and compile again if you need to. Methuselah collected from Social Security for years. C works from left to right with math: 65 minus 19; minus Still, the math part of the equation must be on the right. The variable that holds the result is on the left. The direct result Are variables necessary? In the last few Methuselah programs, the values were known, for the most part. Only when you enter your own age is there truly a need for a variable.

The value is calculated by the C compiler as 65—19, which is The same holds true for the second printf function. You can do the same thing without the math. It must, however, be an integer value. You may have just dabbled with variables, but not been formally introduced.

Valerie is a numeric variable. Whenever she sees an equal sign, she takes to a value and holds it tight. But see another equal sign, and she takes on a new value. In that way, Valerie is a little flaky. But which character? The details are in Chapter 9.

This is — oh, just read the next section. You announce them by providing a list of variables near the top of the source code. That way, the compiler knows what the variables are called and what flavor of variables they are what values they can contain. Officially, this process is known as declaring your variables. For example: int count; char key; char lastname[30]; Three variables are declared in this example: an integer variable, count; a character variable, key; and a character variable, lastname, which is a string that can be as many as 30 characters long.

Declaring variables at the beginning of the program tells the compiler several things. Second, the declarations tell the compiler which type of variable is being used.

The compiler knows that integer values fit into the count variable, for example. The space must be set aside as the program is created by the compiler. Cluster them all up right there. A suitable complaint message is issued by the proper authorities. You have to follow a few rules, and you cannot use certain names for variables. When you break the rules, the compiler lets you know by flinging an error message your way. Single-letter variables are just hunky-dory.

But index is better than i, count is better than c, and name is better than n. Short, descriptive variable names are best. All of C is lowercase, for the most part. They can contain letters and numbers.

This may not generate an error with your compiler, but it makes your source code confusing. Refer to Table , in Chapter 3, for a list of the C language keywords. Little L looks too much like a 1 one , and O looks too much like a 0 zero. For example, the compiler may assume that forgiveme and forgivemenot are the same variable.

If so, an ugly situation can occur. Presetting variable values Suppose that this guy named Methuselah is years old. I understand that this may be a new, bold concept to grasp, but work with me here. That requires two steps. First comes the declaration: int methus; This line tells the compiler that methus is capable of holding an integer-size value in its mouth and all that. Normally, string variables are created and given a size.

For example: char prompt[22]; Here, a character string variable, prompt, is created and given room for 22 characters. Then you use gets or scanf to stick text into that variable. The reason is that the compiler is smart enough to figure out how long the string is and use that value automatically. No guesswork — what joy! Just follow the variable name with an equal sign and its value.

Remember to end the line with a semicolon. After all, a variable is still a variable. Each of them is set equal to 0. You probably see this type of declaration used more often than you end up using it yourself. C program was concocted. It works like those old Chinese all-you- can-eat places, where steaming trays of yummy glop lie waiting under grease- smeared panes of sneeze-protecting glass. Repair any unexpected errors — as well as those you may have been expecting — and recompile if need be.

Run the final program. Is that lira or dollars? But the 1. Save the change to disk. Recompile and run. Unlike an integer, floating-point values can contain a decimal part.

That formats the output to only two decimal places. Maybe you want to chance two pints? C into doing some math for you. Suppose that you want to figure out how much two pints of the orange stuff is. Then you have to stick some math into the final printf function, which calculates how much two pints of the sticky stuff would be. Before, you had only the price variable.

Because price is a floating-point, or decimal, value, the result still is floating-point. Save these changes and recompile the program. You have to pay more, but — mmmm — your tummy will thank you. Multiple declarations C is full of abbreviations and shortcuts. One such trick is to declare several variables in one statement. The following three int statements create three integer variables: methus, you, and diff: int methus; int you; int diff; The following single-line statement does the same thing: int methus,you,diff; Each of the variables is specified after the int keyword and a space.

Each is followed by a comma, with the final variable followed by a semicolon to end the statement. This shortcut is primarily a space-saving technique. You can declare variables of only the same type in a multiple declaration. Keep variables that are defined with a value on a line by themselves. Because it never changes, you can create a constant named pi that is equal to that value.

A variable can go there, though a string constant — a literal, quoted string — is used instead. Dreaming up and defining constants All this constant nonsense can seem silly. Carefully type the preceding source code.

Compile it! Fix it if you have to! Run it! The output is pretty plain; something like this example is displayed: Now, the speed limit here is No big deal. But what if the speed limit were really 45? That would mean that you would have to edit the program and replace 55 with 45 all over.

Better still, what if the program were lines long and you had to do that?



0コメント

  • 1000 / 1000