Nothing Special   »   [go: up one dir, main page]

C++ Chapter 2 Basic of C++

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 14

CHAPTER TWO

Basics of C++

The parts of a C++ Program.


To understand the basic parts of a simple program in C++, let’s have a look at the following
code:

#include<iostream.h>
#include<conio.h>
Void main()
{
cout<<”\n HelloW orld!”
getch();

}
Any C++ program file should be saved with file name extension “.CPP”
Type the program directly into the editor, and save the file as hello.cpp, compile it and then run
it. It will print the words Hello World! On the computer screen.
 The first character is the #. This character is a signal to the preprocessor. Each time you
start your compiler, the preprocessor runs through the program and looks for the pound (#)
symbols and act on those lines before the compiler runs.
 The include instruction is a preprocessor instruction that directs the compiler to include a
copy of the file specified in the angle brackets in the source code.
 If the path of the file is not specified, the preprocessor looks for the file under c:\tc\include\
folder or in include folder of the location where the editor is stored.
The effects of line 1, i.e. include<iostream.h> is to include the file iostream.h into the program
as if the programmer had actually typed it.
 When the program starts, main() is called automatically.
 Every C++ program has a main() function.
 The return value type for main() here is void, which means main function will not return a
value to the caller (which is the operating system).
 The main function can be made to return a value to the operating system.
 The Left French brace “{“signals the beginning of the main function body and the
corresponding Right French Brace “}” signals the end of the main function body. Every
Left French Brace needs to have a corresponding Right French Brace.
 The lines we find between the braces are statements or said to be the body of the function.
 A statement is a computation step which may produce a value or interact with input and
output streams.
 The end of a single statement ends with semicolon (;).
 The statement in the above example causes the sting “Hello World!” to be sent to the
“cout” stream which will display it on the computer screen.
A Brief look at cout and cin
 cout is an object used for printing data to the screen.
 To print a value to the screen, write the word cout, followed by the insertion operator also
called output redirection operator (<<) and the object to be printed on the screen.
 Syntax: cout<<Object;
 The object at the right hand side can be:
 A literal string: “Hello World”
 A variable: a place holder in memory
 cin is an object used for taking input from the keyboard.
 To take input from the keyboard, write the word cin, followed by the input redirection
operator (>>) and the object name to hold the input value.
 Syntax: cin>>Object
 cin will take value from the keyboard and store it in the memory.
Thus the cin statement needs a variable which is a reserved memory place holder.
Both << and >> return their right operand as their result, enabling multiple input or multiple
output operations to be combined into one statement. The following example will illustrate
how multiple input and output can be performed:
E.g.:
 cin>>var1>>var2>>var3;
Here three different values will be entered for the three variables. The input should be
separated by a space, tan or newline for each variable.
 cout<<var1<<”, “<<var2<<” and “<<var3;
Here the values of the three variables will be printed where there is a “,” (comma) between the
first and the second variables and the “and” word between the second and the third.
Putting Comments on C++ programs
 A comment is a piece of descriptive text which explains some aspect of a program.
Program comments are text totally ignored by the compiler and are only intended to inform the
reader how the source code is working at any particular point in the program.
 C++ provides two types of comment delimiters:
 Single Line Comment: Anything after // {double forward slash} (until the end of the line
on which it appears) is considered a comment.
Eg: cout<<var1; //this line prints the value of var1
 Multiple Line Comment: Anything enclosed by the pair /* and */ is considered a comment.
Eg: /*this is a kind of comment where Multiple lines can be enclosed in one C++ program
*/
Comments should be used to enhance (not to hinder) the readability of a program. The
following two points, in particular, should be noted:
 A comment should be easier to read and understand than the code which it tries to explain.
A confusing or unnecessarily-complex comment is worse than no comment at all.
 Over-use of comments can lead to even less readability. A program which contains so
much comment that you can hardly see the code can by no means be considered readable.
 Use of descriptive names for variables and other entities in a program, and proper
indentation of the code can reduce the need for using comments.
A brief look at functions
 In general, a function is a block of code that performs one or more actions.
 Most functions are called, or invoked, during the course of the program, which is after the
program starts execution.
 Program commands are executed line by line, in the order in which they appear in the
source code, until a function is reached. The program then branches off to execute the
function. When the function finishes, it returns control to the line of code immediately
following the call to the function.
 Functions consist of a header and a body. The header, in turn is made up of the return type,
the function name, and the parameters to that function.
 The parameters to a function allow values to be passed into the function. A parameter is a
