0% found this document useful (0 votes)
15 views

C++ 2

The key steps to creating a C++ program are: 1. Write source code in a text editor with a .cpp extension. 2. Compile the source code into an object file with a .obj extension. 3. Link the object file with libraries to produce an executable program. The basic structure of a C++ program includes comments, preprocessor directives, function prototypes and definitions, and global variable declarations. It must also contain a main function which acts as the program entry point.

Uploaded by

eyob
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

C++ 2

The key steps to creating a C++ program are: 1. Write source code in a text editor with a .cpp extension. 2. Compile the source code into an object file with a .obj extension. 3. Link the object file with libraries to produce an executable program. The basic structure of a C++ program includes comments, preprocessor directives, function prototypes and definitions, and global variable declarations. It must also contain a main function which acts as the program entry point.

Uploaded by

eyob
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Chapter Two ASTU

C++ Basics
– Structure of C++ Program
A C++ program has the following structure
[Comments]
[Preprocessor directives]
[Global variable declarations]
[Prototypes of functions]
[Definitions of functions]

1
ASTU

– C++ IDE
• The complete development cycle in C++ is:
 Write the program,
 compile the source code,
 link the program,
 and run it.
Writing a Program
 To write a source code, your compiler may have its own built-in
text editor, or you may be using a commercial text editor or
word processor that can produce text file.
 The important thing is that whatever you write your program
in, it must save simple, plain-text files, with no word processing
commands embedded in the text.

2
ASTU

 Examples of safe editors include Windows


Notepad, the DOS Edit command, EMACS, and
vi. Many commercial word processors, such as
WordPerfect, Word, and dozens of others, also of-
fer a method for saving simple text files.
 The files you create with your editor are called
source files, and for C++ they typically are
named with the extension .cpp

3
ASTU

Compiling
 Your source code file can't be executed, or run, as
a program can.
 To turn your source code into a program, you use
a compiler.
 In Borland’s turbo C++ you pick the RUN menu
command or type

4
ASTU

Tc <filename>
 From the command line, where <filename> is the
name of your source code file (for example, tex-
t.cpp).
 Other compilers may do things slightly differently
 After your source is compiled an object file is
produced. This file is often named with the
extension .OBJ.
 this is still not an executable program, however. To
turn this into an executable program, you must run
your linker.
5
ASTU

Linking
 C++ programs are typically created by linking
together one or more OBJ files with one or more libraries.
 A library is a collection of linkable files that were
supplied with your compiler
 All C++ compilers come with a library of useful
functions (or procedures) and classes that you can
include in your program.
 A function is a block of code that performs a service,
such as adding two numbers or printing to the screen.
 A class is a collection of data and related functions.

6
Summary
ASTU

The steps to create an executable file are


1. Create a source code file, with a .CPP extension.
2. Compile the source code into a file with
the .OBJ extension.
3. Link your OBJ file with any needed libraries
to produce an executable program.

7
Showing Sample program
ASTU

 Any meaningful program written in C++ has to contain a number of


components:
the main function;
some variable declarations;
and some executable statements.
For example, the following is a very basic C++ program:
1: #include <iostream.h>
2:
3: int main()
4: {
5: cout << "Hello World!\n";
6: return 0;
7: }
8
ASTU

 On line 1, the file iostream.h is included in the file.


The first character is the # symbol, which is a signal to the
preprocessor.
 Each time you start your compiler, the preprocessor is run.
 The preprocessor reads through your source code,
