Introduction to Programming in C

Index   |   Using VC++
 
Introduction
Basic Output
Variables
Conditionals
Loops
Example 1
More on Conditionals
8 Further Exploration
Algorithm Design
10 Arrays
 
< Previous

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.

Variables and Math

  • 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 a "shortcut" method for adding a value to a variable.
    a = a + 6;  // this is what you have been using
    a += 6;     // this is a "shortcut" to do the same thing
    
    There are similar operators for the other math operations: -=  *=  /=  %=
  • There are also quick ways to increment or decrement a variable:
    a = a + 1;  // this is what you have been using
    a += 1;     // what you just learned above
    ++a;        // this also increments a
    a++;        // and so does this
    
    b = b - 1;  // this is what you have been using
    b -= 1;     // what you just learned above
    --b;        // this also decrements b
    b--;        // and so does this
    
    There is an important distinction between ++a and a++ when used as part of a more complex statement.
    • 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.
    a = 5;
    b = a++;  // b gets a's value, and then a is changed
    c = ++a;  // a is changed, and then c gets a's new value
    
    After executing the 3 statements above, a will be 7, b will be 5, and c will be 7.

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:
    • integer (int) values: 5, -34, 0, 27
    • floating point (double) values: 5.0, -34.7, 0.0, 67.2
    • 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" statement */
    i = 6;                 // initialization
    while (i <= 20)        // conditional
    {
        printf("%d\n", i);
        i = i + 2;         // 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.
< Previous Next >