






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
This chapter gets you started immediately writing some simple C programs and helps you to understand some basic elements in any high level programming language such as data types, arithmetic operators, output statements and assignment statements.
Typology: Study notes
1 / 12
This page cannot be seen from the preview
Don't miss anything!
This work is produced by The Connexions Project and licensed under the Creative Commons Attribution License †
Abstract This chapter gets you started immediately writing some simple C++ programs and helps you to understand some basic elements in any high level programming language such as data types, arithmetic operators, output statements and assignment statements.
1.1 Modular Programs
A large program should be organized as several interrelated segments, arranged in a logical order: The segments are called modules. A program which consists of such modules is called a modular program. In C++, modules can be classes or functions. We can think of a function as a program segment that transforms the data it receives into a nished result. Each function must have a name. Names or identiers in C++ can made up of any combination of letters, digits, or underscores selected according to the following rules:
Examples: DegToRadintersectaddNums FindMax1_densityslope Examples of invalid identiers: 1AB E% while Note: C++ is a case-sensitive language (i.e. upper and lower case characters are treated as dierent letters).
∗Version 1.1: Jul 6, 2009 11:37 pm GMT- †http://creativecommons.org/licenses/by/3.0/
1.2 The main() function
The main() function is a special function that runs automatically when a program rst executes. All C++ programs must include one main() function. All other functions in a C++ program are executed from the main() function. The rst line of the function, in this case int main() is called a function header line. The function header line contains three pieces of information:
int main() {
program statements in here return 0; } Note: The line return 0; is included at the end of every main function. C++ keyword return is one of several means we will use to exit a function. When the return statement is used at the end of main as shown here, the value 0 indicates that the program has terminates successfully.
1.3 The cout Object
The cout object is an output object that sends data given to it to the standard output display device. To send a message to the cout object, you use the following pattern: cout text; The insertion operator, , is used for sending text to an output device. The text portion of the statement is called a text string. Text string is text that is contained within double quotation marks. Consider the following program. Example #include <iostream.h> int main() { cout "Hello world!; return 0; } The output of the above program: Hello world!
1.4 Preprocessor Directives
Before you can use any runtime libraries in your program, you must rst add a header-le into your program, using the #include statement. A header le is a le with an extension of .h that is included as part of a program and noties the compiler that a program uses run-time libraries. One set of classes you will use extensively in the next few chapters is the iostream classes. The iostream classes are used for giving C++ programs input capabilities and output capabilities. The header le for the iostream class is iostream.h. The #include statement is one of the several preprocessor directives that are used with C++.
Exponential notation, or scientic notation is a way of writing a very large numbers or numbers with many decimal places using a shortened format. 2.0e11 means 2* C++ supports three dierent kinds of oating-point numbers:
A double precision oating-point number can contain up to 15 signicant digits. The Character Data Type To store text, you use the character data type. To store one character in a variable, you use the char keyword and place the character in single quotation marks. Example: char cLetter = `A';
2.2 Escape Sequence
The combination of a backlash () and a special character is called an escape sequence. When this character is placed directly in front of a select group of character, it tells the compiler to escape from the way these characters would normally be interpreted. Examples: \n : move to the next line \t : move to the next tab The bool Data Type The C++ bool type can have two states expressed by the built-in constants true (which converts to an integral one) and false (which converts to an integral zero). All three names are keywords. This data type is most useful when a program must examine a specic condition and, as a result of the condition being either true or false, take a prescribed course of action.
2.3 Arithmetic Operators
Most programs perform arithmetic calculations. Arithmetic operators are used to perform mathematical calculations, such as addition, subtraction, multiplication, and division in C++.
Figure 1: Arithmetic operators
A simple arithmetic expression consists of an arithmetic operator connecting two operands in the form: operand operator operand Examples: 3 + 7 18 3 12.62 + 9. 12.6/2. Example #include <iostream.h> int main() { cout "15.0 plus 2.0 equals " (15.0 + 2.0) '\n' "15.0 minus 2.0 equals " (15.0 - 2.0) '\n' "15.0 times 2.0 equals " (15.0 * 2.0) '\n' "15.0 divided by 2.0 equals " (15.0 / 2.0) '\n'; return 0; } The output of the above program: 15.0 plus 2.0 equals 17 15.0 minus 2.0 equals 13 15.0 times 2.0 equals 30 15.0 divided by 2.0 equals 7.
2.4 Integer Division
The division of two integers yields integer result. Thus the value of 15/2 is 7. Modulus % operator produces the remainder of an integer division. Example: 9%4 is 1 17%3 is 2 14%2 is 0
double precision) as operands is called a oating-point expression, and the result of the expression is a oating point value (the term real expression is also used).
One of the most important aspects of programming is storing and manipulating the values stored in vari- ables. A variable is simply a name chosen by the programmer that is used to refer to computer storage locations. The term variable is used because the value stored in the variable can change, or vary. Variable names are also selected according to the rules of identiers:
Example: Some valid identiers my_variable Temperature x x _my_variable Some invalid identiers are as follows: %x1%my_var@x We should always give variables meaningful names, from which a reader might be able to make a reason- able guess at their purpose. We may use comments if further clarication is necessary.
3.1 Declaration Statements
Naming a variable and specifying the data type that can be stored in it is accomplished using declaration statement. A declaration statement in C++ programs has the following syntax: type name; The type portion refers to the data type of the variable. The data type determines the type of information that can be stored in the variable. Example: int sum; long datenem; double secnum; Note:
Example: int num = 15; float grade1 = 87.0; Variable declarations are just the instructions that tell the compiler to allocate memory locations for the variables to be used in a program. A variable declaration creates a memory location but it is undened to start with, that means it's empty. Example #include <iostream.h> int main() {
float price1 = 85.5; float price2 = 97.0; float total, average;
total = price1 + price2; average = total/2.0; // divide the total by 2. cout "The average price is " average endl; return 0; } The output of the above program: The average price is 91. Let notice the two statements in the above program: total = price1 + price2; average = total/2.0; Each of these statements is called an assignment statement because it tells the computer to assign (store) a value into a variable. Assignment statements always have an equal (=) sign and one variable name on the left of this sign. The value on the right of the equal sign is assigned to the variable on the left of the equal sign.
3.2 Display a Variable's Address
Every variable has three major items associated with it: its data type, its actual value stored in the variable and the address of the variable. The value stored in the variable is referred to as the variable's contents, while the address of the rst memory location used for the variable constitutes its address. To see the address of a variable, we can use address operator, &, which means the address of . For example, &num means the address of num. Example #include <iostream.h> int main() { int a;
a = 22; cout "The value stored in a is " a endl; cout "The address of a = " &a endl; return 0; } The output of the above program: The value stored in a is 22 The address of a = 0x0065FDF The display of addresses is in hexadecimal notation.
Portable languages like C++ must have exible data type sizes. Dierent applications might need integers of dierent sizes. C++ provides long integer, short integer, and unsigned integer data types. These three additional integer data types are obtained by adding the quantier long, short or unsigned to the normal integer declaration statements. Example: long int days; unsigned int num_of_days;
Ch = In1/2 + 1; // Right side = 65; assigns `A' to Ch In2 = Ch + 1; // Right side = 66; assigns 66 to In Real2 = In1/2; // Right side = 64; assigns 64.0 to Real In3 = Real1/2.0 // Right side = 6.17; truncates this value and assigns 6 to In The general rules for converting integer and oating point operands in mixed mode arithmetic expressions were presented as follows:
Notice that converting values to lower types can result in incorrect values. For example, the oating point value 4.5 gives the value 4 when it is converted to an integer value. The following table lists the built-in data types in order from highest type to lowest type.
4.2 Determining Storage Size
C++ provides an operator for determining the amount of storage your compiler allocates for each data type. This operator, called the sizeof() operator. Example: sizeof(num1) sizeof(int) sizeof(oat) The item in parentheses can be a variable or a data type. Example // Demonstrating the sizeof operator #include <iostream.h> int main() { char c; short s; int i; long l; float f; double d; long double ld; cout "sizeof c = " sizeof(c) "\tsizeof(char) = " sizeof( char ) "\nsizeof s = " sizeof(s) "\tsizeof(short) = " sizeof( short ) "\nsizeof i = " sizeof (i) "\tsizeof(int) = " sizeof( int ) "\nsizeof l = " sizeof(l) "\tsizeof(long) = " sizeof( long )
"\nsizeof f = " sizeof (f) "\tsizeof(float) = " sizeof(float) "\nsizeof d = " sizeof (d) "\tsizeof(double) = " sizeof(double) endl; return 0; } The output of the above program: sizeof c = 1sizeof(char) = 1 sizeof s = 2sizeof(short) = 2 sizeof i = 4sizeof(int) = 4 sizeof l = 4sizeof(long) = 4 sizeof f = 4sizeof(oat) = 4 sizeof d = 8sizeof(double) = 8
In this section, the software development procedure presented in the previous chapter is applied to a specic programming problem. This procedure can be applied to any programming problem to produce a completed program and forms the foundation for all programs developed in this text. Problem: Telephone Switching Networks A directly connected telephone network is one in which all telephones in the network are connected directly and do not require a central switching station to establish calls between two telephones. The number of direct lines needed to maintain a directly connected network for n telephones is given by the formula: lines = n(n-1)/ For example, directly connecting four telephones requires six individual lines. Using the formula, write a C++ program that determines the number of direct lines for 100 telephones and the additional lines required if 10 new telephones were added to the network. Use our top-down software development procedure.
5.1 Step 1: Analyze the Problem
For this program, two outputs are required: the number of direct lines required for 100 telephones and the additional lines needed when 10 new telephones are added to the existing network. The input item required for this problem is the number of telephones, which is denoted as n in the formula.
5.2 Step 2: Develop a Solution
The rst output is easily obtained using the given formula lines = n(n-1)/2. Although there is no formula given for additional lines, we can use the given formula to determine the total number of lines needed for 110 subscribers. Subtracting the number of lines for 100 subscribers from the number of lines needed for 110 subscribers then yields the number of additional lines required. Thus, the complete algorithm for our program, in pseudocode, is: Calculate the number of direct lines for 100 subscribers. Calculate the number of direct lines for 110 subscribers. Calculate the additional lined needed, which is the difference between the second and the first calculation. Display the number of lines for 100 subscribers. Display the additional lines needed.