declaration of the type of value that will be passed to the function; the actual value passed
by the calling function is called arguments.

Let us have an example:


#include<iostream.h>
#include<conio.h>
void main()
{
cout<<”\n In main function”;
demoFunction();
cout<<”\n Back in main function”;
getch();
}
void demoFunction()
{
cout<<”\nde moFunction”;
}

Functions return either a value or void (i.e. they return nothing).


 A function that adds two integers might return the sum, and thus would be defined to return
an integer value. A function that just prints a message has nothing to return and would be
declared to return void.
 A function may return a value using a return statement; a return statement also causes the
function to exit.
 If there is no return statement at the end of a function, the function will automatically return
void.
Variables and Constants.
Variables
 A variable is a reserved place in memory to store information in.
 A variable will have three components:
 Variables are used for holding data values so that they can be used in various
computations in a program.
 All variables have three important properties:
 Data Type: a type which is established when the variable is defined. (e.g. integer,
real, character etc). Data type describes the property of the data and the size of the
reserved memory.
 Name: a name which will be used to refer to the value in the variable. A unique
identifier for the reserved memory location.
 Value: a value which can be changed by assigning a new value to the variable
A variable is a symbolic name that can be given a variety of values. It represent a particular
place in the computer memory.
A variable can be of type integer, floating-point, and or character.

Basic C++ Variables


Key Word Numerical High Digits of Bytes of
Range: low precision Memory
Character Char -128 127 None 1
Integer int -32,768 32,767 None 2
long -2,147,483,648 2,147,483,647 None 4
Floating Point float 3.4*10 -38
3.4*10 +38
7 4
double 1.7 * 10 -308
1.7*10 +308
15 8
long double 3.4*10 -4932
1.1*10 +4932
19 10
Table 2.1 Basic variables
Unsigned Variables
By eliminating the sign of character and integer types you can change their
range to start at 0 and include only positive numbers. This allows them to
represent numbers twice as big as the signed versions.
Key Word Numerical High Digits of Bytes of
Range: low precision Memory
Character Char 0 255 None 1
Integer Int 0 65,535 None 2
Long 0 4,294,967,295 None 4
Table 2.2 Unsigned variables
Expressions

Expression is any statement or part of a statement that evaluates to a value (returns a value) as
a result of computation. A statement may have one or many expressions. Expressions are made
up of sequences of operators, operands in the form of constants and variables, and
punctuators, which specify a computation as per the rules of the underlying language i.e. their
arrangement should in a correct syntax based on the rule of the programming language used.
Expressions are evaluated based on the operators they contain and the context in which they
are used. All C++ statements end with a semicolon.

 White spaces: white spaces characters (spaces, tabs, new lines) can’t be seen and
generally ignored in statements. White spaces should be used to make programs more
readable and easier to maintain.
 Blocks: a block begins with an opening French brace ({) and ends with a closing
French brace (}).
 Expressions: an expression is a computation which yields a value. It can also be viewed
as any statement that evaluates to a value (returns a value).

Operator is a language specific syntactical token that requires an action to be taken. The
most familiar operators are drawn from mathematics. For example *(multiplication) is an
operator.
Operand receives an operation action. For any given operator there may be one, two or more
operands. There is no limit to the number of operators and operands that can be combined to
form expiration.
There are about 7 basic operator types in C++: arithmetic, assignment, increment/ decrement,
relational, conditional, sizeof and logical operators. These operators work on either a single
or two operands and so can be called either unary or binary based on the number of their
operands respectively.

1. Arithmetic Operators
C++ provides five basic arithmetic operators. These are summarized in Table 2.1.

Operator Name Example


+ Addition 12 + 4.9 // gives 16.9
- Subtraction 3.98 - 4 // gives -0.02
* Multiplication 2 * 3.4 // gives 6.8
/ Division 9 / 2.0 // gives 4.5
% Remainder 13 % 3 // gives 1

Table 2.3 Arithmetic operators.

Except for remainder (%) all other arithmetic operators can accept a mix of integer and real
operands. Generally, if both operands are integers then the result will be an integer. However,
if one or both of the operands are reals then the result will be a real (or double to be exact).
When both operands of the division operator (/) are integers then the division is performed as
an integer division and not the normal division we are used to. Integer division always results
in an integer outcome (i.e., the result is always rounded down). For example:
9 / 2 // gives 4, not 4.5!
-9 / 2 // gives -4, not -4.5!
Unintended integer divisions are a common source of programming errors. To obtain a real
division when both operands are integers, you should cast one of the operands to be real:

int cost = 100;