looking for lines that begin with the pound symbol (#),
and acts on those lines before the compiler runs.
 include is a preprocessor instruction that says,
“What follows is a filename. Find that file and read it in right
here.”

9
ASTU

 The file iostream.h (Input-Output-Stream) is used by


cout, which assists with writing to the screen. The effect
of line 1 is to include the file iostream.h into this pro-
gram as if you had typed it in yourself.
 The preprocessor runs before your compiler each time
the compiler is invoked.
 The preprocessor translates any line that begins with a
pound symbol (#) into a special command, getting your
code file ready for the compiler.
 The angle brackets will cause the preprocessor to
look for the file iostream.h in the directory that holds all
the H files for your compiler
10
ASTU

 Line 3 begins the actual program with a function named


main().
 Every C++ program has a main() function.
In general, a function is a block of code that performs one
or more actions.
 Usually functions are invoked or called by other
functions, but main() is special. When your program
starts, main() is called automatically.
 main(), like all functions, must state what kind of value it
will return. The return value type for main() in HELLO.CPP
is int, which means that this function will return an integer
value.
11
ASTU

 All functions begin with an opening brace ({) and


end with a closing brace (}). The braces for the
main() function are on lines 4 and 7.
 Everything between the opening and closing
braces is considered a part of the function.
 The meat and potatoes of this program is on line 5
 The object cout is used to print a message to the
screen.
 cout is used in C++ to print strings and values to the
screen.
A string is just a set of characters.
12
ASTU

 Here's how cout is used: type the word cout, followed


by the output redirection operator (<<).
 If you want a string of characters written, be sure to en-
close them in double quotes ("), as shown on line 5.

 The final two characters, \n, tell cout to put a new line af-
ter the words Hello World!
 All ANSI-compliant programs declare main() to return an
int. This value is "returned" to the operating system
when your program completes. Some programmers signal
an error by returning the value 1.
 The main() function ends on line 7 with the
closing brace.
13
Basic Elements
ASTU

Keywords (reserved words)


 Reserved/Key words have a unique meaning within
a C++ program.
 These symbols, the reserved words, must not be
used for any other purposes.
 All reserved words are in lower-case letters.
The following are some of the reserved words of
C++.

14
ASTU

asm auto bool break case catch


const_cast Class const char continue default
dynamic_cast Do double delete else enum
explicit extern false float for friend
goto if inline int long mutable
namespace new operator Private protected public
reinterpret_cast Register return short signed sizeof
static_cast Static struct switch template this

throw true try typedef typeid typename

union Unsigned using virtual void volatile

wchar_t          

15
Identifiers
ASTU

 An identifier is name associated with a function or data


object and used to refer to that function or data object.
An identifier must:
 Start with a letter or underscore
 Consist only of letters, the digits 0-9, or the underscore
symbol ( _ )
 Not be a reserved word
 For the purposes of C++ identifiers, the underscore sym-
bol, _, is considered to be a letter. Its use as the first charac-
ter in an identifier is not recommended though, because
many library functions in C++ use such identifiers.
 Similarly, the use of two consecutive underscore
symbols, _ _, is forbidden. 16
ASTU

The following are valid identifiers


Although using _Pressure is not recommended.

Length days_in_year DataSet1 Profit95

Int _Pressure first_one first_1

The following are invalid:


• Although using _Pressure is not recommended.
• The following are invalid:
days-in-year 1data int first.val
Throw my__best No## bestWish!

17
ASTU

 C++ is case-sensitive. That is lower-case


letters are treated as distinct from upper-case
letters.
Thus the word NUM different from the
word num or the word Num.
 Identifiers can be used to identify variable or
constants or functions. Function identifier is
an identifier that is used to name a function.

18
Literals
ASTU
 Literals are constant values which can be a number, a character
of a string.
For example the number 129.005, the character ‘A’ and the string
“hello world” are all literals.
There is no identifier that identifies them.
Comments
 A comment is a piece of descriptive text which explains some
aspect of a program.
 Program comments are totally ignored by the compiler and are
only intended for human readers.
 C++ provides two types of comment
 Anything after // (until the end of the line on which it appears) is
considered a comment.
 Anything enclosed by the pair /* and */ is considered a comment.
19
Data Types, Variables, and Constants
ASTU

Variables
 A variable is a symbolic name for a memory location in which
data can be stored and subsequently recalled.
 Variables are used for holding data values so that they can be
utilized in various computations in a program. All variables
have two important attributes:
 A type, which is, established when the variable is defined
(e.g., integer, float, character). Once defined, the type of a C++
variable cannot be changed.
 A value, which can be changed by assigning a new value to the
variable. The kind of values a variable can assume depends on
its type. For example, an integer variable can only take integer
values (e.g., 2, 100, -12) not real numbers like 0.123.

20
Variable Declaration
ASTU

 Declaring a variable means defining (creating) a variable.


 You create or define a variable by stating its type, fol-
lowed by one or more spaces, followed by the variable
name and a semicolon.

 The variable name can be virtually any combination of


letters, but cannot contain spaces and the first character
must be a letter or an underscore.

 Variable names cannot also be the same as keywords used


by C++.

21
ASTU
 Legal variable names include x, J23qrsnf, and myAge.
 Good variable names tell you what the variables are for;
using good names makes it easier to understand the flow of
your program.
The following statement defines an integer variable called
myAge:
int myAge;
 IMPORTANT- Variables must be declared before used!
 As a general programming practice, avoid such horrific
names as J23qrsnf, and restrict single-letter variable names
 C++ is case-sensitive. In other words, uppercase and lower-
case letters are considered to be different. A variable named
age is different from Age, which is different from AGE.
22
Creating More Than One Variable at a Time
ASTU

 You can create more than one variable of the


same type in one statement by writing the
type and then the variable names, separated
by commas.
For example:
 int myAge, myWeight; // two int variables
 long area, width, length; // three longs
 keep in mind that you cannot mix types in one
definition statement.

23
Assigning Values to Your Variables
ASTU

You assign a value to a variable by using the


assignment operator (=). Thus, you would assign
5 to Width by writing
int Width;
Width = 5;
You can combine these steps and initialize Width
when you define it by writing
int Width = 5;

24
ASTU

 Just as you can define more than one variable at


a time, you can initialize more than one vari-
able at creation. For example:
// create two int variables and initialize them
int width = 5, length = 7;
 It is possible to even mix definitions and initial-
izations:
int myAge = 39, yourAge, hisAge = 40;
This example creates three type int variables, and it
initializes the first and third.
25
Basic Data Types
ASTU

 When you define a variable in C++, you must tell


the compiler what kind of variable it is: an inte-
ger, a character, and so forth.
 This information tells the compiler how much
room to set aside and what kind of value you want
to store in your variable.
 Several data types are built into C++. The vari-
eties of data types allow programmers to select
the type appropriate to the needs of the applica-
tions being developed.

26
ASTU

 The data types supported by C++ can be


classified as basic (fundamental) data types,
user defined data types, derived data types and
empty data types. However, the discussion
here will focus only on the basic data types.
 Basic (fundamental) data types in C++ can be
conveniently divided into numeric and
character types.

27
ASTU

 Numeric variables can further be divided into


integer variables and floating-point variables.
 Integer variables will hold only integers whereas
floating number variables can accommodate real
numbers.
 Both the numeric data types offer modifiers that are
used to vary the nature of the data to be stored. The
modifiers used can be short, long, signed & unsigned

28
The data types used in C++ programs ASTU

Type Size Values


unsigned short int 2 bytes 0 to 65,535
short int(signed short int) 2 bytes -32,768 to 32,767
unsigned long int 4 bytes 0 to 4,294,967,295
long int(signed long int) 4 bytes -2,147,483,648 to
2,147,483,647
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
signed int 2 bytes -32,768 to 32,767
Char 1 byte 256 character values
Float 4 bytes 3.4e-38 to 3.4e38
Double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.2e-4932 to 1.2e4932

Table C++ data types and their ranges


29
Signed and Unsigned
ASTU

 The idea here is that sometimes you need negative


numbers, and sometimes you don't.
 Integers (short and long) without the word "unsigned"
are assumed to be signed.
 Signed integers are either negative or positive.
 Unsigned integers are always positive.
 Because you have the same number of bytes for both
signed and unsigned integers, the largest number you
can store in an unsigned integer is twice as big as the
largest positive number you can store in a signed
integer.

30
A demonstration of the use of variables.
ASTU

#include <iostream.h>
int main()
{
unsigned short int Width = 5,Length;
Length = 10;
unsigned short int Area = Width * Length;
cout << "Width:" << Width << "\n";
cout << "Length: " << Length << endl;
cout << "Area: " << Area << endl;
return 0;
}
Output:
Width:5
Length: 10
Area: 50
31
Characters
ASTU

 Character variables (type char) are typically 1 byte,


enough to hold 256 values.
 A char can be interpreted as a small number (0-255) or
as a member of the ASCII set.
 ASCII stands for the American Standard Code for In-
formation Interchange. The ASCII character set and its
ISO (International Standards Organization) equivalent
are a way to encode all the letters, numerals, and
punctuation marks.
 In the ASCII code, the lowercase letter "a" is assigned
the value 97.

32
ASTU

 All the lower- and uppercase letters, all the


numerals, and all the punctuation marks are
assigned values between 1 and 128.
 Another 128 marks and symbols are reserved
for use by the computer maker, although the
IBM extended character set has become
something of a standard.

33
Operators
ASTU

 C++ provides operators for composing arithmetic,


relational, logical, bitwise, and conditional
expressions.
 It also provides operators which produce useful
side-effects, such as assignment, increment,
and decrement.

34
Assignment Operators
ASTU

 The assignment operator is used for storing a value at


some memory location (denoted by a variable).
 Its left operand should be an lvalue, and its right
operand may be an arbitrary expression.
 The latter is evaluated and the outcome is stored in
the location denoted by the lvalue.
 The only kind of lvalue we have seen so far is a
variable
 The assignment operator has a number of variants,
obtained by combining it with the arithmetic and
bitwise operators.

35
ASTU

Operator Example Equivalent To


 
= n = 25

+= n += 25 n = n + 25

-= n -= 25 n = n – 25

*= n *= 25 n = n * 25

/= n /= 25 n = n / 25

%= n %= 25 n = n % 25

36
ASTU

 An assignment operation is itself an expression whose


value is the value stored in its left operand.
 An assignment operation can therefore be used as the
right operand of another assignment operation.
For example:
int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = (n = p = 100) + 2;// means: m = (n = (p = 100)) + 2;
This is equally applicable to other forms of assignment.
For example:
m = 100;
m += n = p = 10; // means: m = m + (n = p = 10);
37
Arithmetic Operators
ASTU

C++ provides five basic arithmetic operators.


These are summarized in table below
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

Arithmetic operators.
38
ASTU

 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).
 Integer division always results in an integer
outcome (i.e., the result is always rounded
down).
39
ASTU

For example:
9 / 2 // gives 4, not 4.5!
-9 / 2 // gives -5, not -4!
 Unintended integer divisions are a common
source of programming errors.
 To obtain a real division when both operands are inte-
gers, you should cast one of the operands to be real:
int cost = 100;
int volume = 80;
double unitPrice = cost / (double) volume; // gives 1.25

40
ASTU

 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 illegal to divide a number by zero. This re-
sults in a run-time division-by-zero failure, which
typically causes the program to terminate.

41
ASTU

 There are also a number of predefined library


functions, which perform arithmetic operations.
 As with input & output statements, if you want
to use these you must put a #include statement
at the start of your program. Some of the more
common library functions are summarized
below.

42
ASTU

Parameter Result
Header File Function Type(s) Type Result

<stdlib.h> abs(i) Int int Absolute value of i


<math.h> cos(x) Float float Cosine of x (x is in ra-
dians)

<math.h> fabs(x) Float float Absolute value of x


<math.h> pow(x, y) Float float x raised to the power
of y
<math.h> sin(x) Float float Sine of x (x is in radi-
ans)
<math.h> sqrt(x) Float float Square root of x
<math.h> tan(x) Float float Tangent of x

43
Relational Operators
ASTU

 C++ provides six relational operators for comparing


numeric quantities.
 Relational operators evaluate to 1 (representing the true
outcome) or 0 (representing the false outcome).
 These are summarized in table below.
Operator Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
<  Less Than 5 < 5.5 // gives 1
<= Less Than or 5 <= 5 // gives 1
Equal
>  Greater Than 5 > 5.5 // gives 0
>= Greater Than or 6.3 >= 5 // gives 1
Equal
Relational operators
44
ASTU

 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.
45
ASTU

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 1, and is therefore
undefined.
 C++ provides library functions (e.g., strcmp)
for the lexicographic comparison of string.
46
Logical Operators
ASTU

 C++ provides three logical operators for combining


logical expression.
 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 1
|| Logical Or 5 < 6 || 6 < 5 // gives 1

Logical operators
47
ASTU

 Logical negation is a unary operator, which negates


the logical value of its single operand. If its operand
is nonzero it produces 0, and if it is 0 it produces 1.
 Logical and produces 0 if one or both of its oper-
ands 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.

48
ASTU

The following are, therefore, all valid logical expressions


!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
 C++ does not have a built-in boolean type. It is
customary to use the type int for this purpose
instead.
For example:
intsorted = 0; // false
intbalanced = 1; // true
49
Conditional Operator (?:)
ASTU
 The conditional operator takes three operands. It has the
general form:
Syntax:
operand1 ? operand2 : operand3
First operand1 is a relational expression and will be
evaluated. If the result of the evaluation is non-zero
(which means TRUE), then operand2 will be the final re-
sult.
Otherwise, operand3 is the final result.
E.g: General Example
Z=(X<Y? X : Y)
This expression means that if X is less than Y the value of X
will be assigned to Z otherwise (if X>=Y) the value of Y will
be assigned to Z. 50
Comma Operator (,)
ASTU

 Multiple expressions can be combined into one expression


using the comma operator.
 The comma operator takes two operands. Operand1,Operand2
 The comma operator can be used during multiple declaration,
for the condition operator and for function declaration, etc
E.g.
int m,n,min;
int mCount = 0, nCount = 0;
min = (m < n ? (mCount++ , m) : (nCount++ , n));
Here, when m is less than n, mCount++ is evaluated and the
value of m is stored in min. otherwise, nCount++ is evaluated
and the value of n is stored in min.

51
The sizeof() Operator
ASTU

 This operator is used for calculating the size of


any data item or type.
 It takes a single operand (e.g. 100) and returns the
size of the specified entity in bytes.
 The outcome is totally machine dependent.
E.g
a = sizeof(char)
b = sizeof(int)
c = sizeof(1.55)
etc
52
Increment/decrement Operators ASTU

 The a auto increment (++) and auto decrement (--)


operators provide a convenient way of, respectively,
adding and subtracting 1 from a numeric variable.
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
Increment and decrement operators

53
ASTU

 Both operators can be used in prefix and post-


fix 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.

54
ASTU
#include <iostream>
Using namespace std;
int main ()
{ int count = 10, 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
} 55
Precedence of Operators ASTU

 The order in which operators are evaluated in an


expression is significant and is determined by precedence
rules.
Operator type Operator
Unary !, ++ ,-- ,-
Arithmetic Multiplicative *, / ,%
+,-
Additive

Relational Inequality <, >, < =, > =


Equality == , !=

Logical And &&


Or ||
Conditional ?:
Assignment =, +=, -=, *=, /=, %=
56
E.g.
ASTU

a==b+c*d
c * d is evaluated first because * has a higher prece-
dence than + and = = The result is then added to b be-
cause + has a higher precedence than = = And then ==
is evaluated.
 Precedence rules can be overridden by using brackets.
E.g. rewriting the above expression as:
a = = (b + c) * d causes + to be evaluated before *.
Operators with the same precedence level are evaluated
in the order specified by the column on the table of
precedence rule.
E.g. a = b += c the evaluation order is right to left, so the
first b += c is evaluated followed by a = b.
57
Simple Type Conversion
ASTU

 A value in any of the built-in types we have see so


far can be converted (type-cast) to any of the other
types.
For example:
(int) 3.14 // converts 3.14 to an int to give 3
(long) 3.14 // converts 3.14 to a long to give 3L
(double) 2 // converts 2 to a double to give 2.0
(char) 122 // converts 122 to a char whose code is 122
(unsigned short) 3.14 // gives 3 as an unsigned short
int (3.14) // same as: (int) 3.14

58
Exercises
ASTU

 Find the average of two numbers given by the


user
 Swap the contents of two variables using a
third variable.

59

You might also like