Professional Documents
Culture Documents
Basic C Programs
Basic C Programs
We're ready to create our first program. Here are the steps.
Next >
Create a new project: o Start Visual C++ Express 2005 (hereafter referred to as VC++). o Select File/New/Project o In the Project types panel, choose General. o In the Templates panel, choose Empty Project. o In the Name edit, enter HelloWorld. o (Leave Location and Solution Name alone, and leave Create directory for solution checked.) o Click OK. Create a file called main.c for your code: o Select Project/Add New Item. o In the Categories panel, choose Code. o In the Templates panel, choose C++ File (.cpp). o In the Name edit, enter main.c (note that we are using the C suffix, .c, not the default C++ suffix). o Click Add. Type in the following code. Be sure to get the punctuation correct -- notice the semicolons at the end of some lines, use double quotes (not two apostrophes), and be careful to use backslash (\) and not slash (/).
#include <stdio.h> int main() { printf("Hello, World!\n"); } return 0;
Select File/Save. Select Build/Build Solution (or hit F7) to build your code into an executable program. Look at the Output window/tab at the bottom and make sure there were no errors. (If there are errors, look at the Errors tab for details and correct the problems.) Select Debug/Start Without Debugging (or hit Ctrl-F5) to run your program. VC+ + will open a command line window to show your program's output.
Explanations
You'll see these items in the sample programs; they are important to the compiler, but it's not necessary for you to fully understand them at this point. You can skip this list, but here's a quick explanation for the curious:
- this is a compiler directive that lets the compiler know we want it to include a file that has information about something that our program will use. stdio.h - this file is included because it contains details about the printf function that our code uses (stdio is short for "standard input and output"). main() - this is a function, and the special name (main) lets the compiler know that this is where to start running our program. The int before it indicates the type of value returned by the function, in this case an integer.
#include
Important stuff...
- the braces indicate a block of code. This construct is used extensively in C to indicate a group of instructions. printf(...) - this is a function that will print a formatted string (to "standard" output, i.e. the screen). The code for that function lives in a library that will be accessed as part of the build process. The parameter or argument to printf is a string, which needs to be contained in double quotes. \n - an escape character that tells the code to display a newline character. (You can't just put a carriage return in the string.) The backslash is a special character, and the character after it indicates what should be displayed. (If you actually want a backslash displayed, put two of them in the string: "\\".) Each statement must end with a semicolon (;). For readability, convention is to put one statement per line, and to indent the statements within a block (the contents of { }).
{ }
Changes
Make the following changes to your program:
Use multiple printf statements to get the same result. Put "World" on its own line (careful about the space). Keep your code "pretty" -- make sure that your statements are all nicely aligned. This is a good habit to get into now! Try adding additional text, including new lines. Can you create a blank line?
Exercises
Let's introduce a compiler error to see how it gets reported:
Remove the semicolon from the end of a printf statement. Hit F7 to build the program.
Notice that the Output window (at the bottom) reports a compiler error. Doubleclick on the line reporting the error; this will highlight the line of code that is mentioned in the error report. Read the message explaining the problem. In this case, it says there is a missing semicolon; note that the highlighted line is the line after the one that's missing the semicolon.
When you are done working with this project, select File/Close Solution.
Summary
Create a new project and main.c file for each program. Build your program with F7 or Build/Build Solution. Check for errors in the Output window. Run your program with Ctrl-F5 or Debug/Start Without Debugging. Use printf to display formatted text. Use "\n" to start a new line of text.
Create a project called Math. Create a source file called main.c. Type in (or copy/paste) the following code:
#include <stdio.h> int main() { int a; int b; a = 6; printf("The value of a is %d.\n", a); b = a + 3; printf("The value of b is %d.\n", b); } return 0;
Save your file. Build your program (F7). Check the Output window for errors. Run your program (Ctrl-F5).
Explanations
"int a;" is a variable declaration, which lets the compiler know that our program wants memory to store an integer, and will refer to that memory with the name "a". "a = 6;" is a variable initialization; read this as "a gets 6" -- it's best not to think of "=" as "equals" since you cannot reverse the statement. ("6 gets a" would not make sense, either to you or the compiler!) There is a new special character in this example of printf: %. The % character tells printf to place the value of a variable at this location. The character after the % indicates the type of value, in this case d for a decimal (base 10) integer. The variable to use is passed as another parameter, after the string. The basic arithmetic operators are
+ * /
Definitions
Variable A named location where a value can be stored (and modified). Variable Declaration A statement that lets the compiler know what type of variable we need (and thus how much memory) and what we want to call it. Variable Initialization Giving a value to a variable. There is no default value assigned when a variable is declared.
Exercises
Practice with calculations and output:
Change the initial value for a. Change what's added to b. Try things like
b = a * 5;
or
b = 2 + a * 5;
You can use parentheses for more complex operations, just as in math. Make the output appear all on one line, e.g.
The value of a is 6 and the value of b is 9.
(Hint: Why are you getting two lines? It's not because there are two printf statements.)
Changes
Initialize a with the value 7 and change the line setting b to "b = a / 2;" What do you expect to happen? Build, check for errors, then run your program. You will see that the result is 3, not 3.5! Since we are using integers, there are no fractional values. The rule for division using integers is that the result is truncated, not rounded. You can output multiple variables in one printf statement by specifying %d in each location that you want a value. You will need to pass as many variables as you have %d in the string, e.g.
printf("a is %d and b is %d.\n", a, b);
Exercises
Experiment with division to get a good understanding of how truncation works. Try things like 1 / 3, 4 / 3, 16 / 5, and 19 / 5.
When you are done working with this project, select File/Close Solution.
Summary
You need to declare variables before you can use them. Use operators + - * and / to perform mathematical operations. Division (/) of integers will truncate (not round) the result. printf uses "%d" to output an integer variable.
Conditionals
Next >
Create a project called If. Create a source file called main.c. Type in (or copy/paste) the following code:
#include <stdio.h> /* This program shows the use of a conditional statement (if) and the two styles of comments supported by the C language. */ int main() { int temp; // temperature temp = 85; printf("It is %d degrees outside.\n", temp); if (temp > 70)
{ } }
return 0;
Save your file. Build your program (F7). Check the Output window for errors. Run your program (Ctrl-F5).
Explanations
A comment is text added for a human reader; it is ignored by the compiler. This example shows both styles. o The first comment style is to enclose text between /* and */, as shown by the comment before the main() function. Comments using this style can appear on multiple lines, or in the middle of a line of code; once the */ is reached, the compiler will begin processing again. o The second comment style is to use // followed by text, as shown following the declaration of the variable temp. In this case, the comment continues until the end of the line. There is no way to close this style of comment before the end of the line, and each commented line needs to begin with //. The if statement enables the program to make a decision -- if the expression in the parentheses is true, the block of code following the if is executed. If the expression is false, that block (the braces { } and the code inside them) is skipped. In this case, since temp is 85, and since 85 is greater than 70, the expression is true, and the "warm" message is printed. Note that there is no semicolon at the end of the if expression! The line with the if is the first part of a statement (which is completed by the block following it). By convention, statements inside the braces are indented (for readability). Comparison operators are: less than greater than less than or equal to greater than or equal to equal to (note that a single = will not == work!) != not equal to
< > <= >=
Definition
Boolean Expression
An expression that evaluates to either true or false; typically a comparison. The contents of the parentheses in an if statement should be a Boolean expression.
Exercises
Initialize the temperature (temp) to 50 (instead of 85) and run the program again. In this case, since 50 is less than 85, the if statement is false, so the block of text containing the "warm" message is skipped. What would you expect to happen for temperature values of 69, 70, and 71? Try those values and see if your predictions are correct. Make the "warm" message show when the temperature is 70. There are (at least) two ways to do this; can you figure them out? Which one seems more logical to you?
Changes
Make the following changes to your program:
You can have multiple statements in the block corresponding to an if. Add the code below (gray text is existing code). Be sure to keep the code nicely indented for readability. Then build, check for errors, and run the program (be sure to set temp to a value that will make the if expression true).
if (temp > 70) { printf("%d degrees is warm.\n", temp); printf("Let's go hiking!\n"); }
If you want to do something when the Boolean expression in the if statement is false, just add an else clause and a corresponding block of code (shown below). o When the Boolean expression in the if is true, the block following the if will be executed and the block following the else will be skipped. o When the Boolean expression in the if is false, the block following the if will be skipped and the block following the else will be executed. Add the code below, then build, check for errors, and run the program. Test it with different temperature values.
if (temp > 70) { printf("%d degrees is warm.\n", temp); printf("Let's go hiking!\n"); } else { printf("%d degrees is cool.\n", temp); }
You can input a value from the user. Make the following 3 edits, shown below: o Add the #define line. It must be before the #include line. (This is only necessary for VC++ users; if you are using the Mac OS X tools, or another Windows compiler, you probably won't need this (although it is harmless to leave it in); it suppresses a warning about using scanf, which Microsoft has deprecated in favor of its safer version, scanf_s. We'll stick with scanf for compatibility with other tools.) o Comment out "temp = 85;". We'll input the value instead of setting it here. o Add the two new statements (calls to printf and scanf). The printf statement is a prompt to let the user know what the program is expecting. scanf is another function, one that will input from the keyboard; again, %d indicates a decimal (base 10) integer value. The & in front of temp is important -- it allows scanf to change the value of the variable temp. Build, check for errors, and run the program. Once this code is added, you don't need to change code and rebuild in order to test with different values for temp!
#define _CRT_SECURE_NO_DEPRECATE #include <stdio.h> /* This program shows the use of a conditional statement (if) and the two styles of comments supported by the C language. */ int main() { int temp; // temperature // temp = 85; printf("What is the temperature? "); scanf("%d", &temp); printf("It is %d degrees outside.\n", temp); if (temp > 70) { printf("%d degrees is warm.\n", temp); printf("Let's go hiking!\n"); } else { printf("%d degrees is cool.\n", temp); } } return 0;
You can nest one if statement inside another. Add the code below, then build, check for errors, and run the program. Test it with different values.
if (temp > 70)
printf("%d degrees is warm.\n", temp); if (temp > 100) { printf("In fact, that's really hot!\n"); } printf("Let's go hiking!\n");
Exercise
Nest an if statement in the else block to show a message that it's freezing when it's 32 degrees or less.
When you are done working with this project, select File/Close Solution.
Summary
Text enclosed between /* and */ is a comment, and is not processed by the compiler. Text after //, until the end of the line, is a comment. Programs can make decisions using if statements, optionally followed by else statements. Values can be input using the scanf function.
Loops
Next >
Create a project called Loops. Create a source file called main.c. Type in (or copy/paste) the following code:
#include <stdio.h> /* print the numbers 1 to 9, inclusive */ int main() { int i; i = 1; // start at 1 while (i <= 9) { printf("i is now %d\n", i); i = i + 1; // increase by 1 } /* execution will continue here when the "while" condition is false */
return 0;
Save your file. Build your program (F7). Check the Output window for errors. Run your program (Ctrl-F5).
Explanations
As in the if statement, the while statement contains a Boolean expression that determines whether the block following the while expression is executed. The difference is that in the case of a while loop, after performing the steps in the block, execution returns back to the line with the while expression, evaluating the Boolean expression again. This looping continues as long as the expression is true. When the expression is false, the block is skipped, and program execution continues with the statement following the loop's block. Note that as with if, there is no semicolon following the while expression; it is the first part of a statement, completed by the block following it. As indicated by the comment, this program will print the numbers from one to nine, inclusive. Let's trace through to see what will happen as the program executes. o At the beginning of the program i is set to 1. o Next, the while expression is evaluated. Since i is 1, and 1 is less than or equal to 9, the expression is true, so we enter the block of code following the while expression. o In the block, we print "i is now 1", then change i by taking its current value (1) and adding 1 to it, thus getting 2. o When we reach the end of the block (the }), we go back to the while expression at the top of the loop. o Now, we compare the current value of i (2) to 9. The expression is still true, so we enter the block again. o This time, we print "i is now 2", then change i by taking its current value (2) and adding 1 to it, thus getting 3. o Again, we return to the while expression. This obviously continues for several more iterations. Let's jump ahead to when i is 9 when we return to the top of the loop. o Since "9 <= 9" is true, we enter the block, print "i is now 9", and then change i to be 10 (current value of 9, plus 1). o Now when we return to the while expression, it is (finally!) false. At this point, we "exit the loop," skipping the block and going to the code immediately after it, in this case the return statement (since the comment is ignored by the compiler). Note that when we exit the loop, i is not 9, the last "good" value -- it is 10, the value that made the condition false.
Definition
Loop Variable A variable that controls a loop (in this case i). It is initialized before the loop, used in the loop's Boolean expression, and changes inside the loop's block.
Changes
Make the following change to your program:
Add a printf statement to show the value of i after the loop is exited.
Exercises
Try the following to practice with loops. For each of these, you may find it useful to use scratch paper to organize your thoughts. As you make changes to the code, be sure to update the comments so they accurately reflect what your code is doing!
Show the values from 10-20, inclusive. See if you can do this two different ways (by changing the Boolean expression). Show the numbers 15 down to 5, inclusive (i.e. 15, 14, 13...3, 2, 1). Count to 100 by 5s.
When you are done working with this project, select File/Close Solution.
Summary
while
loops can be used to repeat code as long as the specified condition remains Next >
true.
Example 1
Create a project called Temperature. Create a source file called main.c. Type in (or copy/paste) the following code:
#include <stdio.h> /* convert from Fahrenheit to Celsius using the formula degrees C = (5/9) (degrees F - 32) */ #define fFirst 0 #define fLast 300 #define fStep 20 int main() { int f; // start with 0 degrees F // end with 300 degrees F // step by 20 degrees F
// degrees Fahrenheit
int c;
// degrees Celsius
f = fFirst; while (f <= fLast) { c = 5 * (f - 32) / 9; printf("%d %d\n", f, c); f = f + fStep; } } return 0;
Save your file. Build your program (F7). Check the Output window for errors. Run your program (Ctrl-F5).
Explanations
The #define lines at the top describe substitutions to be made by the compiler. Each time that fStep is used, the compiler will automatically use 20. The effect is similar to when variables are initialized and used, but the #define method is quicker to execute. It is natural to wonder, "why not just put the numbers directly into the code?" That would work, but the list of defined values at the top makes the code easy to understand and modify (without sacrificing any efficiency). Notice that comments explain what the program will do and how the variables are used. Look at the calculation for degrees Celsius. The code doesn't use "5/9 * (f-32)" because the calculation 5/9 would result in a value of 0 since integer division is truncated. This is easily solved by doing the multiplication first, and then the division.
Changes
Make the following changes to your program:
Help the columns align a little better by separating the values with a tab ("\t") instead of spaces. Build, check for errors, and run with this change. Wouldn't it be nicer if the numbers were aligned on the right instead of the left? That's pretty simple to do! We can specify how many spaces each number should use, and it will be right-justified in that area. Three spaces will work nicely here. Change the string passed to printf to include a 3 in each %d:
printf("%3d\t%3d\n", f, c);
Build, check for errors, and run with this change. OK, that looks better, but it would be even more useful if we had better precision for the Celsius values. Let's use floating point numbers:
First, we need to declare the variable c as a floating point variable. The common type for that is double, which is a double-precision floating point number that can store up to 15 significant digits. Change the declaration for c to:
double c; // degrees Celsius
The calculation is still using integers, though (f, 5, 32, and 9 are all integer values). The first calculation will be (f-32). That's fine with integers, as is the multiplication by 5 that comes next. We just need to make sure to force a calculation using floating point numbers when we divide by 9. The rule is that if either operand is a floating point number, the calculation will be made with floating point. In this case, we can change "9" to "9.0" -that makes it a floating point value. Note that we don't use floating point when it's not needed. There are several reasons for this -- integer math is faster, and integers require less memory. We need to change the call to printf to let it know that the second variable we're sending is a double. use %f to indicate a floating point number:
printf("%3d\t%f\n", f, c);
We can control the formatting of floating point numbers similarly to the way we did for integers. Try using "%6.2f" -- the 6 is the number of spaces that the value will use (including the decimal point); the 2 is the number of digits to show after the decimal.
Exercises
Add column headings. Think about where this code should go. Do you want it to happen each time through the loop? Before the loop? After it? Add another column (after the Celsius column) that will show "cold" for values under 70 degrees Celsius, or "warm" for values of 70 and over. Think about how you will decide what to print, and where this code should go.
When you are done working with this project, select File/Close Solution.
Summary
Use #define statements for constant values (instead of using variables or putting the numbers directly in the code). This helps code be more readable and easier to maintain. When making calculations, consider how integer division gets truncated. Use floating point numbers (double variables) when necessary. You can control formatting of numbers by using things like "%3d" and "%6.2f".
More on Conditionals
Next >
Conditionals are used in if and while expressions. This section covers some additional important features for conditionals. Note that the examples below are code fragments; you will need to put them inside your main() function.
In the case where there is only one statement in a block following an if, the braces are optional and can be omitted.
if (a < b) printf("a is smaller!\n"); When an if's condition is true, the computer will execute the (one) statement immediately following the if. In order to execute multiple statements, they are
combined into a block (multiple statements in braces); the block is considered a single statement. This applies to all conditionals, e.g. else, else if (below), while, and for (explained in the next section).
What happens if you forget and put a semicolon after an if or while condition? The computer identifies the semicolon as an empty statement. Consider the following examples -- the erroneous semicolon is marked in red.
if (a < b); printf("boo!"); while (a < b); { // some code here... a = a + 1; } o In the first example, when the if's condition is true, the statement following the if is executed -- this is the semicolon / empty statement!
So, "boo!" will always be printed. (Note that code indentation is ignored by the compiler.) o The second example is an excellent illustration of an infinite loop. If the condition (a < b) is true, execution will move to the statement following the while condition, in this case the empty statement specified by the semicolon. After executing that statement (doing nothing), execution returns to the condition. But, since nothing is changing a or b, the condition will never become false, and execution will never leave the loop! To check another condition in the else case following an if, you can use the "else if" clause. When the condition of the if is false, the condition of the else
will be checked. If it is true, the block (or statement) following it will be executes; if the else if's condition is false, the block will be skipped, and execution will continue after it.
if if (score >= 90) printf("you got an A\n"); else if (score >= 80) printf("you got a B\n"); else if (score >= 70) printf("you got a C\n"); else printf("better luck next time!\n"); printf("done...\n");
Some examples using the above code: the if's condition is true, so its statement is executed (the "A" message is printed). The remaining else if and else statements are then skipped, and execution continues with the statement after the ifelse group (the "done" message). o score = 85: the if's condition is false, so execution moves to the (first) else if. That condition is true, so its statement is executed (the "B" message is printed). The remaining else if and else statements are then skipped, and execution continues with the statement after the if-else group (the "done" message). o score = 65: the if's condition is false, so execution moves to the (first) else if. Its condition is false, so execution moves to the second else if (comparing score to 70). That is also false, so execution moves to the else at the end; this is the block that catches conditions not handled by any of the if or else if conditions. It prints the "better luck" message, then execution continues with the "done" message. You can use a compound Boolean expression in a conditional clause to check multiple conditions. Use && for a logical AND, and || for a logical OR. Note that both operands must be complete Boolean expressions.
o if (age >= 13 && age <= 19) printf("you are a teenager\n"); if (age < 10 || age >= 65) printf("you get a discount\n"); score = 95:
The operator NOT (!) will negate an expression, turning a true expression false, or a false expression true. It's useful to know the opposite of conditional expressions. This is what happens if you want the logical NOT of an expression. Expression Opposite Opposite Simplified
a < b a <= b a == b !(a < b) !(a <= b) !(a == b) a >= b a > b a != b
Sometimes it's easier to express a conditional that's the opposite of what you want to check in code. For example, if you expect input between 1 and 10 (inclusive), and want to show an error when you don't get something in that range. In this case, it's fairly straightforward to express the desired situation:
a >= 1 && a <= 10
While we could use the expression above, it's better to resolve the NOT and use a simpler expression. Here are the rules for negating expressions that use logical AND and logical OR: Expression Opposite Opposite Simplified
a && b a || b !(a && b) !(a || b) !a || !b !a && !b
Recall from above how to find the opposite of an inequality, which simplifies our expression to:
a < 1 || a > 10 if (a < 1 || a > 10) printf("Bad value!");
If you want to compare a variable to several values, you could use a series of else if statements (starting with if and possibly ending with else). But, a better way is to use a switch statement. One common example is a menu, where the program displays a list of options, and the user enters a number to select what the program should do.
switch (a) { case 1: printf("option 1..."); break; case 2: printf("option 2..."); break; case 3: printf("option 3..."); break; case 0: case 99: printf("exiting..."); break; default: printf("unknown option!"); break; } o In this example, the printf
statements would be replaced with code to actually perform the specified option.
o o o
The contents of the parentheses following the switch must be an integer (or char; see next section), and is typically a variable, as shown here, but could also be a mathematical expression. The case keyword must be followed by a constant value (not a variable). Each case statement must list a single value; it cannot specify a range. When the program runs, it looks at the value of variable a, jumps to the correct case statement, and begins executing code there. (Note that values 0 and 99 both result in printing the exit message.) The break statement at the end of each case causes execution to "break" out of the switch, continuing execution at the statement immediately after the switch statement's closing brace. If a break statement is eliminated, execution will "fall through" to the next case statement. The default statement is optional, but is a convenient way to handle all values that aren't specifically listed with a case statement. It is like the final else after a series of else if statements.
Summary
Braces around a block following an if or else are optional if there is only one statement in the block. Use else if to make multiple comparisons in a row. Use logical AND (&&) and logical OR (||) operators to combine Boolean expressions in a conditional expression. Use switch to conveniently and efficiently choose among several values for a variable.
Further Exploration
Next >
With what you have learned in the previous sections, you can write programs to solve a variety of problems. But, in order to read code written by a more experienced programmer (and to become a better programmer yourself), you will need to understand some other ways of doing things. Note that the examples below are code fragments; you will need to put them inside your main() function.
You can declare multiple variables (of the same type) at once by listing names separated with commas.
int num1, num2;
In addition to the usual math operators (+ - * /), there is an operator for "modulo," %, which will calculate the remainder of an integer division. This
example also shows how a long line of code (the printf statement) can be separated onto multiple lines.
int inches; int result_feet, result_inches; inches = 62; result_feet = inches / 12; result_inches = inches % 12; printf("%d inches = %d feet, %d inches\n", inches, result_feet, result_inches); /* output will be: 62 inches = 5 feet, 2 inches */
There is an important distinction between ++a and a++ when used as part of a more complex statement.
o o o
When the ++ operator is used before a variable, it is a pre-increment and the increment happens before other calculations. When the ++ operator is used after a variable, it is a post-increment and the increment happens after other calculations. The same rules apply for the -- operator.
// b gets a's value, and then a is changed // a is changed, and then c gets a's new value
a = 5; b = a++; c = ++a;
Variable Types
In order to store a character, you can use the char type. Assign values to a char by putting a character in single quotes. You can also compare char variables to quoted characters. The printf and scanf functions use "%c" for char data types.
char ch1, ch2, ch3; ch1 = 'a'; ch2 = '?'; scanf("%c", &ch3); printf("You typed %c\n", ch3); if (ch3 == 'x') printf("x marks the spot!\n");
Characters are represented with ASCII values, so, for example, if you store the value '4' in a char variable, it will be assigned the ASCII value of 52. Conveniently, the char data type can also be used to hold 8-bit numeric values. This is done in cases where the larger capacity of an int is not needed and memory is tight.
Examples of data types: o integer (int) values: 5, -34, 0, 27 o floating point (double) values: 5.0, -34.7, 0.0, 67.2 o character (char) values: 'a', 'A', '?', '$', '5' (Note that you can't do something like '13'; the quotes must contain a single character.) In the "Example 1" section, you learned about the double data type. Here is some additional information, covering input and arithmetic operations.
int a, b; double x, y; a = 5; b = 3; scanf("%lf", &x); // note that scanf uses %lf printf("your number is %f\n", x); /* the following uses integer math since a and b are both integers; 5/3 is 1, which is then converted to a floating-point number and stored into y */ y = a / b; /* this will use floating point math since x is a floating-point number */ y = a / x; /* this forces a floating-point calculation; the "(double)" is a "cast" which instructs the compiler to convert the variable "a" to a double-precision floating-point number, after which the calculation is performed */
y = (double)a / b;
Note that you can also cast a double to an integer value (e.g. (int)x), which results in truncation (not rounding!) of the floating-point value.
Loops
One common way to control a loop is with a for statement. It works like a while statement, but nicely groups the three main parts of loop control: initialization, conditional, and variable update. The two loops below will perform the same steps; note where the each part of the while example is located in the equivalent for example. One important thing to remember with the for loop is that the variable update (the last item in the parentheses) is done at the end of the loop, after all the statements in the block.
int i; /* looping with a "while" i = 6; // while (i <= 20) // { printf("%d\n", i); i = i + 2; // } statement */ initialization conditional
variable update
/* the same logic in a "for" loop */ for (i = 6; i <= 20; i = i + 2) { printf("%d\n", i); }
Note that the braces in the for loop are optional in this case. As with if statements, the braces around the statements in the for block may be omitted if there is just one statement.
Another useful loop is the do...while loop. In this loop, the block comes before the condition, and it thus always executed at least once. The do...while loop is very useful for things like validating input from the user:
do { printf("Please enter a positive number: "); scanf("%d", &x); } while (x <= 0);
The prompt and input will always happen, and then the result can be checked, repeating the loop in the case of invalid input. Note that there is a semicolon after the while statement here since it is the end of the statement.
Summary
Declare multiple variables of the same type by separating their names with commas, e.g.
int a, b, c;
Use the modulo operator (%) to calculate the remainder of an integer division. Use "shortcut" operators += ++ etc. In addition to the int type, there are types char and double. Use casting to convert between types. In addition to while loops, you can use for and do...while loops.
Algorithm Design
Next >
As programming projects get more complicated, it becomes worthwhile to plan before you start coding. Start by developing a plan, then implement and test it.
Problem-solving phase:
1. Analyze -- understand and define the problem; ask questions, state assumptions. 2. Develop an algorithm -- determine the steps necessary to solve the problem; use scratch paper. 3. Test -- follow the exact steps to make sure that the algorithm works. Try specific cases and see how your algorithm reacts.
Definition
algorithm A step-by-step procedure for solving a problem.
Implementation phase:
1. 2. 3. 4. Write code -- translate the algorithm into a programming language. Test -- have the computer follow the steps (execute the program). Debug -- check the results and make corrections until the answers are correct. Use the program.
Example
Assignment: for a given number of cents, print the number of quarters, dimes, nickels, and pennies needed to reach that value (with minimal coins).
Think about how you would do it in real life. o Which coin do you start with? o How do you know how many you need?
How do you figure out how much money is left after that coin? Use scratch paper to organize your thoughts; list the steps you will need to perform. Brainstorm with a friend if you like! Create a new project. Work in stages, for example just working on calculating and printing the result for the first coin. Get that part compiling and working correctly, then move on to the next coin. Think about interesting test cases, e.g. results that don't need any of a specific coin. On paper, list the things you want to try, and what you expect the answer to be for each. Test your program, and correct it as necessary.
o
Exercises
Here are some other ideas for programs you can write:
Modify the "count to 100 by 5's" program to show 5 to 50 on one line and 55 to 100 on the next line. Write a new program to print the squares of numbers from 1 to 10, inclusive. Write a new program to input 5 numbers and print their average. Write a new program to input 5 numbers and print the largest value. Make sure that it works correctly if you enter all negative numbers! Write a new program to input numbers until the user enters 0, and then print the average of all the numbers, not including the 0. Write a new program to show the Fibonacci numbers less than 100. The Fibonacci sequence starts with two ones and each number is the sum of the two numbers before it: 1 1 2 3 5 8 13 21 ...