int volume = 80;
double unitPrice = cost / (double) volume; // gives 1.25

The remainder operator (%) expects integers for both of its operands. It returns the remainder
of integer-dividing the operands. For example 13%3 is calculated by integer dividing 13 by 3
to give an outcome of 4 and a remainder of 1; the result is therefore 1. It is possible for the
outcome of an arithmetic operation to be too large for storing in a designated variable. This
situation is called an overflow. The outcome of an overflow is machine-dependent and
therefore undefined.

It is illegal to divide a number by zero. This results in a run-time division-byzero failure which
typically causes the program to terminate.
The following example demonstrates the 5 basic arithmetic operations.
Example
#include<iostream.h>
#include<conio.h>
int main ( )
{
clrscr();
int a = 12;
int b = 6;
cout<< a << " + " << b << " = " << a + b << endl;
cout<< a << " - " << b << " = " << a - b << endl;
cout<< a << " * " << b << " = " << a * b << endl;
cout<< a << " / " << b << " = " << a / b << endl;
cout<< a << " % " << b << " = " << a % b << endl;
getch();
return 0;
}
2. Relational Operators
C++ provides six relational operators for comparing numeric quantities. These are summarized
in Table 2.2. Relational operators evaluate to 1 (representing the true outcome) or 0
(representing the false outcome).

Operator Name Example


== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
< Less Than 5 < 5.5 // gives 1
<= Less Than or Equal 5 <= 5 // gives 1
> Greater Than 5 > 5.5 // gives 0
>= Greater Than or Equal 6.3 >= 5 // gives 1
Table 2.4 Relational operators.

Note that the <= and >= operators are only supported in the form shown. In particular, =< and
=> are both invalid and do not mean anything. The operands of a relational operator must
evaluate to a number. Characters are valid operands since they are represented by numeric
values. For example (assuming ASCII coding):

'A' < 'F' // gives 1 (is like 65 < 70)

The relational operators should not be used for comparing strings, because this will result in
the string addresses being compared, not the string contents. For example, the expression
"HELLO" < "BYE"
causes the address of "HELLO" to be compared to the address of "BYE". As these addresses
are determined by the compiler (in a machine-dependent manner), the outcome may be 0 or
may be 1, and is therefore undefined. We will see their practical implementation in the next
chapter using statements.

Example
#include<iostream.h>
#include<conio.h>
int main ( )
{ clrscr();
int x;
cout<< Enter a number << endl;
cin>>x;

cout<< "\n the number you enter >10 is "<<x>10<< endl;


cout<< "the number you enter < 5 is "<<x<5<< endl;
cout<< "the number you enter >=5 is "<<x>=5<< endl;
cout<< "the number you enter !=5 is "<<x!=5<< endl;
cout<< "the number you enter ==5 is "<<x==5<< endl;
getch();
return 0;
}

3. Logical Operators
C++ provides three logical operators for combining logical expression. These are summarized
in Table 2.3. Like the relational operators, logical operators evaluate to 1 or 0.

Operator Name Example

! Logical Negation !(5 == 5) // gives 0


&& Logical And 5 < 6 && 6 < 6 // gives 0
|| Logical Or 5 < 6 || 6 < 5 // gives 1

Table 2.5 Logical operators.


Logical negation (!) is a unary operator, which negates the logical value of its single operand.
If its operand is nonzero it produce 0, and if it is 0 it produces 1.

Logical and (&&) produces 0 if one or both of its operands evaluate to 0. Otherwise, it
produces 1.

Logical or (||) produces 0 if both of its operands evaluate to 0. Otherwise, it produces 1.

Note that here we talk of zero and nonzero operands (not zero and 1). In general, any nonzero
value can be used to represent the logical true, whereas only zero represents the logical false.
The following are, therefore, all valid logical expressions:

Example
#include<iostream.h>
#include<conio.h>
int main ( )
{ clrscr();
int x;
int y;
x= 10<5 || 5>=10;
y = x>0;
cout<< !20 << endl;
cout<< (10 && 5)<< endl;
cout<< x << endl;
cout<< y<< endl;
getch();
}
4. Increment/Decrement Operators
The auto increment (++) and auto decrement (--) operators provide a convenient way of,
respectively, adding and subtracting 1 from a numeric variable. These are summarized in Table
2.4. The examples assume the following variable definition:

int k = 5;

Operator Name Example

++ Auto Increment (prefix) ++k + 10 // gives 16


