Introduction and basic C++ programming Getting Started


For loops Here is an example of a simple for



Download 403.98 Kb.
Page3/3
Date28.05.2018
Size403.98 Kb.
#51778
1   2   3

For loops
Here is an example of a simple for loop that will print the numbers from 1 to 5.

int i;
for (i = 1; i <= 5; i = i + 1) // header of the loop

cout << i << endl; // body of the loop
Note that the header does not end in a semicolon because by itself it is not a complete C++ statement, just as the header of a main program is not one. The header is always followed by something called the body of the loop. The header together with the body is a complete C++ statement.

This simple for loop starts by giving an initial value to a variable (in our example, i), which we will call the index or control variable. The process of giving a variable an initial value is called initialization, and we say that i is initialized to 1. The for loop tells the computer to repeat the body of the loop, which in our example contains the single cout instruction, for several values of i. In this case, it will output the value i for i = 1, 2, 3, 4, and 5.


The for loop header specifies three things, separated by semicolons: what initial value to use, what test determines whether or not the loop should continue, and how the loop control variable should change (in this case, increment) each time through the body of the loop.
initial

value increment

 


for loop header: for (i = 1; i <= 5; i = i + 1)



test whether to



continue the loop
The for loop header is followed by the body of the loop. We are allowed to specify one statement that will be executed each time through the loop. In this case, that one statement is cout. Each time through the body of the loop, the current value of i is sent to cout. Then the new value of i, which is obtained by adding 1 to the previous value of i, is used to test the condition controlling the loop.

CAUTION:

Even though the increment step (i = i + 1) is contained in the header, it is executed after the body of the loop on each pass.




Tracing the for Loop
Now let's go step by step through the for loop. Going step by step is called tracing or hand simulating a program and is an extremely important programming tool.

PROGRAM TRACE:
The variable i starts at 1, which is compared to the final value of 5. Since 1 is less than or equal to 5, the program enters the body of the loop and sends the value of i to cout, printing 1. This completes the first pass through the for loop.
• Then we increment i by 1 to 2 and compare this new value to 5. Since 2 is less than or equal to 5, we execute the body of the loop. This time the program prints 2 on a new line. This completes the second pass.
• Then i increases to 3, which is less than or equal to the limiting value of the control variable (5), so we print 3.
• Similarly, i increases to 4, and we print 4.
• Then i increases to 5, which is also allowed since we test whether the current value is less than or equal to the final value. The program prints 5.
• Then i increases to 6. At this point, the condition i <= 5 is no longer true. Therefore, we do not enter the body of the loop when i has the value 6. Instead, the for loop is completed, and we continue with the next statement following the loop. In our example, since the body of the loop consists of a statement to print the value of i, the entire for loop prints the values 1, 2, 3, 4, and 5, each on a separate line.
A for Loop Using a Compound Statement
Let's look at a slightly more complicated example, which is very close to what we want to do in Problem 1. In this example, we will do two things inside the body of the for loop.
After the header in a for loop, we are allowed to execute only a single statement. However, a pair of braces is used in C++ whenever we want to execute a series of statements where normally just one is allowed. This entire series, called a compound statement, can then be treated as a single statement.
Example:

A loop to compute the expression i * i, store it in a variable called sq, then print both i and sq.


int i,sq;
for (i = 1; i <= 5; i = i + 1) {

sq = i * i;

cout << i << sq << endl;

}

Shorthand for Increments: ++ and --


Because increment statements are so common, C++ has a shortcut form that is almost always used. In the line below, the statement on the right is an abbreviation for the statement on the left.
i = i + 1; can be replaced by i++;
for (number = 4; number <= 9; number++)

In the same way, subtracting one from a variable can be abbreviated by using the decrement operator --. For example, these two statements are equivalent:


number = number - 1; and number--;

Once again, here is an example using a for loop header:

