0% found this document useful (0 votes)
32 views43 pages

Chapter 2

Uploaded by

abebemako302
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views43 pages

Chapter 2

Uploaded by

abebemako302
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

ü Structure of C++ Program

ü C++ IDE
ü Basic Elements
Ø Keywords (reserved words)
Ø Identifiers
Ø Literals
Ø Comments
ü Data type, Variable and Constants
ü Operators
ü Precedence of Operators
ü Simple Type Conversion
ü Statements
A C++ program has the following structure
P[Comments]
P[Preprocessor directives]
P[Global variable declarations]
P[Prototypes of functions]
P[Definitions of functions]
The complete development cycle in C++ is:
P Write the program,
P Compile the source code,
P Link the program, and
P Run it.
ü Write the program
Ø 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 files.
ØEx: Wins Notepad, the DOS Edit command, EMACS, &vi.
Ø Many commercial word processors, such as WordPerfect,
Word, and dozens of others, also offer a method for saving
simple text files.
ü Compile the source code
Ø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. After your source code 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.
ü Link the program
ØC++ programs are typically created by linking together one
or more OBJ files with one or more libraries.
P Finally, Run it.
ØPress F9 or use any related command to run the program.
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.
1: #include <iostream.h>
2:
3: int main ()
4: {
5: cout << "Hello Africa! \n";
6: return 0;
7 :}
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.
On Line 3
ü begins the actual program with a function named main().
ü Every C++ program has a main() function.
ü When your program starts, main() is called automatically.
On line 4 and 7,
ü All functions begin with an opening brace ({) and end with a
closing brace (}).
ü Everything between the opening and closing braces is
considered a part of the function.
2.4.1. Keywords (reserved words)
P Reserved/Key words have a unique meaning within a C++
program.
P These symbols, the reserved words, must not be used for any
other purposes.
P All reserved words are in lower-case letters.
2.4.2. Identifiers
P An identifier is name associated with a function or data
object and used to refer to that function or data object.
P 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
2.4.2. Identifiers
PValid Identifiers:
Length days_in_year DataSet1 Profit95
Int _Pressure first_one first_1

PInvalid Identifiers:

days-in-year 1data int first.val


