C++ Chapter 2 Basic of C++
C++ Chapter 2 Basic of C++
C++ Chapter 2 Basic of C++
Basics of C++
#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.
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.
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:
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).
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):
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;
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.
Logical and (&&) produces 0 if one or 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;
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.
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();}
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));
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):
Exercises
2.2 Add extra brackets to the following expressions to explicitly show the order in which the
operators are evaluated:
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