for (number = 9; number >= 4; number--)
Finally, the increment and decrement operators can also appear to the left of the variable name. In the case of a simple assignment statement (e.g., as part of a for loop header), these three statements have the same meaning:
i++; ++i; i = i + 1;
However, if the increment or decrement operator is used as part of a larger expression, there can be differences in meaning.
Int I = 4;

Cout << i++;

Cout <Output: 4 5
Int i=4;

Cout << ++i;

Count << i;
Output 5 5

Unary Increment/Decrement Operators


a++; same as a = a + 1; same as ++a;

a; same as a = a  1; same as a;


a++ postincrement

++a preincrement

a postdecrement

a predecrement


Example:
int c;

c = 5;


cout << c << endl; //prints 5

cout << c++ << endl; //prints 5 (then increments)

cout << c << endl << endl; //prints 6

c = 5;


cout << c << endl; //prints 5

cout << ++c << endl; //prints 6 (after incrementing)

cout << c << endl; //prints 6
Why was C++ named C++?

C++ was derived from C, so this is a cute pun since it’s an operation in these languages. C was called C because it was derived from the B language. B was derived from the language BCPL.

(why was java called java (c++++, oak, coffee) – programmers have strange sense of humor)

(SNOBOL, 1963, StriNg Oriented SymBOlic Language – originally called SEXI – String EXpression Interpreter – a little awkward as a programming language name).



If Statements
In pseudocode (structured English) we might express a decision as:
If student’s grade is greater than or equal to 60

Print “Passed”
In C++ this would be coded as:
if (grade >= 60)

cout << “Passed”;

Syntax for if statement:

if <boolean expression > <statement1> ;
A boolean expression represents a condition that is either true or false. It is formed using operands (constants, variables) and operators (arithmetic operators, relational operators, logical operators).