++ Auto Increment (postfix) k++ + 10 // gives 15
-- Auto Decrement (prefix) --k + 10 // gives 14
-- Auto Decrement (postfix) k-- + 10 // gives 15

Table 2.6 Increment and decrement operators.


Both operators can be used in prefix and postfix form. The difference is significant. When
used in prefix form, the operator is first applied and the outcome is then used in the expression.
When used in the postfix form, the expression is evaluated first and then the operator applied.
Both operators may be applied to integer as well as real variables, although in practice real
variables are rarely useful in this form.
Example
#include <iostream.h>
#include<conio.h>
void main ()
{
clrscr();

int count = 10;


int dec=5;
cout <<"count = "<< count << endl; //displays 10
cout <<"dec = "<< dec << endl; //displays 5
cout<< "count = "<< ++count << endl; //displays 11 (prefix)
cout<< "dec = "<< --dec << endl; //displays 4 (prefix)
cout<<"count = " << count << endl; //displays 11
cout<<"dec = " << dec<< endl; //displays 4
cout<<"count = "<< count++<<endl; //displays 11 (postfix)
cout<<" dec = "<< dec--<<endl; //displays 4 (postfix)
cout<<"count = "<<count << endl; //displays 12
cout<<"dec = "<<dec << endl; //displays 3
getch();
}

5. Assignment Operator
The assignment expressions evaluate the operand on the right side of the operator (=) and
place its value in the variable on the left. The value on the right side may be a constant as in
the following example or a variable, or it may be an expression with a combination of
variable, constant and operators. There are two forms of assignments a simple and a
compound.

5.1 Simple assignment: a simple assignment is the assignment found in algebraic


expressions. The value of the expression on the right of the assignment operator is evaluated
and become the value of the total expression. The assignment operator then place the value in
the left operand.

Example
#include<iostream.h>
#include<conio.h>
void main( )
{
clrscr();
int num;
num1 = 20;
int num2 =num1 + 12;
cout<<”num1 =”<<num1<<endl;
cout<<”num2 =”<<num2<<endl;
getch();
}

The last statement in the above simple program assigns 20 to the variable num1.
In an assignation, operation evaluation always takes place from right to left. The statement x
= z; assigns to the variable x value that the variable z contains, irrespective of any previous
value which was stored in x. (i.e. if variable x has data in it previously, that will be replaced
by the new data contained in z )

e.g. a = b = c = 10;

The above statement first assigns the integer constant 10 to the variable c, then content of c
(that is 10) to b, then content of b (that is 10) to a and as a result the integer value 10 is
assigned to each of the three variables.
Note that if we assign z to x (by writing x = z), then at the time of assignment, x takes the
current value of z, and subsequent changes in the value of z will have no effect on the value
of x. This is to say that after the assignment expression x = z, if for instance we change the
value of variable z like z = 20, this will not affect the value of variable x in any way. This
fact is shown in the following program

Example
#include <iostream .h>
#include<conio.h>
void main( )
{ clrscr();
int a = 10;
int b = 5;
cout<<"a =" << a<<", b = "<<b<< endl;
a = b;
cout<<"a = " <<a<<", b = "<< b<< endl;
b = 7;
cout<<"a = " <<a<<", b = "<<b<<endl;
getch();}

5. 2 Compound assignment: a compound assignment is a shorthand notation for a


simple assignment. It implies that the left operand is repeated as a part of the right
expression. There are 5 compound assignment operator discussed in this chapter: -= , * = ,
/ = , += and % =. Table 2.5 demonstrates the compound expression with their equivalent
simple expression.

Compound Expression Equivalent Simple Expressions


x += y x= x + y
x -= y x= x - y
x *= y x= x * y
x /= y x= x / y
x %= y x= x % y
Table 2.7 compound assignment operators.
Example
num1 = 20;
num1 = num1 + 10;
The second statement above first adds 10 on num1, and assigns the result on itself , to make
num1 now 30.We can replace the last statement in the above example in the following
manner.
num1 + = 10;

Example
#include<iostream.h>
#include<conio.h>
int main ( )
{ clrscr();
int x=10;
int y=2;
cout<<" the value of the expression x+=y is: "<< x+=y<<endl;
cout<<" the value of the expression x-=y is: "<< x-=y<<endl;
cout<<" the value of the expression x/=y is: "<< x/=y<<endl;
cout<<" the value of the expression x*=y is: "<< x*=y<<endl;
cout<<" the value of the expression x%=y is: "<< x%=y<<endl;
getch();
return 0;
}

