CSC 306 Introduction to Programming with C++

The C++ Data Types and Conditional Statement

Chapter 2.1 and 2.4(pages 65-74)


Objectives

Important Definitions


Integer (int) and Floating Point (float) Data Types

The numeral "3" and the number "3.0" actually represent the same amount of information, but in C++ they are used and stored in the computer very differently. A positive, negative, or zero whole number such as "3" without a fractional part is called an integer, while "3.0" is called a floating point number. Integers in C++ are stored in variables of type int, while floating point numbers are stored in variables of types float or double, which we will discuss later. Integers are stored in C++ variables exactly as they are as whole numbers, without even rounding! Division with integers in C++ does not store fractional portions, so the modulus operator (represented as the percent sign in C++ programs) is used to compute the remainder if one exists. Consider the following program which does division with integers and the modulus operator, %, to get the remainder of the division:
#include <iostream>
using namespace std;

// This "IntegerDivision.cpp" program is designed to demonstrate both
// integer division and the modulus (%) operation.

int main() {
    int denom, numer, answer, remain;

    cout << "Enter an integer for the numerator: ";
    cin >> numer;
    cout << "Enter a number for the denominator: ";
    cin >> denom;
    
    answer = numer / denom; // Performs integer division
    remain = numer % denom; // Gives remainder from integer division

    cout << endl;
    cout << numer << " divided by " << denom << " is " << answer;
    cout << " leaving a remainder of " << remain << "." << endl;

    return 0;
}
Download, compile, and run this code, IntegerDivision.cpp, trying a number of examples so you see what is happening. This type of division of two integers that discards the decimal or fractional part of the number is called integer division. Integer division can be a useful tool because it give you the most number of times the denominator can be multipled without exceeding the numerator.
WARNING: Most of us are so used to working with decimal numbers that it can be easy to make a logic error and expect a decimal number answer instead!

Identifiers and Naming Identifers in C++

Note that in the source code, meaningful names (called identifiers) are given to the variables. Any name can be given to variables, but there are several rules one must follow. Identifiers
  1. must begin with an uppercase or lowercase letter or an "_" (underscore) symbol.
  2. may be followed by any number of letters, numbers, and "_" symbols only. Any other symbols are not allowed, so the identifiers "_hello", "h333llo", "_h", "_3" are valid, but "he-llo" "3hello", h$llo" are not.
  3. may not be a reserved word, such as "int" or "main".
Finally, C++ is case-sensitive, so upper and lower case letters are not equivalent; thus "hEllo", "hello", and "HELLO" are all different.
WARNING: Not following these rules will likely result in syntax errors!

Conditional (if) Statements

Conditional statements enable the programmer to design programs that change their behavior according to certain conditions. The simpliest form of a C++ conditional statement is using the if condition, as demonstrated by the following example, where the variable num is declared as an int:
    if( num < 0 ) {
       cout << "The number is negative.\n";
    }
Note that because the example above is a portion of a complete proram, it is called a code fragment. You can compile and run the complete program, called IfConditional.cpp The expression in parentheses is called the condition. If the condition is true, then the statement(s) between the curly brackets get executed. If the condition is not true, these statement(s) are skipped. In C++, the condition can contain any of the following comparison operators:
> greater than
< less than
>= greater than or equal
<= less than or equal
== equal
!= not equal
Another useful form of the conditional statement that is used when different outcomes are required depending upon the condition. This form of the conditional execution is alternative execution or if-then-else, in which there are two possibilities, and the condition determines which one gets executed. Each of these routes that the program can execute is called a branch. The syntax of this statement looks like:
    if( num % 2 == 0 ) {  // What to do when num is exactly divisible by 2.
	cout << "The number is even." << endl; 
    } 
    else {                // What to do when num is NOT divisible by 2. 
	cout << "The number is odd." << endl;
    }
Try this example, ConditionalIfElse.cpp, noting that here we used only the modulus operator, %, without the division operator, /, because we only needed the remainder.

Note that the above code is a much more efficient way of coding the algorithm than the following code:

    if( num % 2 == 0 ) { // What to do when num is exactly divisible by 2.
	cout << "The number is even." << endl; 
    } 
    if( num % 2 != 0 ) { // What to do when num is NOT divisible by 2.
	cout << "The number is odd." << endl; 
    }
Though this code with two if statements will accomplish exactly the same task and have the same output as the code with the if-else, it is less efficient because num is tested twice instead of just once.

Chaining the If Conditional Statement

Sometimes you want to check for a number of related conditions and choose one of several actions. One way to do this is by chaining a series of ifs and elses as in the following example:
    if( num > 0) {
	cout << "The number is positive." << endl;
    }
    else 
	if( num < 0) { 
	    cout << "The number is negative." << endl; 
	}
	else { 
	    cout << "The number is 0." << endl;
	} 
Note that the second if-else is chained in the first else. Try this example, ConditionalChaining.cpp. These if-else chains can become as long as you need, although they can be difficult to read if they get too long. One way to make them easier to read is to use standard indentation, as demonstrated in these examples. If you keep all the statements and braces lined up, you are less likely to make syntax errors, and you can find errors more quickly if you do make them.

In addition to chaining, you can also nest one conditional within another. The previous example done this way is:


    if( num > 0) {
	cout << "num is positive" << endl; 
    }
    else { 
	if( num < 0) {
	    cout << "num is negative" << endl;
	}
	else {
	    cout << "num is 0" << endl; 
	}
    }
This example will have exactly the same output as the previous example, however, in this nested example, there is now an "outer conditional" that contains two branches. The first branch contains a simple output statement, but the second branch contains another if statement, which has two branches of its own. Fortunately, those two branches are both output statements, although they could have been conditional statements as well. Notice again that standard indentation helps make the structure apparent, but nevertheless, nested conditionals get difficult to read very quickly. This kind of nested structure is common and enables conditional execution behavior that is not possible otherwise.


The Assignment Details

This assignment must be completed individually! You will write a new C++ program using the modulus operator and a conditional statement. Your program, named YourLastName_306A3.cpp, will prompt the user to type in a year, read in the user's input and then outputs the number of days for that year. You will use the following description to determine how to design your program: "The calendar year is 365 days long, unless the year is exactly divisible by 4, in which case an extra day is added to February to make the year 366 days long. If the year is the last year of a century, eg. 1800, 1900, 2000, then it is only a leap year if it is exactly divisible by 400. Therefore, 1900 wasn't a leap year but 2000 was. The reason for these rules is to bring the average length of the calendar year into line with the length of the Earth's orbit around the Sun, so that the seasons always occur during the same months each year." From The web site of the Royal Observatory in Greenwich Be sure to: You may want to look carefully at the code given in the last two assignments as you think about how to complete this assignment.

This assignment must be completed individually. When you are finished with your assignment, drop your source code into the CSC306_A03 dropbox on the Academic server.


Back to Introduction to Computer Programming with C++ Homepage