• If the condition is true, we execute the statement that follows [in this case, cout << "You Passed!" << endl, and continue processing.


result = 75;

if (result >= 60)

cout << "You Passed!";

cout << endl;


• If the condition is false, we simply skip that statement and "fall through" to the next instruction.
result = 45;

if (result >= 60)

cout << "You Passed!";

cout << endl;


In the example above, if result is greater than or equal to 0, we print the word "Admit," but if result is less than 0, we don't. Instead, we proceed to the next statement, which sends the cursor to a new line in all cases.

if (cond) // no semicolon here



stmt-1; // end of if statement

stmt-2; // next statement


Arithmetic

Relational

Logical

+ -

< less than > greater than

|| or

* / %

== equal to

!= not equal to



&& and

arithmetic functions

<= less than or equal to

>= greater than or equal to



! not

Ex. if ((x > 0) && (a == b)) …


Maybe this one:
Operator Precedence


Operator

Associativity

Type

( )

L  R

parenthesis

++ – – + – !

R  L

unary operators

* ? %

L  R

multiplicative

+ –

L  R

additive

<< >>

L  R

insertion

< <= > >=

L  R

relational

= = !=

L  R

equality

&&

L  R

and

||

L  R

or

?:

R  L

conditional

= += –= *= /= %=

R  L

assignment

Precedence of Arithmetic, Assignment, and Relational Operators

----------------------------------------------------------------------------------------

Associativity


highest precedence - (unary) + (unary) ++ -- right to left

(done first)

* / % left to right

+ - left to right


< <= > >= left to right

== != left to right


lowest precedence = += -= *= /= %= right to left

(done last)

-------------------------------------------------------------------------------------

for(num=1;num<10;num++)

sum = sum + num;

same as


for(num=1;num<10;num++)

sum += num;


(go through multiply, divide, etc)


Standard Library of Functions (math.h)
In addition to the five standard arithmetic operations (+, -, *, /, and %), C++ offers simple functions to perform other mathematical operations. These functions save us a lot of calculation; instead, the computer does most of the work. For example, sometimes we need the square root of a number. C++ has a function called sqrt() that automatically finds the square root.
double w,root;

w = 12;


root = sqrt(w + 7);

The expression sqrt(w + 7) finds the square root of w + 7. Since w has the value 12, the sqrt() function finds the square root of 19 (which is 4.36) and assigns it to root.


The function sqrt() is called a library function because its instructions are stored in a library. (Note: In C++, when referring to the name of a function, it is customary to use parentheses after the name; this distinguishes the name of a function from other types of identifiers.) The collection of these functions is called the standard library of functions or the C++ standard library.
The expression which invokes a function from the standard library is known as the call to the function or a function call. Typically, the function call specifies two things: the name of the function and the value or values on which the function should operate.

root = sqrt(w+7);

 

function value on which



name sqrt() should operate
A call to a library function can be placed on the right-hand side of an assignment statement, in a cout expression, or anywhere that an expression can occur. For example, here are some C++ statements that use library functions (we will explain ceil() and floor() in a moment):
a = sqrt(b);

cout << ceil(5.5);

z = x + floor(w);
#include

#include

using namespace std;

int main(){

cout << sqrt(25) << endl;

cout << ceil(5.5) << endl;

cout << floor(3.6) << endl;

system("pause");

}

output:


5

6

3


In addition to sqrt(), there are many other library functions. A useful one is abs(). The expression abs(x) finds the absolute value of the integer x, which in mathematics is written |x|. A call to abs() always returns a positive or 0 integer answer.

Talk about HW:
Math.h vs. cmath (sqrt)
#include
at the beginning of the program. If you use math.h, which is a C library, you will need to specify #include because C header files require .h. Using .h is not required for C++ header files, but it is for C header files.

Setw
Manipulator – function that is called in a nontraditional way. Manipulators area placed after the insertion operator.

Endl is a manipulator function. manipulator may or may not have arguments. We have others ex: setw.
Endl – means end of line. It does the same thing as appending the endline character ‘\n’ to the string itself.
Setw means set the output field width to 4 columns for the next output.
Cout << “Start” << setw(4) << 10 << setw(4) << 20 << setw(6) << 30;
Start 10 20 30
(2 spaces before the 10, two before the 20, and 4 before the 30).

Types
Integer Types

Integers stored in either 16 or 32 bits

Integer Types – signed and unsigned
Signed Integer – leftmost signbit is 0 if the number is positive or 0, and 1 if it’s negative.
Largest 16 bit integer is 32,767 (2 to 15 power – 1). 32-bit is 2,147,483,647 (2 to 31 power – 1).
Unsigned Integer – no sign bit. 16 bit= 65,535(2 to 16 power – 1)

32 bit = 4,294,967,295(2 to 32 power – 1)

default signed in C. we declare unsigned if want no sign bit. Useful for systems programming and low-level, machine-dependent applications. We’ll discuss later – (when dealing with long numbers – strings – converting)

Avoid unsigned for now


Long integers – A 16-bit integer with its upper limit of 32,767 may be too limited for many applications, C also provides long integers. (2,147,483,647)
Short integer – may need to save space at times by instructing the compiler to store a number in less space than normal.

Declarations
Constant declarations:

Used to associate meaningful names with constants -- items that will never change throughout execution of the program.


const float PI=3.14159;

Variable declarations:

Used to associate identifiers of a given type with memory cells used to store values of this type. - the values stored in the data cells are changeable.


char letter;

char letter1, letter2;

float x, y;

Data Type char
Char stands for character. A variable of this data type can hold any one character (e.g., 'a' or ' ' or '?'). A character is essentially anything that can be typed--a number, letter, space, period, or symbol. In addition, special characters like the tab character '\t' (used earlier in this chapter) and newline character '\n' (which can be used in place of endl) are values of type char.

( some computers (DOS PCs) the int set of values consists of all integers in the range –32,768 to 32,767.


There are nine int types:

short int unsigned short int char

int unsigned int signed char

long int unsigned long int unsigned char


The difference among these 9 types is the range of values they allow. These ranges may depend somewhat on the computer system.

short is the same as short int)

char type uses 8 bits to store a single character. Is actually numeric in that it stores the ASCII code value of the character. Character input is automatically converted; on output the value is converted to char first.

char

char c = 64;

cout << c << “ “; //prints ‘@’

c = c + 1; //increments c to 65

cout << c << “ “; //prints ‘A’

c = c + 1; //increments c to 66

cout << c << “ “; //prints ‘B’

c = c + 1; //increments c to 67

cout << c << “ “; //prints ‘C’


EXAMPLE 2-17:
char letter;
letter = 'a';

if (letter != 'b')

cout << "letter has the value " << letter << '\n';
Since letter is not equal to 'b', this example prints the following:
letter has the value a

Data type char is actually a subset of data type int. Each char value has a number associated with it, called its ASCII value; the ASCII values for characters range from 0 to 255. We could change the declaration in Example 2-17 to the following without altering the code:


int letter;
For a while, we will use characters only as part of strings to be printed, since a variable of type char by itself is not very useful (it can hold only one character).
convert to uppercase:
if(‘a’<=ch && ch <=’z’)

ch=ch – ‘a’ +’A’;


a=97

A=65
Real number types

float double long double

On most systems, double uses twice as many bytes as float. In general, float uses 4 bytes, double uses 8 bytes, and long double uses 8, 10, 12, or 16 bytes.

// Prints the amount of space each of the 12 fundamental types uses.
#include

using namespace std;

int main()

{

cout << "Number of bytes used:\n ";



cout << "\t char: " << sizeof(char) << endl;

cout << "\t short: " << sizeof(short) << endl;

cout << "\t int: " << sizeof(int) << endl;

cout << "\t long: " << sizeof(long) << endl;

cout << "\t unsigned char: " << sizeof(unsigned char) << endl;

cout << "\t unsigned short: " << sizeof(unsigned short) << endl;

cout << "\t unsigned int: " << sizeof(unsigned int) << endl;

cout << "\t unsigned long: " << sizeof(unsigned long) << endl;

cout << "\t signed char: " << sizeof(signed char) << endl;

cout << "\t float: " << sizeof(float) << endl;

cout << "\t double: " << sizeof(double) << endl;

cout << "\t long double: " << sizeof(long double) << endl;

system(“pause”);

return 0;

}

Output:
Number of bytes used:



char: 1

short: 2


int: 4

long: 4


unsigned char: 1

unsigned short: 2

unsigned int: 4

unsigned long: 4

signed char: 1

float: 4


double: 8

long double: 12

Press any key to continue . . .

Casting


Dividing two integers will give you an int result, you can change one to be a double to give you a double result.

If both of the operands in a division are variables:

int total_candy, number_of_people;

double candy_per_person;

#program sets total_candy to 9 and number_of_people to 2

candy_per_person = total_candy/number_of_people;


Unless you convert the value in one of the variables total_candy or number_of_people to a value of type double, the result of the division will be 4 and not 4.5 as it should be.
The fact that the variable candy_per_person is of type double doesn’t help. If one was a constant, you could add a decimal point and a zero to convert the constant to double, bu there both are variables.
In c++ we could convert:
double(9)

The type double can be used as if it were a predefined function that converts a value of some other type, such as 9, to a value of type double, 9.0. (it’s a kind of predefined function) It’s called type casting.


Double answer;

Answer = double(9)/2;


Rewrite earlier example:
int total_candy, number_of_people;

double candy_per_person;

#program sets total_candy to 9 and number_of_people to 2

candy_per_person = double(total_candy)/number_of_people;


Do the typecasting before you do the division. If you wait until after the division is completed then the digits after the decimal point are already lost.

If you use this the value will be 4.0 not 4.5:

candy_per_person = double(total_candy/number_of_people); // WRONG!

(C does (double)total_candy/number_of_people – this is the same idea – it does it on the total_candy not the whole thing. So that works too, but the other way is C++)



of

Download 403.98 Kb.

Share with your friends:
1   2   3




The database is protected by copyright ©ininet.org 2024
send message

    Main page