6. Conditional Operator
The conditional operator takes three operands. It has the general form:
operand1? operand2: operand3
First operand1 is evaluated, which is treated as a logical condition. If the result is nonzero then
operand2 is evaluated and its value is the final result. Otherwise, operand3 is evaluated and its
value is the final result.

Example
#include<iostream.h>
#include<conio.h>
int main ( )
{
clrscr();
int m = 1, n = 2;
int min = (m < n ? m : n); // min receives 1
cout <<"The minimum value is = :"<<min;
getch();
return 0;
}
Note that of the second and the third operands of the conditional operator only one is
evaluated. This may be significant when one or both contain side-effects (i.e., their evaluation
causes a c hange to the value of a variable).
For example, in int min = (m < n ? m++ : n++);
m is incremented because m++ is evaluated but n is not incremented because n++ is not
evaluated. Because a conditional operation is itself an expression, it may be used as an operand
of another conditional operation, that is, conditional expressions may be nested.

For example:
int m = 1, n = 2, p =3;
int min = (m < n ? (m < p ? m : p) : (n < p ? n : p));

7. The sizeof Operator


C++ provides a useful operator, sizeof, for calculating the size of any data item or type. It takes
a single operand which may be a type name (e.g., int) or an expression (e.g., 100) and returns
the size of the specified entity in bytes. The outcome is totally machine-dependent.

Example:
#include <iostream.h>
#include<conio.h>
int main ( )
{
clrscr();
cout << "char size = " << sizeof(char) << " bytes\n";
cout << "short size = " << sizeof(short) << " bytes\n";
cout << "int size = " << sizeof(int) << " bytes\n";
cout << "long size = " << sizeof(long) << " bytes\n";
cout << "float size = " << sizeof(float) << " bytes\n";
cout << "double size = " << sizeof(double) << " bytes\n";
cout << "1.55 size = " << sizeof(1.55) << " bytes\n";
cout << "1.55L size = " << sizeof(1.55L) << " bytes\n";
cout << "HELLO size = " << sizeof("HELLO") << " bytes\n";
getch();
return 0;
}
When run, the program will produce the following output (on the author’s PC):

char size = 1 bytes


short size = 2 bytes
int size = 2 bytes
long size = 4 bytes
float size = 4 bytes
double size = 8 bytes
1.55 size = 8 bytes
1.55L size = 10 bytes
HELLO size = 6 bytes
Operator Precedence
Let’s summarize the precedence situation for operators we have seen so far. The operators
higher on the list have higher precedence those lower down. Operators with higher precedence
are evaluated before those with lower precedence. Operators on the same row have equal
precedence. You can force an expression to be evaluated first by placing parenthesis () around
the expression.

Operator type Operator


Unary !, ++ ,-- ,-
Arithmetic Multiplicative *, / ,%
Additive +,-
Relational Inequality <, >, < =, > =
Equality == , !=
Logical And &&
Or ||
Conditional ?:
Assignment =, +=, -=, *=, /=, %=
Table 2.9 operator precidence
For example, in
1. a == b + c * d
c * d is evaluated first because * has a higher precedence than + and ==. The result is then
added to b because + has a higher precedence than ==, and then == is evaluated.
Precedence rules can be overridden using brackets. For example, rewriting the above
expression as
a == (b + c) * d
causes + to be evaluated before *.
a = b += c
The evaluation order is right to left, so first b += c is evaluated, followed by a = b.

Exercises

2.1 Write expressions for the following:

 To test if a number n is even.


 To test if a character c is a digit.
 To test if a character c is a letter.
 To do the test: n is odd and positive or n is even and negative.
 To give the absolute value of a number n.

2.2 Add extra brackets to the following expressions to explicitly show the order in which the
operators are evaluated:

(n <= p + q && n >= p - q || n == 0)


( (p < q ? n < p ? q * n - 2 : q / n + 1 : q - n)
2.3 What will be the value of each of the following variables after its initialization:
double d = 2 * int(3.14);
long k = 3.14 - 3;
char c = 'a' + 2;

2.4 Write a program which inputs a positive integer n and outputs 2 raised to the power of n.
 Hint: check the library functions in the <math.h> header file.

2.5 Write a program which inputs three numbers and outputs the message sorted if the
numbers are in ascending order, and outputs not sorted otherwise.

2.6 Write a program that accept an integer from the user and print the last digit of the entered
integer.

2.7 Write a program that accepts three numbers from the user and return the average of the
three numbers.

2.8 Write a program that accepts the temperature in F0 form and generate the C0 equivalent.
 Hint: C0 =(F0 – 32) 5/9

You might also like