throw my__best No## bestWish!
2.4.3. Literals
P Literals are constant values which can be a number, a character
of a string.
P For example the number 129.005, the character ‘A’ and the
string “hello world” are all literals.
2.4.4. 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 delimiters:
Ø Single Line //……………………………
Ø Multi Linie /*…………………………….*/
2.5.1. Variables
P A variable is a symbolic name for a memory location in which
data can be stored and subsequently recalled.
P All variables have two important attributes:
Ø A type
Ø A value
2.5.1. Variables
Variable Declaration
ü means defining (creating) a variable.
ü You create or define a variable by stating its type, followed by
one or more spaces, followed by the variable name and a
semicolon.
ü The following statement defines an integer variable called
myAge:
int myAge;
2.5.1. Variables
Creating More Than One Variable at a Time
P For example:
int myAge, myWeight; // two int variables
long area, width, length; // three longs
Assigning Values to Your Variables
PYou assign a value to a variable by using the assignment
operator (=).
P Thus, you would assign 5 to Width by writing
int Width;
Width = 5;
PYou can combine these steps and initialize Width when you
define it by writing : int Width = 5;
2.5.2. Basic Data Types
P When you define a variable in C++, you must tell the compiler
what kind of variable it is: an integer, a character, and so forth.
P This information tells the compiler how much room to set
aside and what kind of value you want to store in your variable.
P Several data types are built into C++.
2.5.2. Basic Data Types
P 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.
P However, the discussion here will focus only on the basic data
types.
2.5.2. Basic Data Types
ü Basic (fundamental) data types in C++ can be conveniently
divided into
Ø Numeric Type and
Ø integer variables will hold only integers
Ø floating-point variables can accommodate real numbers.
Ø Character types
ü The modifiers used can be short, long, signed and unsigned.
2.5.3. Signed and Unsigned
P Integer types come in two varieties: signed and unsigned.
P The idea here is that sometimes you need negative numbers,
and sometimes you don't.
P Integers (short and long) without the word "unsigned" are
assumed to be signed.
P Signed integers are either negative or positive.
P Unsigned integers are always positive.
2.5.4. Characters
P Character variables (type char) are typically 1 byte, enough to
hold 256 values.
P A char can be interpreted as a small number (0-255) or as a
member of the ASCII set.
2.5.5. Characters and Numbers
P When you put a character, for example, `a', into a char
variable, what is really there is just a number b/n 0 and 255.
P The value/letter relationship is arbitrary; there is no particular
reason that the lowercase "a" is assigned the value 97.
P It is important to realize, however, that there is a big d/f b/n the
value 5 and the character `5'. The latter is actually valued at 53,
much as the letter `a' is valued at 97.
P C++ provides operators for composing
Øarithmetic,
Ørelational,
Ølogical,
Øbitwise, and
Øconditional expressions.
P It also provides operators which produce useful side-effects,
such as assignment, increment, and decrement.
2.6. Operators
2.6.1. Assignment Operators
ü The assignment operator is used for storing a value at some
memory location (typically denoted by a variable).
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
2.6.2. Arithmetic Operators
P C++ provides five basic arithmetic operators.
P Except for remainder (%) all other arithmetic operators can
accept a mix of integer and real operands.
P 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).
2.6.2. Arithmetic Operators
P Integer division always results in an integer outcome (i.e.,
the result is always rounded down).
P For example:
9/2 // gives 4, not 4.5!
-9 / 2 // gives -5, not -4!
2.6.3. Relational Operators
ü 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
2.6.4. Logical Operators
ü 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
2.6.5. Increment/ Decreament Operators
P The auto increment (++) and auto decrement (--) operators
provide a convenient way of, respectively, adding and
subtracting 1 from a numeric variable.
P 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
2.6.5. Increment/ Decreament Operators
P Both operators can be used in prefix and postfix form.
P When used in prefix form, the operator is first applied and the
outcome is then used in the expression.
P When used in the postfix form, the expression is evaluated
first and then the operator applied.
ü 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.
PFor 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
P Statements represent the lowest-level building blocks of a
program.
P The order in which statements are executed is called flow
control (or control flow).
P C++ provides different forms of statements for different
purposes.
P C++ provides different forms of statements for different
purposes.
Ø Declaration statements are used for defining variables.
Ø Assignment-like statements are used for simple, algebraic
computations.
Ø Branching statements are used for specifying alternate paths
of execution, depending on the outcome of a logical condition.
Ø Loop statements are used for specifying computations which
need to be repeated until a certain logical condition is satisfied.
2.9. Statements
2.9.1. Input/Output Statements
P C++ provides two useful operators for this purpose: >> for
input and << for output.
Exercise 2.1
1. Write a C++ program that outputs the following text on screen:
Hint use endl or ‘\n’
Oh what
a happy day!
Oh yes,

2. Write a C++ program to prompt the user to input her/his name


and print this name on the screen, as shown below. The text
from keyboard can be read by using cin>> and to display the
text on the screen you can use cout<<.
Hello Girmay!.
Exercise 2.1
3. Write a C++ program to print the following lines:
You are number 1.
You are too young to study programming.
4. Write a C++ program to prompt the user to input 3 integer values
and print these values in forward and reversed order, as shown
below.
Please enter your 3 numbers: 12 45 78
Your numbers forward:
12
45
78
Your numbers reversed:
78
45
12
Exercise 2.1
5. Write a C++ program that two defines variables for floating-
point numbers and initializes them with the values 123.456 and
76.543 Then display the sum and the difference of these two
numbers on screen.
6. The sizeof operator can be used to determine the number of
bytes occupied in memory by a variable of a certain type. For
example, sizeof(short) is equivalent to 2. Write a C++ program
that displays the memory space required by each fundamental
type on screen.
Exercise 2.1
7. The following program contains several errors:
#include <stream>
int main
{
cout << "If this text",
cout >> " appears on your display, ";
cout << " endl;"
cout << 'you can pat yourself on '
<< " the back!" << endl.
return 0;
)
Resolve the errors and run the program to test your changes.
C u nxt Class!!!

You might also like